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 | ||
|
|
6a0a51313f | ||
|
|
639df1b8c5 | ||
|
|
1cdc365955 | ||
|
|
acbf7d5921 | ||
|
|
8efc526ca8 | ||
|
|
8246c09ab0 | ||
|
|
e5b65d9ed4 | ||
|
|
90700f1d59 | ||
|
|
dd6e7b8cb0 | ||
|
|
7eaff3c8bf | ||
|
|
faedb625c7 | ||
|
|
b0ff3efba9 | ||
|
|
b3c6ebad2e | ||
|
|
c61f74866c | ||
|
|
e559473fff | ||
|
|
2b40d7f507 | ||
|
|
fbf5537dcd | ||
|
|
def791ff59 | ||
|
|
d3fa1cc243 | ||
|
|
2b773eaac6 | ||
|
|
23e058e662 | ||
|
|
718c5a18d2 | ||
|
|
092192b824 | ||
|
|
ea56e8bf65 | ||
|
|
fd049f98db | ||
|
|
cbc9f070ec | ||
|
|
729ec2908d | ||
|
|
4e56387f31 | ||
|
|
037fb499e5 | ||
|
|
ebf115e1c3 | ||
|
|
3144489f34 | ||
|
|
6003a98754 | ||
|
|
47c926bd4a | ||
|
|
8a4f6990e7 | ||
|
|
c32d5e1c2f | ||
|
|
d00d549bd9 | ||
|
|
7ecc88e234 | ||
|
|
f6cda775be | ||
|
|
a9276cc89c | ||
|
|
e76cb197d0 | ||
|
|
b30c867087 | ||
|
|
c91d4ff3c7 | ||
|
|
eaf518a01d | ||
|
|
b5c8a72728 | ||
|
|
6543d3ad7d | ||
|
|
6e5ef8f6c0 | ||
|
|
23f9533124 | ||
|
|
a4a083658e |
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,12 +81,12 @@ 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
|
||||
@@ -93,6 +97,7 @@ 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
|
||||
+17
-1
@@ -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/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
|
||||
# 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
|
||||
+5
-2
@@ -26,8 +26,9 @@ share/python-wheels/
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
# Pytest / local temp
|
||||
backend/.pytest_tmp/
|
||||
.pytest_tmp/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
@@ -83,3 +84,5 @@ backend/data/kb/
|
||||
.pytest_cache/
|
||||
backend/data/fixed_assets/manifest.json
|
||||
backend/data/shipping_notice/
|
||||
backend/data/logs/
|
||||
backend/data/logs/*.log
|
||||
Vendored
+3
-2
@@ -1,7 +1,8 @@
|
||||
{
|
||||
// 后端 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": [
|
||||
|
||||
@@ -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) |
|
||||
@@ -5,6 +5,8 @@ FROM ${PYTHON_BASE_IMAGE}
|
||||
ARG APT_MIRROR=https://mirrors.aliyun.com
|
||||
ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple
|
||||
ARG PIP_EXTRA_INDEX_URL
|
||||
ARG PIP_TIMEOUT=300
|
||||
ARG PIP_RETRIES=15
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
+18
-3
@@ -3,7 +3,8 @@ backend/app/__init__.py
|
||||
|
||||
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
|
||||
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
|
||||
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;models/services 仍可通过 from app import db 引用。
|
||||
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter;
|
||||
并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。
|
||||
"""
|
||||
import logging
|
||||
import uuid
|
||||
@@ -56,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():
|
||||
|
||||
@@ -24,18 +24,22 @@ def register_blueprints(app: Flask) -> None:
|
||||
from app.api.user import user_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.maintenance import maintenance_bp
|
||||
from app.api.speech import speech_bp
|
||||
from app.api.training import training_admin_bp, training_user_bp
|
||||
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
|
||||
|
||||
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
|
||||
from app.api.kb import knowledge_base_bp
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
from app.api.workspace import (
|
||||
workspace_announcements_bp,
|
||||
workspace_file_check_bp,
|
||||
workspace_schedule_bp,
|
||||
workspace_shipping_notice_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, 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')
|
||||
@@ -46,10 +50,15 @@ def register_blueprints(app: Flask) -> None:
|
||||
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"),
|
||||
)
|
||||
)
|
||||
+121
-38
@@ -2,11 +2,13 @@
|
||||
backend/app/api/agents.py
|
||||
|
||||
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||
依赖:app.core.auth.jwt、models、minio_service。
|
||||
逻辑:按当前用户 RBAC 返回可访问 Agent;未登录 raise UnauthorizedError。
|
||||
依赖: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.core.auth.jwt import get_current_user
|
||||
@@ -19,45 +21,45 @@ from app.services.minio_service import minio_service
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
|
||||
def _serialize_agent_row(row) -> dict:
|
||||
return serialize_agent_list_item(row)
|
||||
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()
|
||||
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
|
||||
]
|
||||
|
||||
# [STEP 1] 按 extra_config 分类字段排序后序列化
|
||||
return jsonify([_serialize_agent_row(row) for row in sort_agent_rows(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):
|
||||
@@ -68,7 +70,12 @@ def list_agent_guides(agent_id):
|
||||
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:
|
||||
@@ -87,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,
|
||||
@@ -100,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 sort_agent_rows(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)
|
||||
|
||||
+283
-99
@@ -8,6 +8,8 @@ backend/app/api/chat.py
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
@@ -20,7 +22,9 @@ 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.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
@@ -37,15 +41,44 @@ from app.core.errors import (
|
||||
)
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
|
||||
SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent'
|
||||
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:
|
||||
@@ -53,18 +86,18 @@ def _session_title_from_text(text: str) -> str:
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
|
||||
def _user_facing_chat_query(text: str, agent_name: str | None = None) -> str:
|
||||
def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_name: 当前 Agent 名称,仅对发货通知 Agent 做工具名净化。
|
||||
agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_name or '').strip() != SHIPPING_NOTICE_AGENT_NAME:
|
||||
if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE:
|
||||
return value
|
||||
import re
|
||||
|
||||
@@ -195,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:
|
||||
"""
|
||||
@@ -259,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))
|
||||
@@ -275,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()
|
||||
@@ -932,10 +1019,10 @@ def get_chat_messages():
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_name = str(getattr(g.current_agent, 'name', '') or '').strip()
|
||||
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': _user_facing_chat_query(log.query, agent_name)})
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
@@ -951,7 +1038,7 @@ def get_chat_messages():
|
||||
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 [],
|
||||
@@ -985,6 +1072,9 @@ def save_local_message():
|
||||
if role == 'user':
|
||||
user_query = user_query or content
|
||||
content = ''
|
||||
else:
|
||||
# 本地生成的助手/表单消息不能携带 query;历史回放会把 query 渲染成用户气泡。
|
||||
user_query = ''
|
||||
|
||||
if not message_type:
|
||||
raise ValidationError('type is required')
|
||||
@@ -1098,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():
|
||||
@@ -1130,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:
|
||||
@@ -1163,6 +1337,19 @@ def chat_completions():
|
||||
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,
|
||||
@@ -1203,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, object] | 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(
|
||||
session.session_id,
|
||||
task_id=shipping_task_id,
|
||||
batch_no=shipping_batch_no,
|
||||
trigger_source="frontend_chat",
|
||||
request_id=request_id,
|
||||
)
|
||||
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,
|
||||
display_query=display_query,
|
||||
)
|
||||
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
|
||||
@@ -1306,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:
|
||||
@@ -1366,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'}
|
||||
@@ -1957,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',
|
||||
},
|
||||
)
|
||||
@@ -27,13 +27,19 @@ from app.core.errors import (
|
||||
)
|
||||
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"}
|
||||
@@ -41,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:
|
||||
@@ -57,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)
|
||||
@@ -65,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")
|
||||
@@ -77,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")
|
||||
|
||||
@@ -104,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():
|
||||
@@ -128,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:
|
||||
@@ -148,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}"
|
||||
|
||||
|
||||
@@ -268,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))
|
||||
|
||||
|
||||
@@ -289,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
|
||||
@@ -303,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)
|
||||
@@ -371,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,
|
||||
)
|
||||
+173
-102
@@ -1,126 +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.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
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
|
||||
@@ -130,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,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,10 +1,17 @@
|
||||
"""
|
||||
backend/app/api/schedule/__init__.py
|
||||
|
||||
用途:排程管理 Blueprint 入口(Wave 3:自 schedule_admin 单体迁入 _legacy)。
|
||||
依赖:schedule/_legacy.py(路由实现)、schedule/* services。
|
||||
逻辑:register_blueprints 从本包 import schedule_admin_bp;后续从 _legacy 拆 tasks.py / runs.py。
|
||||
用途:排程管理 Blueprint 入口(Wave 3 分包)。
|
||||
依赖:schedule/blueprint.py、config、tasks、runs、platform_tasks。
|
||||
逻辑:import 子模块注册路由;register_blueprints 从本包 import schedule_admin_bp。
|
||||
"""
|
||||
from app.api.schedule._legacy import schedule_admin_bp
|
||||
from app.api.schedule.blueprint import schedule_admin_bp
|
||||
|
||||
import app.api.schedule.common # noqa: F401
|
||||
import app.api.schedule.config # noqa: F401
|
||||
import app.api.schedule.tasks # noqa: F401
|
||||
import app.api.schedule.runs # noqa: F401
|
||||
import app.api.schedule.platform_tasks # noqa: F401
|
||||
import app.api.schedule.rpa_workers # noqa: F401
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -1,529 +0,0 @@
|
||||
"""
|
||||
backend/app/api/schedule/_legacy.py
|
||||
|
||||
用途:排程任务与运行记录管理 API(admin 域,Wave 3 迁包源文件)。
|
||||
依赖:app.core.decorators、app.core.auth.jwt、app.core.errors、schedule/* services。
|
||||
逻辑:管理员 CRUD ScheduleTask、触发运行、导出;后续拆至 schedule/tasks.py、runs.py。
|
||||
"""
|
||||
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.core.decorators import require_admin
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.core.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.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
|
||||
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
|
||||
|
||||
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')
|
||||
@@ -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,10 +1,10 @@
|
||||
"""
|
||||
backend/app/api/schedule_admin.py
|
||||
|
||||
用途:排程 admin API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.schedule._legacy。
|
||||
逻辑:旧 import 路径 `from app.api.schedule_admin import schedule_admin_bp` 仍可用;新代码请用 app.api.schedule。
|
||||
用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||
依赖:app.api.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。
|
||||
"""
|
||||
from app.api.schedule._legacy import schedule_admin_bp
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -33,6 +33,8 @@ from app.services.shipping_notice.query_service import (
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
@@ -80,7 +82,10 @@ def _tool_error_code(exc: AppError) -> str:
|
||||
@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():
|
||||
@@ -147,7 +152,7 @@ def tool_create_batch():
|
||||
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)
|
||||
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)})
|
||||
|
||||
@@ -257,6 +262,16 @@ def tool_submit_decision():
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_inventory_source', methods=['POST'])
|
||||
def tool_confirm_inventory_source():
|
||||
"""
|
||||
确认库存查询来源(仅提交 source_code)。
|
||||
【AI 触发时机】:用户在库存源人工检查点选择正式库存源后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_inventory_source(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
@@ -314,15 +329,51 @@ def tool_switch_focus_task():
|
||||
task = get_task_in_batch(batch_no, task_no)
|
||||
if not task:
|
||||
raise NotFoundError("task not found in batch")
|
||||
batch.current_focus_task_no = task.task_no
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source="tool_api",
|
||||
)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
|
||||
|
||||
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||
def rpa_worker_heartbeat():
|
||||
"""
|
||||
RPA Worker 心跳上报。
|
||||
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
|
||||
"""
|
||||
payload = _payload()
|
||||
try:
|
||||
worker = record_rpa_worker_heartbeat(payload)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
|
||||
def rpa_inventory_ready():
|
||||
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
|
||||
def rpa_inventory_batch_ready():
|
||||
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
def repair_task_inventory_attachment(task_no: str):
|
||||
"""
|
||||
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
|
||||
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
|
||||
"""
|
||||
payload = _payload()
|
||||
payload.setdefault("task_no", task_no)
|
||||
payload.setdefault("task_id", task_no)
|
||||
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
||||
|
||||
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
|
||||
@@ -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
|
||||
@@ -36,9 +36,14 @@ def _require_user():
|
||||
|
||||
|
||||
def _require_training_admin():
|
||||
"""确保当前用户具备培训管理权限。"""
|
||||
"""
|
||||
确保当前用户具备培训管理权限。
|
||||
|
||||
用途:统一拦截 HR 管理面板的数据查询、统计与导出接口。
|
||||
核心逻辑:优先复用 User.can_manage_training(),把“角色默认权限 + 前端可配置功能权限”收敛到同一个判断入口。
|
||||
"""
|
||||
user = _require_user()
|
||||
if user.role not in {"admin", "hr"}:
|
||||
if not user.can_manage_training():
|
||||
raise ForbiddenError("Training admin privilege required")
|
||||
return user
|
||||
|
||||
|
||||
+119
-500
@@ -3,13 +3,14 @@ backend/app/api/user.py
|
||||
|
||||
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、models、wecom/dify 相关 services。
|
||||
逻辑:薄路由层鉴权与参数校验;业务编排仍在本文件(Wave 3 拆至 api/user/* + services/user/*)。
|
||||
逻辑:薄路由层鉴权与参数校验;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.core.auth.jwt import get_current_user as _auth_current_user
|
||||
@@ -36,10 +37,12 @@ from app.core.errors import (
|
||||
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'}
|
||||
@@ -129,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())
|
||||
@@ -269,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(
|
||||
@@ -690,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):
|
||||
@@ -728,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
|
||||
@@ -796,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 = []
|
||||
@@ -866,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')
|
||||
@@ -1031,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 {}
|
||||
@@ -1087,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 ''
|
||||
@@ -1111,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
|
||||
@@ -1241,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')
|
||||
@@ -1298,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)}')
|
||||
|
||||
@@ -1345,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
|
||||
@@ -1371,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)
|
||||
@@ -1386,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')
|
||||
@@ -1648,9 +1342,9 @@ 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 if agent.is_active]
|
||||
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]
|
||||
@@ -1667,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': [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})
|
||||
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:
|
||||
@@ -1752,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():
|
||||
@@ -1927,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 {}
|
||||
@@ -1969,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,
|
||||
},
|
||||
@@ -2096,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)
|
||||
@@ -2127,16 +1821,12 @@ 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
|
||||
|
||||
try:
|
||||
@@ -2149,18 +1839,10 @@ def get_agent_details(id):
|
||||
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():
|
||||
@@ -2168,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,111 +1,18 @@
|
||||
"""
|
||||
backend/app/api/workspace_file_check.py
|
||||
|
||||
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、file_check_tools、schedule.query_service。
|
||||
逻辑:鉴权后查询 ScheduleRun 进度;参数缺失 raise ValidationError,资源缺失 raise NotFoundError。
|
||||
用途:工作台文件检核 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.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
|
||||
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)}
|
||||
|
||||
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")
|
||||
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,80 +1,10 @@
|
||||
"""
|
||||
backend/app/api/workspace_schedule.py
|
||||
|
||||
用途:工作台排程运行记录查询 API。
|
||||
依赖:app.core.auth.jwt、app.core.errors、schedule.query_service。
|
||||
逻辑:鉴权后只读查询 ScheduleRun;未登录 raise UnauthorizedError。
|
||||
用途:工作台排程 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.schedule。
|
||||
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from app.api.workspace.schedule import workspace_schedule_bp
|
||||
|
||||
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",
|
||||
)
|
||||
__all__ = ['workspace_schedule_bp']
|
||||
@@ -1,559 +1,10 @@
|
||||
"""
|
||||
api/workspace_shipping_notice.py
|
||||
backend/app/api/workspace_shipping_notice.py
|
||||
|
||||
用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload。
|
||||
逻辑:薄路由层做鉴权与参数校验(统一 raise AppError);业务编排下沉 shipping_notice service。
|
||||
用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。
|
||||
依赖:app.api.workspace.shipping_notice。
|
||||
逻辑:旧 import 路径继续 re-export `workspace_shipping_notice_bp`;真实实现统一维护在 workspace 子包中,避免双份路由漂移。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||
|
||||
from flask import Blueprint, 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.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.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,
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
|
||||
@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()
|
||||
batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter(
|
||||
(ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None))
|
||||
).all()
|
||||
return jsonify(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.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, '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 = _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)
|
||||
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 = _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()
|
||||
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')
|
||||
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 = _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 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:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=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>/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 extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload
|
||||
raw = upload.read() or b''
|
||||
filename = upload.filename or 'notice'
|
||||
saved_path = save_task_notice_upload(task.task_no, filename, raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else []
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
warnings.append(f'notice_text_truncated:{limit}')
|
||||
task.source_type = guess_source_type(filename) or task.source_type
|
||||
result = task_workflow.replace_task_notice(
|
||||
task,
|
||||
raw_text=text,
|
||||
source_file_name=filename,
|
||||
source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(),
|
||||
warnings=warnings,
|
||||
)
|
||||
data = result.setdefault('data', {})
|
||||
if isinstance(data, dict):
|
||||
data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})}
|
||||
return jsonify(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
"""返回指定任务的详情快照。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
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 = _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}))
|
||||
|
||||
@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}
|
||||
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-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))
|
||||
__all__ = ['workspace_shipping_notice_bp']
|
||||
@@ -1,11 +0,0 @@
|
||||
"""
|
||||
backend/app/auth_jwt.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.auth.jwt。
|
||||
依赖:app.core.auth.jwt。
|
||||
逻辑:Casdoor JWKS 校验与 get_current_user;新代码请 from app.core.auth.jwt import ...。
|
||||
"""
|
||||
|
||||
from app.core.auth.jwt import get_current_user, issue_local_access_token # noqa: F401
|
||||
|
||||
__all__ = ['get_current_user', 'issue_local_access_token']
|
||||
@@ -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,25 +0,0 @@
|
||||
"""
|
||||
backend/app/config.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.config.settings。
|
||||
依赖:app.core.config.settings。
|
||||
逻辑:环境文件加载与 Config 类;新代码请 from app.core.config.settings import config。
|
||||
"""
|
||||
|
||||
from app.core.config.settings import ( # noqa: F401
|
||||
ACTIVE_ENV_NAME,
|
||||
Config,
|
||||
DevelopmentConfig,
|
||||
ProductionConfig,
|
||||
TestingConfig,
|
||||
config,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'ACTIVE_ENV_NAME',
|
||||
'Config',
|
||||
'DevelopmentConfig',
|
||||
'ProductionConfig',
|
||||
'TestingConfig',
|
||||
'config',
|
||||
]
|
||||
@@ -2,8 +2,7 @@
|
||||
backend/app/core/__init__.py
|
||||
|
||||
用途:横切能力包入口(errors、response、auth、config、decorators)。
|
||||
逻辑:业务代码优先 from app.core.errors / app.core.auth.jwt 等子模块 import;
|
||||
app/errors.py 等根路径 shim 仅作存量兼容。
|
||||
逻辑:业务代码 from app.core.errors / app.core.auth.jwt 等子模块 import。
|
||||
"""
|
||||
|
||||
from app.core.errors import AppError # noqa: F401
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/core/auth/jwt.py
|
||||
|
||||
用途:Casdoor JWT 校验、legacy header 回退与当前用户解析。
|
||||
依赖:app.extensions.db、app.models.User、PyJWT、requests。
|
||||
逻辑:api 层与 decorators 调用 get_current_user();旧路径 app.auth_jwt 为兼容 shim。
|
||||
逻辑:api 层与 decorators 调用 get_current_user()。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -83,12 +83,6 @@ def _decode_jwt(token: str) -> dict:
|
||||
|
||||
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')
|
||||
@@ -233,14 +227,26 @@ def _legacy_header_user() -> Optional[User]:
|
||||
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)
|
||||
if cached is not 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()
|
||||
@@ -248,35 +254,41 @@ def get_current_user() -> Optional[User]:
|
||||
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:
|
||||
# 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 token_iss=%s token_aud=%s expected_iss=%s expected_aud=%s',
|
||||
'[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 token=%s path=%s', _token_brief(token), 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
|
||||
|
||||
@@ -8,7 +8,7 @@ backend/app/core/config/settings.py
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from dotenv import dotenv_values
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||
@@ -36,18 +36,25 @@ def _load_environment_files() -> str:
|
||||
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():
|
||||
load_dotenv(shared_file, override=False)
|
||||
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():
|
||||
load_dotenv(env_file, override=True)
|
||||
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():
|
||||
load_dotenv(local_file, override=True)
|
||||
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
|
||||
|
||||
|
||||
@@ -71,6 +78,8 @@ def _backend_path(env_key: str, *parts: str) -> str:
|
||||
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'))
|
||||
@@ -112,14 +121,20 @@ class Config:
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
# 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'
|
||||
@@ -145,11 +160,43 @@ class Config:
|
||||
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 '1'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
|
||||
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'
|
||||
@@ -170,6 +217,15 @@ class Config:
|
||||
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'
|
||||
)
|
||||
@@ -187,6 +243,12 @@ class Config:
|
||||
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"
|
||||
)
|
||||
@@ -282,6 +344,16 @@ class Config:
|
||||
)
|
||||
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'),
|
||||
@@ -298,6 +370,31 @@ class Config:
|
||||
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):
|
||||
@@ -318,6 +415,9 @@ class TestingConfig(Config):
|
||||
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 = {
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/core/decorators.py
|
||||
|
||||
用途:API 路由权限装饰器(admin、agent 权限)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.models。
|
||||
逻辑:api 路由使用 @require_admin、@require_agent_permission;旧路径 app.decorators 为兼容 shim。
|
||||
逻辑:api 路由使用 @require_admin、@require_agent_permission。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,10 +25,29 @@ def _get_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 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||
Args:
|
||||
f: 被装饰的视图函数。
|
||||
Returns:
|
||||
@@ -37,8 +56,7 @@ def require_agent_permission(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')
|
||||
agent_id = _resolve_request_agent_id()
|
||||
if not agent_id:
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/core/errors.py
|
||||
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
依赖:无 Flask 依赖。
|
||||
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler;旧路径 app.errors 为兼容 shim。
|
||||
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,9 +22,15 @@ class AppError(Exception):
|
||||
|
||||
|
||||
class ValidationError(AppError):
|
||||
def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Invalid request parameters",
|
||||
*,
|
||||
code: str = "VALIDATION.INVALID_PARAM",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code="VALIDATION.INVALID_PARAM",
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=400,
|
||||
details=details or {},
|
||||
@@ -38,13 +44,23 @@ class UnauthorizedError(AppError):
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
def __init__(self, message: str = "Forbidden"):
|
||||
super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False)
|
||||
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"):
|
||||
super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False)
|
||||
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):
|
||||
@@ -65,8 +81,42 @@ class ConflictError(AppError):
|
||||
|
||||
|
||||
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 __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:
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
"""
|
||||
backend/app/decorators.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.decorators。
|
||||
依赖:app.core.decorators。
|
||||
逻辑:@require_admin / @require_agent_permission;新代码请 from app.core.decorators import ...。
|
||||
"""
|
||||
|
||||
from app.core.decorators import ( # noqa: F401
|
||||
_get_current_user,
|
||||
require_admin,
|
||||
require_agent_permission,
|
||||
)
|
||||
|
||||
__all__ = ['require_admin', 'require_agent_permission', '_get_current_user']
|
||||
@@ -1,23 +0,0 @@
|
||||
"""
|
||||
backend/app/env_persistence.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.config.env_persistence。
|
||||
依赖:app.core.config.env_persistence。
|
||||
逻辑:WeCom 等运行时配置 DB 持久化;create_app before_request 调用 apply_env_settings。
|
||||
"""
|
||||
|
||||
from app.core.config.env_persistence import ( # noqa: F401
|
||||
BACKEND_ENV_PATH,
|
||||
LEGACY_BACKEND_ENV_PATH,
|
||||
ROOT_ENV_LOCAL_PATH,
|
||||
apply_env_settings,
|
||||
persist_env_settings,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'BACKEND_ENV_PATH',
|
||||
'LEGACY_BACKEND_ENV_PATH',
|
||||
'ROOT_ENV_LOCAL_PATH',
|
||||
'apply_env_settings',
|
||||
'persist_env_settings',
|
||||
]
|
||||
@@ -1,9 +0,0 @@
|
||||
"""
|
||||
backend/app/errors.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.errors。
|
||||
依赖:app.core.errors。
|
||||
逻辑:存量代码 from app.errors import ... 仍可用;新代码请改用 app.core.errors。
|
||||
"""
|
||||
|
||||
from app.core.errors import * # noqa: F403
|
||||
@@ -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
|
||||
@@ -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
|
||||
+757
-73
@@ -2,17 +2,25 @@
|
||||
backend/app/jobs/queue.py
|
||||
|
||||
用途:通用后台任务入队、领取与完成状态管理,并保留旧 KB 入队兼容入口。
|
||||
依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层。
|
||||
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环。
|
||||
依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层;
|
||||
shipping_notice Intake 仅在预解析 Job 被 queued 同伴取代时同事务重指 parse_job_id。
|
||||
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环;
|
||||
recover 使用 FOR UPDATE SKIP LOCKED + 条件 UPDATE;finish/fail 以 status/attempts 条件 UPDATE;
|
||||
enqueue 仅在 SAVEPOINT 内 add+flush,唯一冲突回落已有 Job;
|
||||
running→queued 若撞 shipping_notice_parse queued 唯一索引则标 cancelled;
|
||||
替代 Job 须 FOR UPDATE;仅 queued 或已真正持有 Intake lease 的 running 可 supersede。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
from datetime import datetime, timedelta
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy import update
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
@@ -20,7 +28,43 @@ from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
ACTIVE_STATUSES = ("queued", "running")
|
||||
QUEUED_ONLY_STATUSES = ("queued",)
|
||||
TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled")
|
||||
# 与 models.Job.uq_jobs_shipping_parse_queued_ref 对齐
|
||||
_PARSE_QUEUED_UNIQUE_TYPE = JobType.SHIPPING_NOTICE_PARSE.value
|
||||
|
||||
|
||||
def _orm_session() -> Session:
|
||||
"""
|
||||
取得底层 Session。
|
||||
|
||||
scoped_session 代理不转发 in_transaction/get_transaction,须解包后使用。
|
||||
"""
|
||||
return db.session()
|
||||
|
||||
|
||||
def _ensure_outer_dbapi_transaction(session: Session) -> None:
|
||||
"""
|
||||
确保 begin_nested() 不会成为数据库最外层事务。
|
||||
|
||||
核心逻辑:SQLite 在尚未 BEGIN 时执行 SAVEPOINT,随后 RELEASE 等价于 COMMIT,
|
||||
会破坏 commit=False / 外层 rollback。先 materialize 连接事务;SQLite 必要时
|
||||
显式 DBAPI BEGIN(已在事务中则忽略)。
|
||||
"""
|
||||
if not session.in_transaction():
|
||||
session.begin()
|
||||
bind = session.connection()
|
||||
if str(bind.dialect.name or "") != "sqlite":
|
||||
return
|
||||
dbapi_conn = bind.connection.dbapi_connection
|
||||
in_txn = getattr(dbapi_conn, "in_transaction", None)
|
||||
if callable(in_txn) and in_txn():
|
||||
return
|
||||
try:
|
||||
dbapi_conn.execute("BEGIN")
|
||||
except Exception:
|
||||
# 已在事务中:sqlite 会报错,可安全忽略
|
||||
pass
|
||||
|
||||
|
||||
def _normalize_job_type(job_type: JobType | str) -> str:
|
||||
@@ -28,6 +72,242 @@ def _normalize_job_type(job_type: JobType | str) -> str:
|
||||
return str(getattr(job_type, "value", job_type) or "").strip()
|
||||
|
||||
|
||||
def _subject_to_parse_queued_unique(job_type: str | None) -> bool:
|
||||
"""是否受 shipping_notice_parse queued 部分唯一索引约束。"""
|
||||
return str(job_type or "").strip() == _PARSE_QUEUED_UNIQUE_TYPE
|
||||
|
||||
|
||||
def _lock_other_active_parse_job(
|
||||
*,
|
||||
domain: str,
|
||||
job_type: str,
|
||||
business_ref: str | None,
|
||||
exclude_id: int,
|
||||
) -> Job | None:
|
||||
"""
|
||||
FOR UPDATE 锁定同业务锚点下优先级最高的 queued/running 预解析 Job。
|
||||
|
||||
核心逻辑:queued 受部分唯一索引保护且天然可安全替代,因此必须优先于
|
||||
running;仅无 queued 时才按最小 id 选择 running,并交由
|
||||
`_is_safe_supersede_target` 校验精确 Intake lease。持锁期间 Worker 的
|
||||
claim(SKIP LOCKED)会跳过最终候选。
|
||||
|
||||
Args:
|
||||
domain / job_type / business_ref: 与待降级 Job 相同的锚点。
|
||||
exclude_id: 排除自身主键。
|
||||
|
||||
Returns:
|
||||
锁定的最高优先级同伴;没有则 None。
|
||||
"""
|
||||
ref = str(business_ref or "").strip() or None
|
||||
if not ref:
|
||||
return None
|
||||
return (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == str(domain),
|
||||
Job.job_type == str(job_type),
|
||||
Job.business_ref == ref,
|
||||
Job.status.in_(("queued", "running")),
|
||||
Job.id != int(exclude_id),
|
||||
)
|
||||
.order_by((Job.status == "queued").desc(), Job.id.asc())
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _parse_lease_for_job(job: Job) -> str:
|
||||
"""构造 `{job_id}:{attempts}` 执行代次 lease。"""
|
||||
return f"{int(job.id)}:{int(job.attempts or 0)}"
|
||||
|
||||
|
||||
def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
|
||||
"""
|
||||
判定锁定的同伴是否可安全取代旧 running Job。
|
||||
|
||||
核心逻辑:
|
||||
- queued:可 supersede(旧取消,Intake 回到排队挂 keep);
|
||||
- running:仅当 Intake 已明确持有该 Job 的精确 parse_job_id + parse_lease
|
||||
(Worker 已真正 claim Intake)。否则可能 Worker 已按旧 id 决定 skip+finish,
|
||||
若此时伪造 lease 会导致 Intake 永久 parsing。
|
||||
|
||||
Returns:
|
||||
True 表示可取消旧 Job 并重指;False 表示应让旧 Job 正常 requeue。
|
||||
"""
|
||||
db.session.refresh(sibling)
|
||||
status = str(sibling.status or "")
|
||||
if status == "queued":
|
||||
return True
|
||||
if status != "running":
|
||||
return False
|
||||
|
||||
from app.models import ShippingNoticeIntake
|
||||
|
||||
intake_no = str(
|
||||
(cancelled_job.payload_json or {}).get("intake_no")
|
||||
or cancelled_job.business_ref
|
||||
or sibling.business_ref
|
||||
or ""
|
||||
).strip().upper()
|
||||
if not intake_no:
|
||||
return False
|
||||
locked = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == intake_no)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if locked is None:
|
||||
return False
|
||||
expected_lease = _parse_lease_for_job(sibling)
|
||||
return (
|
||||
str(locked.parse_status or "") == "parsing"
|
||||
and locked.parse_job_id is not None
|
||||
and int(locked.parse_job_id) == int(sibling.id)
|
||||
and str(locked.parse_lease or "") == expected_lease
|
||||
)
|
||||
|
||||
|
||||
def _resolve_safe_supersede_sibling(
|
||||
*,
|
||||
domain: str,
|
||||
job_type: str,
|
||||
business_ref: str | None,
|
||||
exclude_id: int,
|
||||
cancelled_job: Job,
|
||||
) -> Job | None:
|
||||
"""
|
||||
锁定同伴并过滤为可安全 supersede 的目标;不安全则视为无替代者。
|
||||
"""
|
||||
sibling = _lock_other_active_parse_job(
|
||||
domain=domain,
|
||||
job_type=job_type,
|
||||
business_ref=business_ref,
|
||||
exclude_id=exclude_id,
|
||||
)
|
||||
if sibling is None:
|
||||
return None
|
||||
if not _is_safe_supersede_target(sibling, cancelled_job=cancelled_job):
|
||||
return None
|
||||
return sibling
|
||||
|
||||
|
||||
def _retarget_intake_parse_job_after_supersede(
|
||||
*,
|
||||
cancelled_job: Job,
|
||||
keep_job: Job,
|
||||
) -> None:
|
||||
"""
|
||||
旧 running 预解析 Job 被安全同伴取代时,同事务重指 Intake.parse_job_id。
|
||||
|
||||
核心逻辑:FOR UPDATE Intake 后复检 keep_job.status——
|
||||
keep 仍为 queued:parsing→queued 并清 parse_lease;
|
||||
keep 已 running:仅在 Intake 已持有其精确 lease 时保留状态,绝不伪造 lease
|
||||
(否则会踩到已决定 skip+finish 的 Worker,造成永久 parsing)。
|
||||
"""
|
||||
if not _subject_to_parse_queued_unique(str(cancelled_job.job_type or "")):
|
||||
return
|
||||
from app.models import ShippingNoticeIntake
|
||||
|
||||
intake_no = str(
|
||||
(cancelled_job.payload_json or {}).get("intake_no")
|
||||
or cancelled_job.business_ref
|
||||
or ""
|
||||
).strip().upper()
|
||||
if not intake_no:
|
||||
return
|
||||
|
||||
# 锁内复检同伴状态(调用方应已 FOR UPDATE keep_job)
|
||||
db.session.refresh(keep_job)
|
||||
keep_status = str(keep_job.status or "")
|
||||
if keep_status not in {"queued", "running"}:
|
||||
return
|
||||
|
||||
locked = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == intake_no)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if locked is None:
|
||||
return
|
||||
current_job_id = int(locked.parse_job_id) if locked.parse_job_id is not None else None
|
||||
cancelled_id = int(cancelled_job.id)
|
||||
keep_id = int(keep_job.id)
|
||||
# 已指向第三方 Job:不抢占
|
||||
if current_job_id is not None and current_job_id not in {cancelled_id, keep_id}:
|
||||
return
|
||||
now = datetime.utcnow()
|
||||
current_lease = str(locked.parse_lease or "") or None
|
||||
status_now = str(locked.parse_status or "")
|
||||
|
||||
if keep_status == "queued":
|
||||
if current_job_id in {cancelled_id, None}:
|
||||
locked.parse_job_id = keep_id
|
||||
# 仅当仍挂旧 Job/旧代次时才打回 queued,避免清掉 keep 新 Worker 的 lease
|
||||
if status_now == "parsing" and (
|
||||
current_job_id == cancelled_id
|
||||
or current_lease is None
|
||||
or str(current_lease).startswith(f"{cancelled_id}:")
|
||||
):
|
||||
locked.parse_status = "queued"
|
||||
locked.parse_lease = None
|
||||
locked.updated_at = now
|
||||
return
|
||||
|
||||
# keep 已 running:只保留已真正接管的状态,禁止伪造 lease 转移
|
||||
keep_lease = _parse_lease_for_job(keep_job)
|
||||
if (
|
||||
status_now == "parsing"
|
||||
and current_job_id == keep_id
|
||||
and current_lease == keep_lease
|
||||
):
|
||||
locked.updated_at = now
|
||||
return
|
||||
# 未真正接管:调用方本不应 supersede;此处 no-op 防误伤
|
||||
return
|
||||
|
||||
|
||||
def _cancel_running_job_superseded(
|
||||
*,
|
||||
job_id: int,
|
||||
now: datetime,
|
||||
message: str,
|
||||
owned_attempt: int | None = None,
|
||||
snap_attempts: int | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
将仍为 running 的 Job 标为 cancelled(已被新 queued 取代)。
|
||||
|
||||
Returns:
|
||||
条件 UPDATE 影响行数。
|
||||
"""
|
||||
where = [Job.id == int(job_id), Job.status == "running"]
|
||||
if owned_attempt is not None:
|
||||
where.append(Job.attempts == int(owned_attempt))
|
||||
elif snap_attempts is not None:
|
||||
where.append(Job.attempts == int(snap_attempts))
|
||||
stmt = (
|
||||
update(Job)
|
||||
.where(*where)
|
||||
.values(
|
||||
status="cancelled",
|
||||
progress=100,
|
||||
message=str(message or "已被新的 queued Job 取代")[:500],
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
finished_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
return int(db.session.execute(stmt).rowcount or 0)
|
||||
|
||||
|
||||
def _worker_id() -> str:
|
||||
"""生成当前 worker 标识,用于锁记录和排障。"""
|
||||
try:
|
||||
@@ -103,12 +383,19 @@ def enqueue(
|
||||
max_attempts: int = 3,
|
||||
message: str | None = None,
|
||||
dedupe_active: bool = True,
|
||||
dedupe_statuses: Sequence[str] | None = None,
|
||||
commit: bool = True,
|
||||
correlation_id: str | None = None,
|
||||
scheduled_at: Any = None,
|
||||
) -> int:
|
||||
"""
|
||||
将任务写入通用 jobs 队列并返回 job id。
|
||||
|
||||
核心逻辑:先按 domain/type/business_ref + dedupe_statuses 查复用;
|
||||
无则 SAVEPOINT 插入。撞上 shipping_notice_parse 的 queued 部分唯一索引时
|
||||
IntegrityError 回读已有 Job(并发双插幂等)。commit=False 时不开自动提交,
|
||||
由调用方与业务行同事务提交。
|
||||
|
||||
Args:
|
||||
job_type: 任务类型。
|
||||
payload: JSON payload。
|
||||
@@ -118,7 +405,10 @@ def enqueue(
|
||||
priority: 优先级,数值越大越先执行。
|
||||
max_attempts: 最大尝试次数。
|
||||
message: 初始状态说明。
|
||||
dedupe_active: 是否复用 active 状态的同业务任务。
|
||||
dedupe_active: 是否复用同业务键下指定状态中的任务。
|
||||
dedupe_statuses: 去重匹配的 Job.status 集合;默认 queued+running。
|
||||
重试场景应传仅 queued,避免复用即将结束的 running Job。
|
||||
commit: False 时仅 flush,由调用方与业务行同一事务提交。
|
||||
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
|
||||
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
|
||||
"""
|
||||
@@ -139,20 +429,26 @@ def enqueue(
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("payload must be a dict")
|
||||
|
||||
if dedupe_active and normalized_ref:
|
||||
existing = (
|
||||
statuses = tuple(dedupe_statuses) if dedupe_statuses is not None else ACTIVE_STATUSES
|
||||
|
||||
def _find_active_dedupe_job() -> Job | None:
|
||||
if not (dedupe_active and normalized_ref and statuses):
|
||||
return None
|
||||
return (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == normalized_domain,
|
||||
Job.job_type == normalized_type,
|
||||
Job.business_ref == normalized_ref,
|
||||
Job.status.in_(ACTIVE_STATUSES),
|
||||
Job.status.in_(statuses),
|
||||
)
|
||||
.order_by(Job.created_at.desc(), Job.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
return int(existing.id)
|
||||
|
||||
existing = _find_active_dedupe_job()
|
||||
if existing is not None:
|
||||
return int(existing.id)
|
||||
|
||||
now = datetime.utcnow()
|
||||
queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now
|
||||
@@ -171,50 +467,207 @@ def enqueue(
|
||||
created_at=queue_at,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
# [STEP] SAVEPOINT 边界:仅在 begin_nested 内 add+flush。
|
||||
# begin_nested 会先 autoflush pending;若 Job 提前进入 Session,冲突会落在 SAVEPOINT 之外,
|
||||
# 毒化外层事务并在异常分支触发 PendingRollbackError。
|
||||
session = _orm_session()
|
||||
_ensure_outer_dbapi_transaction(session)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
session.add(job)
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
# SAVEPOINT 已回滚;确保失败对象不残留为 pending
|
||||
try:
|
||||
session.expunge(job)
|
||||
except Exception:
|
||||
pass
|
||||
# 即使 dedupe_active=False,唯一冲突仍须回落已有 queued(索引层幂等)
|
||||
raced = _find_active_dedupe_job()
|
||||
if raced is None and normalized_ref:
|
||||
raced = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == normalized_domain,
|
||||
Job.job_type == normalized_type,
|
||||
Job.business_ref == normalized_ref,
|
||||
Job.status == "queued",
|
||||
)
|
||||
.order_by(Job.id.asc())
|
||||
.first()
|
||||
)
|
||||
if raced is not None:
|
||||
return int(raced.id)
|
||||
raise
|
||||
if commit:
|
||||
session.commit()
|
||||
return int(job.id)
|
||||
|
||||
|
||||
def recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int:
|
||||
"""回收指定业务域内超时 running 的通用任务。"""
|
||||
def _job_id(job: Job | int) -> int:
|
||||
"""统一解析 Job 主键。"""
|
||||
return int(job if isinstance(job, int) else job.id)
|
||||
|
||||
|
||||
def recover_stale_jobs(
|
||||
*,
|
||||
domain: str,
|
||||
timeout_seconds: float,
|
||||
job_type: str | JobType | None = None,
|
||||
on_recovered: Callable[[Job], None] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
回收指定业务域内超时 running 的通用任务。
|
||||
|
||||
核心逻辑:FOR UPDATE SKIP LOCKED 领取待回收行,再以
|
||||
status=running AND attempts=快照 条件 UPDATE;同事务回调 on_recovered。
|
||||
多 Worker 并发回收时不会双写同一 Job,也不会把已被新 Worker 领取的代次打回 queued。
|
||||
若已存在同锚点 queued 同伴(parse 唯一索引),旧 Job 标 cancelled 并重指 Intake,
|
||||
每条更新包在 SAVEPOINT 内,避免单行 IntegrityError 毒化整批回收。
|
||||
|
||||
Args:
|
||||
on_recovered: 每条 Job 条件更新成功后、统一 commit 前的回调。
|
||||
"""
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=float(timeout_seconds))
|
||||
query = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == domain,
|
||||
Job.status == "running",
|
||||
Job.started_at.isnot(None),
|
||||
Job.started_at < cutoff,
|
||||
)
|
||||
query = db.session.query(Job).filter(
|
||||
Job.domain == domain,
|
||||
Job.status == "running",
|
||||
Job.started_at.isnot(None),
|
||||
Job.started_at < cutoff,
|
||||
)
|
||||
normalized_type = _normalize_job_type(job_type) if job_type else ""
|
||||
if normalized_type:
|
||||
query = query.filter(Job.job_type == normalized_type)
|
||||
stale_jobs = query.order_by(Job.started_at.asc(), Job.id.asc()).all()
|
||||
|
||||
try:
|
||||
stale_jobs = (
|
||||
query.order_by(Job.started_at.asc(), Job.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.all()
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
|
||||
if not stale_jobs:
|
||||
db.session.rollback()
|
||||
return 0
|
||||
|
||||
session = _orm_session()
|
||||
_ensure_outer_dbapi_transaction(session)
|
||||
now = datetime.utcnow()
|
||||
recovered = 0
|
||||
for job in stale_jobs:
|
||||
if int(job.attempts or 0) < int(job.max_attempts or 1):
|
||||
job.status = "queued"
|
||||
job.message = "任务执行超时,已回收等待重试"
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.started_at = None
|
||||
job.updated_at = now
|
||||
# 锁内复检:可能已被他事务终态化(本连接持锁期间一般仍为 running)
|
||||
if str(job.status or "") != "running":
|
||||
continue
|
||||
job.status = "failed"
|
||||
job.error_message = f"任务执行超时(超过 {int(timeout_seconds)}s)"
|
||||
job.message = job.error_message
|
||||
job.progress = 100
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.finished_at = now
|
||||
job.updated_at = now
|
||||
if job.started_at is None or job.started_at >= cutoff:
|
||||
continue
|
||||
snap_attempts = int(job.attempts or 0)
|
||||
max_attempts = int(job.max_attempts or 1)
|
||||
job_id = int(job.id)
|
||||
sibling: Job | None = None
|
||||
rowcount = 0
|
||||
|
||||
if snap_attempts < max_attempts:
|
||||
if _subject_to_parse_queued_unique(str(job.job_type or "")):
|
||||
try:
|
||||
sibling = _resolve_safe_supersede_sibling(
|
||||
domain=str(job.domain),
|
||||
job_type=str(job.job_type),
|
||||
business_ref=job.business_ref,
|
||||
exclude_id=job_id,
|
||||
cancelled_job=job,
|
||||
)
|
||||
except OperationalError:
|
||||
# 死锁会使整个事务失败;回滚后由下一轮回收重试
|
||||
db.session.rollback()
|
||||
return 0
|
||||
# [STEP] SAVEPOINT:queued 唯一冲突不得毁掉整批外层事务
|
||||
try:
|
||||
with session.begin_nested():
|
||||
if sibling is not None:
|
||||
rowcount = _cancel_running_job_superseded(
|
||||
job_id=job_id,
|
||||
now=now,
|
||||
message="超时回收:已存在安全替代解析 Job,旧 Job 已取消",
|
||||
snap_attempts=snap_attempts,
|
||||
)
|
||||
else:
|
||||
result = db.session.execute(
|
||||
update(Job)
|
||||
.where(
|
||||
Job.id == job_id,
|
||||
Job.status == "running",
|
||||
Job.attempts == snap_attempts,
|
||||
)
|
||||
.values(
|
||||
status="queued",
|
||||
message="任务执行超时,已回收等待重试",
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
rowcount = int(result.rowcount or 0)
|
||||
except IntegrityError:
|
||||
try:
|
||||
sibling = _resolve_safe_supersede_sibling(
|
||||
domain=str(job.domain),
|
||||
job_type=str(job.job_type),
|
||||
business_ref=job.business_ref,
|
||||
exclude_id=job_id,
|
||||
cancelled_job=job,
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
return 0
|
||||
if sibling is None:
|
||||
continue
|
||||
with session.begin_nested():
|
||||
rowcount = _cancel_running_job_superseded(
|
||||
job_id=job_id,
|
||||
now=now,
|
||||
message="超时回收:queued 唯一冲突,旧 Job 已取消",
|
||||
snap_attempts=snap_attempts,
|
||||
)
|
||||
else:
|
||||
timeout_msg = f"任务执行超时(超过 {int(timeout_seconds)}s)"
|
||||
result = db.session.execute(
|
||||
update(Job)
|
||||
.where(
|
||||
Job.id == job_id,
|
||||
Job.status == "running",
|
||||
Job.attempts == snap_attempts,
|
||||
)
|
||||
.values(
|
||||
status="failed",
|
||||
error_message=timeout_msg,
|
||||
message=timeout_msg,
|
||||
progress=100,
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
finished_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
rowcount = int(result.rowcount or 0)
|
||||
|
||||
if rowcount != 1:
|
||||
continue
|
||||
db.session.expire(job)
|
||||
db.session.refresh(job)
|
||||
if str(job.status or "") == "cancelled" and sibling is not None:
|
||||
_retarget_intake_parse_job_after_supersede(
|
||||
cancelled_job=job,
|
||||
keep_job=sibling,
|
||||
)
|
||||
if on_recovered is not None:
|
||||
on_recovered(job)
|
||||
recovered += 1
|
||||
db.session.commit()
|
||||
return len(stale_jobs)
|
||||
return recovered
|
||||
|
||||
|
||||
def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
|
||||
@@ -243,7 +696,8 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None,
|
||||
return None
|
||||
|
||||
job.status = "running"
|
||||
job.started_at = job.started_at or now
|
||||
# 每次领取刷新 started_at,避免 fail_job requeue 残留旧时间导致立刻被超时回收
|
||||
job.started_at = now
|
||||
job.locked_at = now
|
||||
job.locked_by = worker_id or _worker_id()
|
||||
job.attempts = int(job.attempts or 0) + 1
|
||||
@@ -254,35 +708,235 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None,
|
||||
return job
|
||||
|
||||
|
||||
def finish_job(job: Job, *, result: dict[str, Any] | None = None, message: str | None = None) -> None:
|
||||
"""标记任务成功完成。"""
|
||||
now = datetime.utcnow()
|
||||
job.status = "success"
|
||||
job.progress = 100
|
||||
job.result_json = result or {}
|
||||
job.message = message or "任务处理完成"
|
||||
job.error_message = None
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.finished_at = now
|
||||
job.updated_at = now
|
||||
db.session.commit()
|
||||
def _sync_parse_intake_after_job_mutation(job_id: int) -> None:
|
||||
"""
|
||||
shipping_notice_parse Job 状态变更后同步 Intake(同事务、commit 前)。
|
||||
|
||||
核心逻辑:委托 sync_intake_after_parse_job_recovery,覆盖 requeue→queued、
|
||||
failed→parse_failed、cancelled→安全重指/终态清理,避免 Intake 永久 parsing。
|
||||
"""
|
||||
job = db.session.get(Job, int(job_id))
|
||||
if job is None or not _subject_to_parse_queued_unique(str(job.job_type or "")):
|
||||
return
|
||||
db.session.expire(job)
|
||||
db.session.refresh(job)
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
sync_intake_after_parse_job_recovery,
|
||||
)
|
||||
|
||||
sync_intake_after_parse_job_recovery(job)
|
||||
|
||||
|
||||
def fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None:
|
||||
"""标记任务失败;retryable 且未达上限时重新排队。"""
|
||||
def finish_job(
|
||||
job: Job | int,
|
||||
*,
|
||||
result: dict[str, Any] | None = None,
|
||||
message: str | None = None,
|
||||
owned_attempt: int | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
条件收口为 success:仅当 Job 仍为 running(且可选 attempts 匹配)时生效。
|
||||
|
||||
Returns:
|
||||
是否实际更新到一行(False 表示代次失效或已非 running,调用方应视为 no-op)。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
can_retry = retryable and int(job.attempts or 0) < int(job.max_attempts or 1)
|
||||
job.status = "queued" if can_retry else "failed"
|
||||
job.progress = 0 if can_retry else 100
|
||||
job.result_json = result or {}
|
||||
job.error_message = str(error or "job failed")[:1000]
|
||||
job.message = "任务失败,等待重试" if can_retry else job.error_message
|
||||
job.locked_by = None
|
||||
job.locked_at = None
|
||||
job.finished_at = None if can_retry else now
|
||||
job.updated_at = now
|
||||
job_id = _job_id(job)
|
||||
where = [Job.id == job_id, Job.status == "running"]
|
||||
if owned_attempt is not None:
|
||||
where.append(Job.attempts == int(owned_attempt))
|
||||
stmt = (
|
||||
update(Job)
|
||||
.where(*where)
|
||||
.values(
|
||||
status="success",
|
||||
progress=100,
|
||||
result_json=result or {},
|
||||
message=message or "任务处理完成",
|
||||
error_message=None,
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
finished_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
rowcount = int(db.session.execute(stmt).rowcount or 0)
|
||||
db.session.commit()
|
||||
cached = db.session.get(Job, job_id)
|
||||
if cached is not None:
|
||||
db.session.expire(cached)
|
||||
return rowcount == 1
|
||||
|
||||
|
||||
def fail_job(
|
||||
job: Job | int,
|
||||
*,
|
||||
error: str,
|
||||
result: dict[str, Any] | None = None,
|
||||
retryable: bool = False,
|
||||
owned_attempt: int | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
条件收口失败:仅 running(且可选 attempts 匹配)时改 queued/failed/cancelled。
|
||||
|
||||
核心逻辑:retryable 且 attempts 未耗尽时,优先安全 supersede,否则 requeue
|
||||
(清空 started_at)并同步 Intake;唯一冲突窗口消失时保持 running 返回 False,
|
||||
禁止误标 failed。attempts 耗尽则 failed 并同步 Intake 离开 parsing。
|
||||
|
||||
Returns:
|
||||
是否实际更新到一行。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
job_id = _job_id(job)
|
||||
error_text = str(error or "job failed")[:1000]
|
||||
payload = result or {}
|
||||
base_where = [Job.id == job_id, Job.status == "running"]
|
||||
if owned_attempt is not None:
|
||||
base_where.append(Job.attempts == int(owned_attempt))
|
||||
|
||||
session = _orm_session()
|
||||
_ensure_outer_dbapi_transaction(session)
|
||||
|
||||
def _expire_cached() -> None:
|
||||
cached = db.session.get(Job, job_id)
|
||||
if cached is not None:
|
||||
db.session.expire(cached)
|
||||
|
||||
if retryable:
|
||||
# 先锁住自身 running 行,再锁同伴,缩短无锁窗口且便于复检 attempts
|
||||
job_row = (
|
||||
db.session.query(Job)
|
||||
.filter(Job.id == job_id, Job.status == "running")
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
sibling: Job | None = None
|
||||
if job_row is not None and _subject_to_parse_queued_unique(str(job_row.job_type or "")):
|
||||
try:
|
||||
sibling = _resolve_safe_supersede_sibling(
|
||||
domain=str(job_row.domain),
|
||||
job_type=str(job_row.job_type),
|
||||
business_ref=job_row.business_ref,
|
||||
exclude_id=job_id,
|
||||
cancelled_job=job_row,
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
return False
|
||||
|
||||
attempts_ok = (
|
||||
job_row is not None
|
||||
and int(job_row.attempts or 0) < int(job_row.max_attempts or 1)
|
||||
)
|
||||
if sibling is not None and attempts_ok:
|
||||
# 仅安全替代者:取消旧 Job(running 且已真正接管 Intake,或仍为 queued)
|
||||
rowcount = _cancel_running_job_superseded(
|
||||
job_id=job_id,
|
||||
now=now,
|
||||
message="失败重试:已存在安全替代解析 Job,旧 Job 已取消",
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
if rowcount == 1:
|
||||
cancelled = db.session.get(Job, job_id)
|
||||
if cancelled is not None:
|
||||
_retarget_intake_parse_job_after_supersede(
|
||||
cancelled_job=cancelled,
|
||||
keep_job=sibling,
|
||||
)
|
||||
_sync_parse_intake_after_job_mutation(job_id)
|
||||
db.session.commit()
|
||||
_expire_cached()
|
||||
return True
|
||||
elif sibling is None and attempts_ok:
|
||||
# 无安全替代(含:同伴 running 但尚未 claim Intake)→ 正常 requeue
|
||||
requeue_stmt = (
|
||||
update(Job)
|
||||
.where(*base_where, Job.attempts < Job.max_attempts)
|
||||
.values(
|
||||
status="queued",
|
||||
progress=0,
|
||||
result_json=payload,
|
||||
error_message=error_text,
|
||||
message="任务失败,等待重试",
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
finished_at=None,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
rowcount = int(db.session.execute(requeue_stmt).rowcount or 0)
|
||||
except IntegrityError:
|
||||
try:
|
||||
sibling = (
|
||||
_resolve_safe_supersede_sibling(
|
||||
domain=str(job_row.domain),
|
||||
job_type=str(job_row.job_type),
|
||||
business_ref=job_row.business_ref,
|
||||
exclude_id=job_id,
|
||||
cancelled_job=job_row,
|
||||
)
|
||||
if job_row is not None
|
||||
else None
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
return False
|
||||
if sibling is None:
|
||||
# 唯一冲突窗口已消失:保持 running,勿强行 failed 造成永久 parsing
|
||||
db.session.rollback()
|
||||
return False
|
||||
with session.begin_nested():
|
||||
rowcount = _cancel_running_job_superseded(
|
||||
job_id=job_id,
|
||||
now=now,
|
||||
message="失败重试:queued 唯一冲突,旧 Job 已取消",
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
if rowcount == 1:
|
||||
cancelled = db.session.get(Job, job_id)
|
||||
if cancelled is not None:
|
||||
_retarget_intake_parse_job_after_supersede(
|
||||
cancelled_job=cancelled,
|
||||
keep_job=sibling,
|
||||
)
|
||||
_sync_parse_intake_after_job_mutation(job_id)
|
||||
db.session.commit()
|
||||
_expire_cached()
|
||||
return True
|
||||
else:
|
||||
if rowcount == 1:
|
||||
_sync_parse_intake_after_job_mutation(job_id)
|
||||
db.session.commit()
|
||||
_expire_cached()
|
||||
return True
|
||||
|
||||
# 终态 failed:同步 Intake 离开 parsing,避免永久卡住
|
||||
fail_stmt = (
|
||||
update(Job)
|
||||
.where(*base_where)
|
||||
.values(
|
||||
status="failed",
|
||||
progress=100,
|
||||
result_json=payload,
|
||||
error_message=error_text,
|
||||
message=error_text,
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
finished_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
rowcount = int(db.session.execute(fail_stmt).rowcount or 0)
|
||||
if rowcount == 1:
|
||||
_sync_parse_intake_after_job_mutation(job_id)
|
||||
db.session.commit()
|
||||
_expire_cached()
|
||||
return rowcount == 1
|
||||
|
||||
|
||||
def process_next_job(
|
||||
@@ -293,7 +947,12 @@ def process_next_job(
|
||||
timeout_config_key: str | None = None,
|
||||
default_timeout_seconds: float = 300,
|
||||
) -> tuple[bool, str]:
|
||||
"""领取并分发一条通用任务。"""
|
||||
"""
|
||||
领取并分发一条通用任务。
|
||||
|
||||
核心逻辑:超时回收必须与本次允许领取的 job_types 同范围,避免同 domain
|
||||
下其他类型被错误阈值或缺少业务回调的入口提前回收;未指定类型时才回收整个 domain。
|
||||
"""
|
||||
import app.jobs.handlers # noqa: F401
|
||||
from app.jobs.registry import get_handler
|
||||
|
||||
@@ -302,29 +961,54 @@ def process_next_job(
|
||||
if timeout_config_key
|
||||
else default_timeout_seconds
|
||||
)
|
||||
recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
|
||||
normalized_types = list(
|
||||
dict.fromkeys(
|
||||
_normalize_job_type(item)
|
||||
for item in (job_types or [])
|
||||
if _normalize_job_type(item)
|
||||
)
|
||||
)
|
||||
if normalized_types:
|
||||
for normalized_type in normalized_types:
|
||||
on_recovered = None
|
||||
if normalized_type == JobType.SHIPPING_NOTICE_PARSE.value:
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
sync_intake_after_parse_job_recovery,
|
||||
)
|
||||
|
||||
on_recovered = sync_intake_after_parse_job_recovery
|
||||
recover_stale_jobs(
|
||||
domain=domain,
|
||||
timeout_seconds=timeout_seconds,
|
||||
job_type=normalized_type,
|
||||
on_recovered=on_recovered,
|
||||
)
|
||||
else:
|
||||
recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
|
||||
job = claim_next_job(domain=domain, job_types=job_types)
|
||||
if not job:
|
||||
return False, "no_job"
|
||||
|
||||
job_id = int(job.id)
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
job_type_value = str(job.job_type or "").strip()
|
||||
payload = dict(job.payload_json or {})
|
||||
payload.setdefault("job_id", job_id)
|
||||
handler = get_handler(JobType(job_type_value))
|
||||
if handler is None:
|
||||
fail_job(job, error=f"no handler registered for {job.job_type}")
|
||||
fail_job(
|
||||
job_id,
|
||||
error=f"no handler registered for {job.job_type}",
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return True, "missing_handler"
|
||||
|
||||
try:
|
||||
handler(ctx, payload)
|
||||
refreshed = db.session.get(Job, job_id)
|
||||
if refreshed and refreshed.status == "running":
|
||||
finish_job(refreshed, message="任务处理完成")
|
||||
# 条件收口:Handler 已 finish/fail 或代次失效时 rowcount=0,不覆盖
|
||||
finish_job(job_id, message="任务处理完成", owned_attempt=owned_attempt)
|
||||
return True, job_type_value
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
refreshed = db.session.get(Job, job_id)
|
||||
if refreshed:
|
||||
fail_job(refreshed, error=str(exc), retryable=True)
|
||||
fail_job(job_id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
|
||||
raise
|
||||
@@ -43,13 +43,23 @@ def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None)
|
||||
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_id=%s', job.get('job_type'), job.get('id'))
|
||||
store.mark_failed(job['id'], message=f'no handler for {job.get("job_type")}')
|
||||
store.mark_failed(
|
||||
job['id'],
|
||||
message=f'no handler for {job.get("job_type")}',
|
||||
owned_attempt=owned_attempt_int,
|
||||
)
|
||||
continue
|
||||
|
||||
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))
|
||||
store.mark_failed(
|
||||
job['id'],
|
||||
message=str(exc),
|
||||
owned_attempt=owned_attempt_int,
|
||||
)
|
||||
+43
-13
@@ -10,7 +10,23 @@ 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 KbJob
|
||||
from app.models import Job, KbJob
|
||||
|
||||
|
||||
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]:
|
||||
@@ -59,7 +75,7 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
|
||||
|
||||
recover_stale_running_jobs()
|
||||
if 'shipping_notice_run' in allowed_types:
|
||||
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()
|
||||
@@ -77,30 +93,44 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||||
|
||||
job = claim_next_shipping_notice_job()
|
||||
if job:
|
||||
return _normalize_kb_job(job)
|
||||
return _normalize_generic_job(job)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def mark_failed(job_id: int, *, message: str) -> None:
|
||||
def mark_failed(job_id: int, *, message: str, owned_attempt: int | None = None) -> None:
|
||||
"""
|
||||
handler 未捕获异常时,将 KbJob 标记为 failed。
|
||||
handler 未捕获异常时,将任务标记为 failed(KbJob 或通用 Job)。
|
||||
|
||||
Args:
|
||||
job_id: KbJob 主键。
|
||||
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 = db.session.get(KbJob, job_id)
|
||||
if not job or job.status != 'running':
|
||||
# 通用 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()
|
||||
job.status = 'failed'
|
||||
job.error_message = message[:1000]
|
||||
job.message = message[:500]
|
||||
job.finished_at = now
|
||||
job.progress = 100
|
||||
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()
|
||||
@@ -15,6 +15,7 @@ class JobType(StrEnum):
|
||||
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'
|
||||
@@ -48,7 +49,7 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
|
||||
# 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': frozenset({'shipping_notice_run', 'shipping_notice_parse'}),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -6,19 +6,24 @@ backend/app/models/__init__.py
|
||||
逻辑:Alembic / Flask-Migrate 通过本模块 import 注册全部表元数据;业务代码继续从此处导入模型类。
|
||||
"""
|
||||
|
||||
from app.models.agent import Agent, AgentGuide, PermissionRequest
|
||||
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, Feedback, GeneralFeedback
|
||||
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,
|
||||
@@ -39,6 +44,7 @@ __all__ = [
|
||||
'Agent',
|
||||
'ChatSession',
|
||||
'ChatLog',
|
||||
'ChatToolRun',
|
||||
'Feedback',
|
||||
'GeneralFeedback',
|
||||
'PermissionRequest',
|
||||
@@ -64,6 +70,14 @@ __all__ = [
|
||||
'ShippingInventoryFile',
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingInventoryMapping',
|
||||
'ShippingNoticeIntake',
|
||||
'ShippingNoticeDocument',
|
||||
'ShippingNoticeCandidate',
|
||||
'FileAsset',
|
||||
'AgentGuide',
|
||||
'AgentDirectoryMember',
|
||||
'TrainingRecord',
|
||||
'MaintenanceDevice',
|
||||
'MaintenanceRecord',
|
||||
'MaintenanceAuditLog',
|
||||
]
|
||||
@@ -1,8 +1,9 @@
|
||||
"""
|
||||
backend/app/models/agent.py
|
||||
|
||||
用途:Dify Agent 配置、新手指南、权限申请模型。
|
||||
依赖:models.base(Base、user_agent_permissions)。
|
||||
用途: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
|
||||
@@ -10,7 +11,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Integer, JSON, String, Text
|
||||
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
|
||||
@@ -20,7 +21,7 @@ class Agent(Base):
|
||||
"""
|
||||
AI 应用配置表
|
||||
用途:存储接入的 Dify Agent 配置信息
|
||||
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关
|
||||
核心逻辑:存储 Dify App ID 和 API Key,控制应用开关;运行时只读结构化列,extra_config 仅实验字段。
|
||||
"""
|
||||
|
||||
__tablename__ = 'agents'
|
||||
@@ -35,8 +36,30 @@ class Agent(Base):
|
||||
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',
|
||||
@@ -57,6 +80,7 @@ class AgentGuide(Base):
|
||||
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)
|
||||
@@ -67,6 +91,30 @@ class AgentGuide(Base):
|
||||
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):
|
||||
"""
|
||||
权限申请表
|
||||
|
||||
@@ -83,6 +83,37 @@ class Feedback(Base):
|
||||
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):
|
||||
"""
|
||||
通用意见反馈表
|
||||
|
||||
@@ -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)
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
@@ -29,6 +29,25 @@ class Job(Base):
|
||||
Index('ix_jobs_type_status_created', 'job_type', 'status', 'created_at'),
|
||||
Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'),
|
||||
Index('ix_jobs_locked_at', 'locked_at'),
|
||||
# 仅预解析 Job:同业务锚点同时只允许一条 queued
|
||||
# (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限)
|
||||
Index(
|
||||
'uq_jobs_shipping_parse_queued_ref',
|
||||
'domain',
|
||||
'job_type',
|
||||
'business_ref',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"job_type = 'shipping_notice_parse' "
|
||||
"AND status = 'queued' "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"job_type = 'shipping_notice_parse' "
|
||||
"AND status = 'queued' "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""
|
||||
backend/app/models/maintenance.py
|
||||
|
||||
用途:设备维保域数据模型,当前覆盖设备台账与台账变更审计。
|
||||
依赖:models.base.Base、SQLAlchemy mapped_column。
|
||||
逻辑:maintenance_devices 为维保助手查询/配置的设备主数据;audit_logs 记录台账导入与人工修改。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Date, DateTime, Index, Numeric, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class MaintenanceDevice(Base):
|
||||
"""设备台账主数据;责任人暂存用户名字符串,不与 users 表建立外键关系。"""
|
||||
|
||||
__tablename__ = 'maintenance_devices'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('device_code', name='uq_maintenance_devices_device_code'),
|
||||
Index('ix_maintenance_devices_name', 'device_name'),
|
||||
Index('ix_maintenance_devices_location', 'install_location'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
device_code: Mapped[str] = mapped_column(String(80), nullable=False)
|
||||
device_name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
model_spec: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
department: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
install_location: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
device_status: Mapped[str] = mapped_column(String(30), default='in_use', nullable=False)
|
||||
manufacturer: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
entry_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
production_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
start_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
responsible_user: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
maintenance_cycle: Mapped[Optional[str]] = mapped_column(String(80), nullable=True)
|
||||
original_value: Mapped[Optional[float]] = mapped_column(Numeric(14, 2), nullable=True)
|
||||
residual_value: Mapped[Optional[float]] = mapped_column(Numeric(14, 2), nullable=True)
|
||||
account_set: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
updated_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class MaintenanceAuditLog(Base):
|
||||
"""设备维保域审计日志,记录台账新增、更新、Excel 导入等写入动作。"""
|
||||
|
||||
__tablename__ = 'maintenance_audit_logs'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
object_type: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
object_id: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
action: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
before_data: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
after_data: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
operator_name: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(80), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class MaintenanceRecord(Base):
|
||||
"""设备维修记录,保存报修、修复与费用工时信息。"""
|
||||
|
||||
__tablename__ = 'maintenance_records'
|
||||
__table_args__ = (
|
||||
Index('ix_maintenance_records_device_code', 'device_code'),
|
||||
Index('ix_maintenance_records_report_date', 'report_date'),
|
||||
Index('ix_maintenance_records_status', 'repair_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
device_id: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
device_code: Mapped[str] = mapped_column(String(80), nullable=False)
|
||||
device_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
model_spec: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
install_location: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
report_date: Mapped[date] = mapped_column(Date, nullable=False)
|
||||
repair_category: Mapped[Optional[str]] = mapped_column(String(80), nullable=True)
|
||||
fault_description: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
reporter: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
approver: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
repair_status: Mapped[str] = mapped_column(String(30), default='pending', nullable=False)
|
||||
repair_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
repair_unit: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
repairer: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
repair_cost: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
repair_hours: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
repair_description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
source_order_no: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
created_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
updated_by: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
@@ -25,14 +25,16 @@ class ScheduleTask(Base):
|
||||
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')
|
||||
schedule_type: Mapped[str] = mapped_column(String(32), default='data_pipeline')
|
||||
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')
|
||||
data_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# platform_job 结构化参数(按 job_registry.params_schema 校验后写入)
|
||||
job_params: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
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=[])
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
"""
|
||||
backend/app/models/shipping.py
|
||||
|
||||
用途:货代发货通知批次、任务、事件、库存文件与库存映射模型。
|
||||
用途:货代发货通知批次、任务、事件、库存文件、接入记录、文档/候选与库存映射模型。
|
||||
依赖:models.base.Base。
|
||||
逻辑:ShippingBatch.create_idempotency_key 为建单幂等;ShippingTask.idempotency_key 为货代上传幂等;
|
||||
Intake.create_idempotency_key 承载混合/open_existing 确认请求重放;
|
||||
Intake/Task/Candidate.business_fingerprint 为业务去重指纹,与文件 content_hash 语义分离;
|
||||
Document/Candidate 承载阶段二「一邮件多订单」识别;ShippingTask.source_candidate_id 预留给建单;
|
||||
ShippingTask.supersedes_task_id 唯一约束保证修订链线性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -10,7 +15,20 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
DateTime,
|
||||
Float,
|
||||
ForeignKey,
|
||||
ForeignKeyConstraint,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
@@ -23,6 +41,11 @@ class ShippingBatch(Base):
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_batches_conversation', 'conversation_id'),
|
||||
UniqueConstraint(
|
||||
'user_id',
|
||||
'create_idempotency_key',
|
||||
name='uq_shipping_batches_user_create_idempotency',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -39,6 +62,7 @@ class ShippingBatch(Base):
|
||||
nullable=True,
|
||||
)
|
||||
file_count: Mapped[int] = mapped_column(Integer, default=1)
|
||||
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
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)
|
||||
@@ -59,6 +83,16 @@ class ShippingTask(Base):
|
||||
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'),
|
||||
Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'),
|
||||
Index('ix_shipping_tasks_inventory_site_id', 'inventory_site_id'),
|
||||
Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'),
|
||||
Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
|
||||
Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
|
||||
Index('ix_shipping_tasks_user_source_content_hash', 'user_id', 'source_content_hash'),
|
||||
Index('ix_shipping_tasks_user_business_fingerprint', 'user_id', 'business_fingerprint'),
|
||||
# 线性版本链:同一父任务至多一个后继(NULL 不冲突)
|
||||
UniqueConstraint('supersedes_task_id', name='uq_shipping_tasks_supersedes_task_id'),
|
||||
Index('ix_shipping_tasks_duplicate_source_task_id', 'duplicate_source_task_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -69,6 +103,36 @@ class ShippingTask(Base):
|
||||
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)
|
||||
source_content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
source_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=True)
|
||||
source_intake_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_notice_intakes.id'),
|
||||
index=True,
|
||||
nullable=True,
|
||||
)
|
||||
# 阶段二:由 Candidate 正式建单时回填;与 Candidate.consumed_task_id 对向引用,用 use_alter
|
||||
source_candidate_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_notice_candidates.id',
|
||||
name='fk_shipping_tasks_source_candidate_id',
|
||||
use_alter=True,
|
||||
),
|
||||
index=True,
|
||||
nullable=True,
|
||||
)
|
||||
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
document_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
supersedes_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'),
|
||||
nullable=True,
|
||||
)
|
||||
duplicate_source_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'),
|
||||
nullable=True,
|
||||
)
|
||||
duplicate_override_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
duplicate_resolution_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
|
||||
@@ -76,6 +140,21 @@ class ShippingTask(Base):
|
||||
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)
|
||||
destination_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
destination_city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
destination_country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
inventory_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
inventory_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
inventory_source_confirmed_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
inventory_source_confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
inventory_source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
inventory_routing_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
inventory_rpa_consumed_run_no: Mapped[Optional[str]] = mapped_column(String(128), 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)
|
||||
@@ -143,6 +222,35 @@ class ShippingInventoryFile(Base):
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_inventory_files_batch_created', 'batch_id', 'created_at'),
|
||||
Index('ix_shipping_inventory_files_user_created', 'user_id', 'created_at'),
|
||||
Index(
|
||||
'ix_shipping_inventory_files_source_snapshot',
|
||||
'source_code',
|
||||
'warehouse_id',
|
||||
'snapshot_status',
|
||||
'exported_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_inventory_files_source_site_wh',
|
||||
'source_code',
|
||||
'site_id',
|
||||
'warehouse_id',
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_inventory_files_rpa_identity_ready',
|
||||
'rpa_run_no',
|
||||
'source_code',
|
||||
'site_id',
|
||||
'warehouse_id',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -158,6 +266,19 @@ class ShippingInventoryFile(Base):
|
||||
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
line_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
|
||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
snapshot_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
exported_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
|
||||
source_query_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)
|
||||
|
||||
@@ -176,6 +297,12 @@ class ShippingTaskInventoryLink(Base):
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_task_inventory_links_task_active', 'task_id', 'is_active'),
|
||||
Index('ix_shipping_task_inventory_links_file_active', 'inventory_file_id', 'is_active'),
|
||||
Index(
|
||||
'ix_shipping_task_inventory_links_task_source',
|
||||
'task_id',
|
||||
'matched_source_code',
|
||||
'matched_site_id',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -184,6 +311,14 @@ class ShippingTaskInventoryLink(Base):
|
||||
link_role: Mapped[str] = mapped_column(String(32), default='member')
|
||||
access_mode: Mapped[str] = mapped_column(String(32), default='readonly')
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), index=True)
|
||||
link_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
matched_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
matched_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
matched_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
audit_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
@@ -195,6 +330,179 @@ class ShippingTaskInventoryLink(Base):
|
||||
)
|
||||
|
||||
|
||||
class ShippingNoticeIntake(Base):
|
||||
"""发货通知预解析接入记录(上传成功至正式建单前的异步解析阶段)。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_intakes'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('intake_no', name='uq_shipping_notice_intakes_intake_no'),
|
||||
UniqueConstraint(
|
||||
'asset_id',
|
||||
'purpose',
|
||||
'parser_version',
|
||||
name='uq_shipping_notice_intakes_asset_purpose_parser',
|
||||
),
|
||||
Index('ix_shipping_notice_intakes_user_conversation_created', 'user_id', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_notice_intakes_parse_status_created', 'parse_status', 'created_at'),
|
||||
Index('ix_shipping_notice_intakes_expires', 'expires_at'),
|
||||
Index('ix_shipping_notice_intakes_user_business_fingerprint', 'user_id', 'business_fingerprint'),
|
||||
Index('ix_shipping_notice_intakes_duplicate_status_created', 'duplicate_status', 'created_at'),
|
||||
Index('ix_shipping_notice_intakes_fp_version_fingerprint', 'fingerprint_version', 'business_fingerprint'),
|
||||
Index('ix_shipping_notice_intakes_user_create_idempotency', 'user_id', 'create_idempotency_key'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
intake_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), index=True, nullable=False)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True, nullable=False)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
purpose: Mapped[str] = mapped_column(String(32), default='shipping_notice', nullable=False)
|
||||
parse_status: Mapped[str] = mapped_column(String(32), default='created', nullable=False, index=True)
|
||||
extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
parse_warnings_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
parser_version: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
parse_job_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True)
|
||||
# 解析执行代次:格式 "{job_id}:{job.attempts}";超时回收清空后旧 Worker 写回被拒绝
|
||||
parse_lease: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
duplicate_status: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
default='unchecked',
|
||||
server_default=text("'unchecked'"),
|
||||
nullable=False,
|
||||
)
|
||||
duplicate_matches_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
duplicate_resolution: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
duplicate_resolved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
duplicate_resolved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
consumed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
consumed_batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True)
|
||||
consumed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
|
||||
create_idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
expires_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)
|
||||
|
||||
|
||||
class ShippingNoticeDocument(Base):
|
||||
"""
|
||||
发货通知文档单元:邮件正文或单个附件(阶段二)。
|
||||
|
||||
核心逻辑:Intake 解析后按 attachment_key 幂等 upsert;附件型 Document 可挂 derived FileAsset。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_notice_documents'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'intake_id',
|
||||
'attachment_key',
|
||||
name='uq_shipping_notice_documents_intake_attachment_key',
|
||||
),
|
||||
# 支撑 Candidate (primary_document_id, intake_id) 复合外键
|
||||
UniqueConstraint('id', 'intake_id', name='uq_shipping_notice_documents_id_intake'),
|
||||
Index('ix_shipping_notice_documents_intake_id', 'intake_id'),
|
||||
Index('ix_shipping_notice_documents_asset_id', 'asset_id'),
|
||||
Index('ix_shipping_notice_documents_content_hash', 'content_hash'),
|
||||
Index('ix_shipping_notice_documents_parse_status', 'parse_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
intake_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_intakes.id'),
|
||||
nullable=False,
|
||||
)
|
||||
asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
|
||||
document_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
attachment_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
filename: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
content_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
classification: Mapped[str] = mapped_column(String(32), default='unknown', nullable=False)
|
||||
parse_status: Mapped[str] = mapped_column(String(32), default='pending', nullable=False)
|
||||
extracted_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
parse_warnings_json: Mapped[Optional[list]] = 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)
|
||||
|
||||
|
||||
class ShippingNoticeCandidate(Base):
|
||||
"""
|
||||
订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
|
||||
|
||||
核心逻辑:通常 1 Document → 1 Candidate;重复检测与决策落在 Candidate 级,互不影响。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_notice_candidates'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('candidate_no', name='uq_shipping_notice_candidates_candidate_no'),
|
||||
UniqueConstraint(
|
||||
'intake_id',
|
||||
'primary_document_id',
|
||||
name='uq_shipping_notice_candidates_intake_primary_document',
|
||||
),
|
||||
# 保证主文档与 Candidate 同属一 Intake,禁止跨 Intake 挂接
|
||||
ForeignKeyConstraint(
|
||||
['primary_document_id', 'intake_id'],
|
||||
['shipping_notice_documents.id', 'shipping_notice_documents.intake_id'],
|
||||
name='fk_shipping_notice_candidates_document_intake',
|
||||
),
|
||||
Index('ix_shipping_notice_candidates_intake_id', 'intake_id'),
|
||||
Index('ix_shipping_notice_candidates_primary_document_id', 'primary_document_id'),
|
||||
Index('ix_shipping_notice_candidates_po_number', 'po_number'),
|
||||
Index(
|
||||
'ix_shipping_notice_candidates_user_fingerprint',
|
||||
'business_fingerprint',
|
||||
),
|
||||
Index('ix_shipping_notice_candidates_duplicate_status', 'duplicate_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
candidate_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
intake_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_notice_intakes.id'),
|
||||
nullable=False,
|
||||
)
|
||||
primary_document_id: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
structured_result_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
validation_status: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
default='pending',
|
||||
server_default=text("'pending'"),
|
||||
nullable=False,
|
||||
)
|
||||
conflicts_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
selected: Mapped[bool] = mapped_column(Boolean, default=True, server_default=text('true'), nullable=False)
|
||||
business_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
fingerprint_strength: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
duplicate_status: Mapped[str] = mapped_column(
|
||||
String(32),
|
||||
default='unchecked',
|
||||
server_default=text("'unchecked'"),
|
||||
nullable=False,
|
||||
)
|
||||
duplicate_matches_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
duplicate_resolution: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
duplicate_resolution_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
duplicate_target_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
duplicate_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
consumed_task_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_tasks.id'),
|
||||
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 ShippingInventoryMapping(Base):
|
||||
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
|
||||
|
||||
|
||||
@@ -61,6 +61,7 @@ class User(Base):
|
||||
department: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
role: Mapped[str] = mapped_column(String(20), default='user')
|
||||
status: Mapped[str] = mapped_column(String(20), default='active')
|
||||
feature_permissions: Mapped[dict] = mapped_column(JSON, default=dict, nullable=False)
|
||||
password_hash: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
language: Mapped[str] = mapped_column(String(10), default='zh-CN')
|
||||
theme_preference: Mapped[str] = mapped_column(String(10), default='system')
|
||||
@@ -84,6 +85,59 @@ class User(Base):
|
||||
uselist=False,
|
||||
)
|
||||
|
||||
def _role_default_feature_permissions(self) -> dict[str, bool]:
|
||||
"""返回当前角色自带的功能权限默认值。"""
|
||||
return {
|
||||
'training_hr_manage': self.role in {'admin', 'hr'},
|
||||
# 发货通知强制新建重复单据:admin 默认开;其他角色默认关,可显式授予
|
||||
'shipping_notice_force_create': self.role == 'admin',
|
||||
}
|
||||
|
||||
def get_feature_permissions(self) -> dict[str, bool]:
|
||||
"""
|
||||
返回当前用户的有效功能权限。
|
||||
|
||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训类业务权限硬编码在多个模块。
|
||||
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
raw = self.feature_permissions if isinstance(self.feature_permissions, dict) else {}
|
||||
result: dict[str, bool] = {}
|
||||
for key, default_value in defaults.items():
|
||||
if key in raw:
|
||||
result[key] = bool(raw.get(key))
|
||||
else:
|
||||
result[key] = bool(default_value)
|
||||
return result
|
||||
|
||||
def set_feature_permissions(self, permissions: dict | None) -> None:
|
||||
"""
|
||||
保存用户显式配置的功能权限覆盖项。
|
||||
|
||||
用途:给管理后台用户编辑表单落库权限配置。
|
||||
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。
|
||||
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
|
||||
"""
|
||||
defaults = self._role_default_feature_permissions()
|
||||
raw = permissions if isinstance(permissions, dict) else {}
|
||||
overrides: dict[str, bool] = {}
|
||||
for key, default_value in defaults.items():
|
||||
if key not in raw:
|
||||
continue
|
||||
normalized = bool(raw.get(key))
|
||||
if normalized != bool(default_value):
|
||||
overrides[key] = normalized
|
||||
self.feature_permissions = overrides
|
||||
|
||||
def has_feature_permission(self, permission_key: str) -> bool:
|
||||
"""判断当前用户是否具备指定功能权限。"""
|
||||
return bool(self.get_feature_permissions().get(permission_key))
|
||||
|
||||
def can_manage_training(self) -> bool:
|
||||
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
|
||||
return self.has_feature_permission('training_hr_manage')
|
||||
|
||||
def set_password(self, password: str) -> None:
|
||||
"""设置密码哈希。"""
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
"""
|
||||
backend/app/response_utils.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.response。
|
||||
依赖:app.core.response。
|
||||
逻辑:create_app 全局 handler 使用 error_payload;新代码请 from app.core.response import ...。
|
||||
"""
|
||||
|
||||
from app.core.response import error_payload, ok, utc_iso, utc_iso_now # noqa: F401
|
||||
|
||||
__all__ = ['error_payload', 'ok', 'utc_iso', 'utc_iso_now']
|
||||
@@ -2,5 +2,32 @@
|
||||
backend/app/services/admin/__init__.py
|
||||
|
||||
用途:管理后台业务服务包。
|
||||
逻辑:Wave 3 从 api/admin/_legacy 抽取 users/agents/departments/settings 等。
|
||||
逻辑:Wave 3 从 api/admin 抽取;子模块按需 import。
|
||||
"""
|
||||
from . import (
|
||||
agent_service,
|
||||
announcement_service,
|
||||
dashboard_service,
|
||||
database_admin_service,
|
||||
department_service,
|
||||
faq_service,
|
||||
guide_service,
|
||||
permission_service,
|
||||
report_service,
|
||||
user_service,
|
||||
wecom_admin_service,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'agent_service',
|
||||
'announcement_service',
|
||||
'dashboard_service',
|
||||
'database_admin_service',
|
||||
'department_service',
|
||||
'faq_service',
|
||||
'guide_service',
|
||||
'permission_service',
|
||||
'report_service',
|
||||
'user_service',
|
||||
'wecom_admin_service',
|
||||
]
|
||||
@@ -1,5 +1,319 @@
|
||||
"""
|
||||
backend/app/services/admin/agent_service.py
|
||||
|
||||
用途:Agent CRUD、权限、guide 配置。
|
||||
用途:管理端 Agent CRUD、连通性测试、用户权限绑定。
|
||||
依赖:models、DifyService、agent_registry.admin_payload、agent_registry.serialization。
|
||||
逻辑:由 api/admin/agents.py 调用;创建/更新写入 Registry 结构化列并清理 extra 已迁移键。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.core.config.settings import Config
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members
|
||||
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
|
||||
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
|
||||
from app.services.agent_registry.catalog_loader import get_dify_required_providers
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_admin
|
||||
from app.services.dify import DifyService
|
||||
|
||||
|
||||
def serialize_agent(agent: Agent) -> dict:
|
||||
"""Agent ORM → 管理端列表 JSON。"""
|
||||
return serialize_agent_for_admin(agent)
|
||||
|
||||
|
||||
def list_agents() -> list[dict]:
|
||||
"""返回全部 Agent(按 id 升序)。"""
|
||||
agents = db.session.query(Agent).order_by(Agent.id.asc()).all()
|
||||
return [serialize_agent(a) for a in agents]
|
||||
|
||||
|
||||
def create_agent(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
创建 Agent 并写入 Registry 结构化列。
|
||||
|
||||
Returns:
|
||||
{ id }。
|
||||
|
||||
Raises:
|
||||
ValidationError: 字段校验失败。
|
||||
"""
|
||||
normalized = validate_agent_payload(data)
|
||||
if not normalized.get('dify_api_key') and normalized.get('runtime_provider') in get_dify_required_providers():
|
||||
raise ValidationError('dify_api_key 为必填项')
|
||||
|
||||
agent = Agent(name=normalized['name'], is_active=normalized['is_active'])
|
||||
if isinstance(data.get('extra_config'), dict):
|
||||
normalized['extra_config'] = data['extra_config']
|
||||
else:
|
||||
normalized['extra_config'] = {}
|
||||
apply_agent_payload(agent, normalized)
|
||||
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
|
||||
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
|
||||
db.session.commit()
|
||||
return {'id': agent.id}
|
||||
|
||||
|
||||
def _pick_update_value(data: dict[str, Any], key: str, current: Any) -> Any:
|
||||
"""区分 PATCH 未传字段与显式 null。"""
|
||||
return data[key] if key in data else current
|
||||
|
||||
|
||||
def update_agent(agent_id: int, data: dict[str, Any]) -> None:
|
||||
"""更新 Agent Registry 结构化列并清理 extra 已迁移键。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
merged = {
|
||||
'name': data.get('name', agent.name),
|
||||
'description': data.get('description', agent.description),
|
||||
'icon_url': data.get('icon_url', agent.icon_url),
|
||||
'is_active': data.get('is_active', agent.is_active),
|
||||
'dify_app_id': data.get('dify_app_id', agent.dify_app_id),
|
||||
'api_base_url': data.get('api_base_url', agent.api_base_url),
|
||||
'agent_code': data.get('agent_code', agent.agent_code),
|
||||
'runtime_provider': data.get('runtime_provider', agent.runtime_provider),
|
||||
'conversation_mode': data.get('conversation_mode', agent.conversation_mode),
|
||||
'dify_app_type': data.get('dify_app_type', agent.dify_app_type),
|
||||
'iframe_url': data.get('iframe_url', agent.iframe_url),
|
||||
'category': data.get('category', agent.category),
|
||||
'sub_category': data.get('sub_category', agent.sub_category),
|
||||
'sort_order': data.get('sort_order', agent.sort_order),
|
||||
'welcome_message': data.get('welcome_message', agent.welcome_message),
|
||||
'suggested_questions_style': data.get('suggested_questions_style', agent.suggested_questions_style),
|
||||
'suggested_questions': data.get('suggested_questions', agent.suggested_questions),
|
||||
'capabilities': data.get('capabilities', agent.capabilities),
|
||||
'file_upload_policy': data.get('file_upload_policy', agent.file_upload_policy),
|
||||
'bound_schedule_task_id': data.get('bound_schedule_task_id', agent.bound_schedule_task_id),
|
||||
'handler_config': _pick_update_value(data, 'handler_config', agent.handler_config),
|
||||
'extra_config': _pick_update_value(data, 'extra_config', agent.extra_config),
|
||||
'is_aggregate': data.get('is_aggregate', agent.is_aggregate),
|
||||
}
|
||||
if data.get('dify_api_key'):
|
||||
merged['dify_api_key'] = data['dify_api_key']
|
||||
|
||||
normalized = validate_agent_payload(merged, agent=agent, provided_fields=frozenset(data.keys()))
|
||||
apply_agent_payload(agent, normalized)
|
||||
if 'directory_member_ids' in data or 'is_aggregate' in data:
|
||||
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
|
||||
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_agent(agent_id: int) -> None:
|
||||
"""删除 Agent(不存在时静默成功)。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if agent:
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_agent_connectivity(agent_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
测试 Agent 连通性(iframe GET 或 Dify chatflow/workflow POST)。
|
||||
核心逻辑:通过则可选自动 is_active=True。
|
||||
"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
tested_at = datetime.utcnow().isoformat()
|
||||
if agent.runtime_provider == 'iframe' or agent.type == 'iframe':
|
||||
return _test_iframe_agent(agent, tested_at)
|
||||
return _test_dify_agent(agent, tested_at)
|
||||
|
||||
|
||||
def _test_iframe_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
iframe_url = str(agent.iframe_url or '').strip()
|
||||
if not iframe_url:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing iframe_url column.',
|
||||
'analysis': '测试失败:未配置 iframe URL。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
try:
|
||||
resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True)
|
||||
passed = 200 <= resp.status_code < 400
|
||||
if passed and (not agent.is_active):
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return {
|
||||
'passed': passed,
|
||||
'request_url': iframe_url,
|
||||
'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}',
|
||||
'analysis': '测试通过:iframe 地址可访问。' if passed else '测试失败:iframe 地址不可访问或返回异常状态。',
|
||||
'http_status': resp.status_code,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
except requests.RequestException as exc:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': iframe_url,
|
||||
'output_info': str(exc),
|
||||
'analysis': '测试失败:请求 iframe 地址异常。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
|
||||
def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]:
|
||||
if not agent.dify_api_key:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing dify_api_key.',
|
||||
'analysis': '测试失败:未配置 API Key。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
|
||||
if not base_url:
|
||||
return {
|
||||
'passed': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing api_base_url.',
|
||||
'analysis': '测试失败:未配置 API Base URL。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
dify_app_type = str(agent.dify_app_type or 'chatflow').strip().lower()
|
||||
if dify_app_type not in ('chatflow', 'workflow'):
|
||||
dify_app_type = 'chatflow'
|
||||
if dify_app_type == 'workflow':
|
||||
request_url = DifyService._build_workflow_url(base_url)
|
||||
payload = {
|
||||
'inputs': {'query': '系统连通性测试,请简短回复OK。'},
|
||||
'response_mode': 'blocking',
|
||||
'user': 'admin_test',
|
||||
}
|
||||
else:
|
||||
request_url = DifyService._build_chat_messages_url(base_url)
|
||||
payload = {
|
||||
'inputs': {},
|
||||
'query': '系统连通性测试,请简短回复OK。',
|
||||
'response_mode': 'blocking',
|
||||
'user': 'admin_test',
|
||||
}
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'}
|
||||
try:
|
||||
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
|
||||
raw_text = (resp.text or '')[:4000]
|
||||
output_info = raw_text
|
||||
passed = False
|
||||
analysis = f'测试失败:HTTP {resp.status_code}。'
|
||||
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
|
||||
passed = True
|
||||
analysis = '测试通过:Workflow 接口可访问且认证通过。'
|
||||
try:
|
||||
data = resp.json()
|
||||
if dify_app_type == 'workflow':
|
||||
passed, output_info, analysis = _parse_workflow_test_response(resp, data, output_info, analysis)
|
||||
else:
|
||||
passed, output_info, analysis = _parse_chatflow_test_response(resp, data, output_info, analysis, passed)
|
||||
except ValueError:
|
||||
if resp.ok and raw_text.strip():
|
||||
passed = True
|
||||
analysis = (
|
||||
'测试通过:Workflow 接口可访问并返回了文本内容。'
|
||||
if dify_app_type == 'workflow'
|
||||
else '测试通过:Chatflow 接口可访问并返回了文本内容。'
|
||||
)
|
||||
if passed and (not agent.is_active):
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return {
|
||||
'passed': passed,
|
||||
'dify_app_type': dify_app_type,
|
||||
'request_url': request_url,
|
||||
'output_info': output_info,
|
||||
'analysis': analysis,
|
||||
'http_status': resp.status_code,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
except requests.RequestException as exc:
|
||||
return {
|
||||
'passed': False,
|
||||
'dify_app_type': dify_app_type,
|
||||
'request_url': request_url,
|
||||
'output_info': str(exc),
|
||||
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at,
|
||||
}
|
||||
|
||||
|
||||
def _parse_workflow_test_response(resp, data, output_info: str, analysis: str) -> tuple[bool, str, str]:
|
||||
passed = 200 <= resp.status_code < 300
|
||||
workflow_data = data.get('data') if isinstance(data, dict) else None
|
||||
outputs = workflow_data.get('outputs') if isinstance(workflow_data, dict) else None
|
||||
status = workflow_data.get('status') if isinstance(workflow_data, dict) else None
|
||||
message = data.get('message') if isinstance(data, dict) else None
|
||||
if isinstance(outputs, dict) and outputs:
|
||||
output_info = str(outputs)[:4000]
|
||||
elif isinstance(message, str) and message.strip():
|
||||
output_info = message[:4000]
|
||||
elif isinstance(data, dict):
|
||||
output_info = str(data)[:4000]
|
||||
if resp.ok and status in ('succeeded', 'success'):
|
||||
analysis = '测试通过:Workflow 接口可访问且业务返回成功。'
|
||||
elif resp.ok:
|
||||
analysis = '测试通过:Workflow 接口可访问且认证通过(本次未返回业务成功状态)。'
|
||||
return passed, output_info, analysis
|
||||
|
||||
|
||||
def _parse_chatflow_test_response(resp, data, output_info: str, analysis: str, passed: bool) -> tuple[bool, str, str]:
|
||||
answer = data.get('answer') if isinstance(data, dict) else None
|
||||
if answer:
|
||||
output_info = str(answer)[:4000]
|
||||
if resp.ok and isinstance(answer, str) and answer.strip():
|
||||
passed = True
|
||||
analysis = '测试通过:Chatflow 接口可访问且已返回回答。'
|
||||
elif resp.ok:
|
||||
analysis = '测试未通过:Chatflow 接口可访问,但未返回有效回答。'
|
||||
else:
|
||||
message = data.get('message') if isinstance(data, dict) else None
|
||||
if message:
|
||||
output_info = str(message)[:4000]
|
||||
return passed, output_info, analysis
|
||||
|
||||
|
||||
def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None:
|
||||
"""将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
current_users = db.session.query(User).filter(User.agents.contains(agent)).all()
|
||||
current_user_ids = {u.id for u in current_users}
|
||||
new_user_ids = set(user_ids)
|
||||
to_add = new_user_ids - current_user_ids
|
||||
if to_add:
|
||||
users_to_add = db.session.query(User).filter(User.id.in_(to_add)).all()
|
||||
for user in users_to_add:
|
||||
user.agents.append(agent)
|
||||
to_remove = current_user_ids - new_user_ids
|
||||
if to_remove:
|
||||
users_to_remove = db.session.query(User).filter(User.id.in_(to_remove)).all()
|
||||
for user in users_to_remove:
|
||||
user.agents.remove(agent)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def import_training_question_bank_from_pdf(agent_id: int, guide_id: int | None = None) -> dict[str, Any]:
|
||||
"""解析指定 Agent 的培训试题 PDF,并返回结构化题库。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
return parse_training_question_bank_from_guide(agent_id=agent_id, guide_id=guide_id)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
backend/app/services/admin/announcement_service.py
|
||||
|
||||
用途:系统公告 CRUD 与活跃公告列表(管理端 + 工作台/登录页只读)。
|
||||
依赖:models.Announcement、app.core.errors。
|
||||
逻辑:api/admin/announcements.py 管理 CRUD;api/workspace/announcements.py 只读活跃列表。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Announcement
|
||||
|
||||
|
||||
def serialize_announcement(ann: Announcement, *, include_active: bool = False) -> dict:
|
||||
"""Announcement ORM → API dict。"""
|
||||
row = {
|
||||
'id': ann.id,
|
||||
'title': ann.title,
|
||||
'content': ann.content,
|
||||
'created_at': ann.created_at.isoformat() if ann.created_at else None,
|
||||
}
|
||||
if include_active:
|
||||
row['is_active'] = bool(ann.is_active)
|
||||
return row
|
||||
|
||||
|
||||
def list_active_announcements() -> list[dict]:
|
||||
"""返回已发布(is_active)公告,供工作台/登录页展示。"""
|
||||
rows = (
|
||||
db.session.query(Announcement)
|
||||
.filter(Announcement.is_active.is_(True))
|
||||
.order_by(Announcement.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
return [serialize_announcement(a) for a in rows]
|
||||
|
||||
|
||||
def list_announcements() -> list[dict]:
|
||||
"""管理端列表:含全部公告及 is_active 字段。"""
|
||||
rows = db.session.query(Announcement).order_by(Announcement.created_at.desc()).all()
|
||||
return [serialize_announcement(a, include_active=True) for a in rows]
|
||||
|
||||
|
||||
def create_announcement(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
创建公告。
|
||||
Returns:
|
||||
{ id, message }。
|
||||
Raises:
|
||||
ValidationError: title/content 缺失。
|
||||
"""
|
||||
if not data.get('title') or not data.get('content'):
|
||||
raise ValidationError('Missing fields')
|
||||
ann = Announcement(
|
||||
title=data['title'],
|
||||
content=data['content'],
|
||||
is_active=bool(data.get('is_active', True)),
|
||||
)
|
||||
db.session.add(ann)
|
||||
db.session.commit()
|
||||
return {'message': 'Created', 'id': ann.id}
|
||||
|
||||
|
||||
def update_announcement(announcement_id: int, data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
更新公告 title/content(及可选 is_active)。
|
||||
Raises:
|
||||
NotFoundError: 公告不存在。
|
||||
ValidationError: title/content 缺失。
|
||||
"""
|
||||
if not data.get('title') or not data.get('content'):
|
||||
raise ValidationError('Missing fields')
|
||||
ann = db.session.get(Announcement, announcement_id)
|
||||
if not ann:
|
||||
raise NotFoundError('Not found')
|
||||
ann.title = data['title']
|
||||
ann.content = data['content']
|
||||
if 'is_active' in data:
|
||||
ann.is_active = bool(data['is_active'])
|
||||
db.session.commit()
|
||||
return {'message': 'Updated'}
|
||||
|
||||
|
||||
def delete_announcement(announcement_id: int) -> dict:
|
||||
"""删除公告(不存在时静默成功)。"""
|
||||
ann = db.session.get(Announcement, announcement_id)
|
||||
if ann:
|
||||
db.session.delete(ann)
|
||||
db.session.commit()
|
||||
return {'message': 'Deleted'}
|
||||
@@ -1,5 +1,60 @@
|
||||
"""
|
||||
backend/app/services/admin/dashboard_service.py
|
||||
|
||||
用途:管理后台仪表盘统计聚合。
|
||||
用途:管理后台仪表盘统计与侧栏角标聚合。
|
||||
依赖:models、SQLAlchemy func。
|
||||
逻辑:由 api/admin/dashboard.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, PermissionRequest, User
|
||||
|
||||
|
||||
def compute_dashboard_summary() -> dict:
|
||||
"""
|
||||
聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。
|
||||
Returns:
|
||||
agent_count、user_count、total_conversations、avg_score。
|
||||
"""
|
||||
total_users = db.session.query(func.count(User.id)).scalar() or 0
|
||||
active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0
|
||||
total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0
|
||||
avg_score = db.session.query(func.avg(Feedback.score)).scalar()
|
||||
avg_score = round(float(avg_score), 1) if avg_score else 0.0
|
||||
return {
|
||||
'agent_count': active_agents,
|
||||
'user_count': total_users,
|
||||
'total_conversations': total_conversations,
|
||||
'avg_score': avg_score,
|
||||
}
|
||||
|
||||
|
||||
def compute_dashboard_badges() -> dict:
|
||||
"""
|
||||
聚合侧栏角标所需的待办数量。
|
||||
Returns:
|
||||
pending_approvals、pending_requests。
|
||||
"""
|
||||
pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0
|
||||
pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0
|
||||
return {
|
||||
'pending_approvals': pending_approvals,
|
||||
'pending_requests': pending_requests,
|
||||
}
|
||||
|
||||
|
||||
def compute_legacy_dashboard_stats() -> dict:
|
||||
"""遗留 /dashboard 接口响应(summary + badges 字段名兼容早期前端)。"""
|
||||
summary = compute_dashboard_summary()
|
||||
badges = compute_dashboard_badges()
|
||||
return {
|
||||
'total_users': summary['user_count'],
|
||||
'active_agents': summary['agent_count'],
|
||||
'total_conversations': summary['total_conversations'],
|
||||
'avg_score': summary['avg_score'],
|
||||
'pending_approvals': badges['pending_approvals'],
|
||||
'pending_requests': badges['pending_requests'],
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
"""
|
||||
backend/app/services/admin/database_admin_service.py
|
||||
|
||||
用途:管理后台通用数据表浏览与 chat_logs 批量删除。
|
||||
依赖:models、report_service(chat_logs 报表复用)。
|
||||
逻辑:由 api/admin/database.py 调用;整型筛选字段对纯数字条件使用等值匹配。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatLog,
|
||||
Department,
|
||||
Feedback,
|
||||
PermissionRequest,
|
||||
QuickQuestion,
|
||||
User,
|
||||
UserDefaultAgent,
|
||||
UserFavoriteAgent,
|
||||
UserHomepageConfig,
|
||||
)
|
||||
from app.services.admin import report_service
|
||||
|
||||
ADMIN_TABLE_MODEL_MAP = {
|
||||
'users': User,
|
||||
'agents': Agent,
|
||||
'chat_logs': ChatLog,
|
||||
'feedbacks': Feedback,
|
||||
'permission_requests': PermissionRequest,
|
||||
'departments': Department,
|
||||
'quick_questions': QuickQuestion,
|
||||
'user_homepage_configs': UserHomepageConfig,
|
||||
'user_favorite_agents': UserFavoriteAgent,
|
||||
'user_default_agents': UserDefaultAgent,
|
||||
}
|
||||
|
||||
|
||||
def _serialize_model_row(item) -> dict:
|
||||
row = {}
|
||||
for col in item.__table__.columns:
|
||||
val = getattr(item, col.name)
|
||||
if isinstance(val, datetime):
|
||||
val = val.isoformat()
|
||||
row[col.name] = val
|
||||
return row
|
||||
|
||||
|
||||
def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]:
|
||||
"""
|
||||
返回管理报表表数据(最多 100 行)。
|
||||
chat_logs 走专用报表 JOIN 逻辑。
|
||||
"""
|
||||
if table == 'chat_logs':
|
||||
return report_service.list_chat_logs_report(query_params)
|
||||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||||
if not model:
|
||||
raise ValidationError('Invalid table')
|
||||
query = db.session.query(model)
|
||||
for key, value in query_params.items():
|
||||
if hasattr(model, key) and value:
|
||||
col = getattr(model, key)
|
||||
col_type = getattr(col, 'type', None)
|
||||
# 整型外键(如 agent_id)用等值过滤,避免 ILIKE '%16%' 误匹配 160
|
||||
if value.isdigit() and col_type is not None and getattr(col_type, 'python_type', None) is int:
|
||||
query = query.filter(col == int(value))
|
||||
else:
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
items = query.limit(100).all()
|
||||
return [_serialize_model_row(item) for item in items]
|
||||
|
||||
|
||||
def get_table_count(table: str, query_params: dict[str, str]) -> dict:
|
||||
"""返回表行数;chat_logs 使用报表筛选。"""
|
||||
if table == 'chat_logs':
|
||||
return report_service.count_chat_logs_report(query_params)
|
||||
model = ADMIN_TABLE_MODEL_MAP.get(table)
|
||||
if not model:
|
||||
raise ValidationError('Invalid table')
|
||||
total = db.session.query(func.count(model.id)).scalar()
|
||||
return {'table': table, 'total': int(total or 0)}
|
||||
|
||||
|
||||
def batch_delete_chat_logs(raw_ids: list[Any]) -> dict:
|
||||
"""按 id 批量删除 ChatLog。"""
|
||||
if not isinstance(raw_ids, list) or not raw_ids:
|
||||
raise ValidationError('ids is required')
|
||||
ids = []
|
||||
for value in raw_ids:
|
||||
try:
|
||||
ids.append(int(value))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not ids:
|
||||
raise ValidationError('No valid ids')
|
||||
cnt = db.session.query(ChatLog).filter(ChatLog.id.in_(ids)).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
return {'deleted_count': cnt}
|
||||
@@ -1,5 +1,91 @@
|
||||
"""
|
||||
backend/app/services/admin/department_service.py
|
||||
|
||||
用途:部门 CRUD。
|
||||
用途:管理端部门 CRUD 业务编排。
|
||||
依赖:models.Department、app.core.errors。
|
||||
逻辑:由 api/admin/departments.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Department
|
||||
|
||||
|
||||
def serialize_department(dept: Department) -> dict:
|
||||
"""部门 ORM → API dict。"""
|
||||
return {
|
||||
'id': dept.id,
|
||||
'name': dept.name,
|
||||
'code': dept.code,
|
||||
'company': dept.company,
|
||||
'description': dept.description,
|
||||
}
|
||||
|
||||
|
||||
def list_departments() -> list[dict]:
|
||||
"""返回全部部门(按 name 升序)。"""
|
||||
depts = db.session.query(Department).order_by(Department.name.asc()).all()
|
||||
return [serialize_department(d) for d in depts]
|
||||
|
||||
|
||||
def create_department(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
创建部门。
|
||||
Returns:
|
||||
{ id, name }。
|
||||
Raises:
|
||||
ValidationError: name 缺失或 name/code 重复。
|
||||
"""
|
||||
if not data.get('name'):
|
||||
raise ValidationError('Name is required')
|
||||
if db.session.query(Department).filter_by(name=data['name']).first():
|
||||
raise ValidationError('Name exists')
|
||||
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
|
||||
raise ValidationError('Code exists')
|
||||
dept = Department(
|
||||
name=data['name'],
|
||||
code=data.get('code'),
|
||||
company=data.get('company'),
|
||||
description=data.get('description'),
|
||||
)
|
||||
db.session.add(dept)
|
||||
db.session.commit()
|
||||
return {'id': dept.id, 'name': dept.name}
|
||||
|
||||
|
||||
def update_department(dept_id: int, data: dict[str, Any]) -> None:
|
||||
"""
|
||||
更新部门字段。
|
||||
Raises:
|
||||
NotFoundError: 部门不存在。
|
||||
ValidationError: name/code 与其它记录冲突。
|
||||
"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if not dept:
|
||||
raise NotFoundError('Not found')
|
||||
if 'name' in data:
|
||||
if db.session.query(Department).filter(Department.name == data['name'], Department.id != dept_id).first():
|
||||
raise ValidationError('Name exists')
|
||||
dept.name = data['name']
|
||||
if 'code' in data:
|
||||
if data['code'] and db.session.query(Department).filter(
|
||||
Department.code == data['code'], Department.id != dept_id
|
||||
).first():
|
||||
raise ValidationError('Code exists')
|
||||
dept.code = data['code']
|
||||
if 'company' in data:
|
||||
dept.company = data['company']
|
||||
if 'description' in data:
|
||||
dept.description = data['description']
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_department(dept_id: int) -> None:
|
||||
"""删除部门(不存在时静默成功)。"""
|
||||
dept = db.session.get(Department, dept_id)
|
||||
if dept:
|
||||
db.session.delete(dept)
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,237 @@
|
||||
"""
|
||||
backend/app/services/admin/faq_service.py
|
||||
|
||||
用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。
|
||||
依赖:models、faq_kb_invalidation、hot_faq_* services。
|
||||
逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, KbDocument, QuickQuestion
|
||||
|
||||
|
||||
def parse_aliases(raw_aliases) -> list[str]:
|
||||
"""解析别名列表,支持 JSON 数组或换行分隔字符串。"""
|
||||
if raw_aliases is None:
|
||||
return []
|
||||
if isinstance(raw_aliases, list):
|
||||
items = [str(item).strip() for item in raw_aliases if str(item).strip()]
|
||||
elif isinstance(raw_aliases, str):
|
||||
items = [line.strip() for line in raw_aliases.splitlines() if line.strip()]
|
||||
else:
|
||||
return []
|
||||
seen: set[str] = set()
|
||||
result: list[str] = []
|
||||
for item in items:
|
||||
if item not in seen:
|
||||
seen.add(item)
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
def parse_expires_at(raw_value) -> datetime | None:
|
||||
"""解析 FAQ 过期时间 ISO 字符串。"""
|
||||
if not raw_value:
|
||||
return None
|
||||
text = str(raw_value).strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return datetime.fromisoformat(text.replace('Z', '+00:00')).replace(tzinfo=None)
|
||||
except ValueError as exc:
|
||||
raise ValidationError('Invalid expires_at format') from exc
|
||||
|
||||
|
||||
def serialize_quick_question(
|
||||
q: QuickQuestion,
|
||||
agent_name: str,
|
||||
stale_kb_document: KbDocument | None = None,
|
||||
) -> dict:
|
||||
"""序列化全局常用问题供管理端展示。"""
|
||||
return {
|
||||
'id': q.id,
|
||||
'title': q.title,
|
||||
'question': q.question,
|
||||
'answer': q.answer,
|
||||
'aliases': q.aliases if isinstance(q.aliases, list) else [],
|
||||
'cache_enabled': bool(q.cache_enabled),
|
||||
'is_enabled': bool(q.is_enabled),
|
||||
'hit_count': q.hit_count or 0,
|
||||
'agent_id': q.agent_id,
|
||||
'agent_name': agent_name,
|
||||
'sort_order': q.sort_order,
|
||||
'expires_at': q.expires_at.isoformat() if q.expires_at else None,
|
||||
'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None,
|
||||
'source_kb_document_ids': q.source_kb_document_ids if isinstance(q.source_kb_document_ids, list) else [],
|
||||
'stale_at': q.stale_at.isoformat() if getattr(q, 'stale_at', None) else None,
|
||||
'stale_reason': q.stale_reason,
|
||||
'stale_kb_document_id': q.stale_kb_document_id,
|
||||
'stale_kb_document_title': stale_kb_document.title if stale_kb_document else None,
|
||||
}
|
||||
|
||||
|
||||
def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answer: bool = False) -> None:
|
||||
"""将请求体字段写入 QuickQuestion 实例。"""
|
||||
if 'title' in data:
|
||||
qq.title = str(data['title']).strip()
|
||||
if 'question' in data:
|
||||
qq.question = str(data['question']).strip()
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
if 'sort_order' in data:
|
||||
qq.sort_order = data.get('sort_order', 0)
|
||||
if 'answer' in data:
|
||||
qq.answer = str(data['answer']).strip() or None
|
||||
if 'aliases' in data:
|
||||
qq.aliases = parse_aliases(data['aliases'])
|
||||
if 'cache_enabled' in data:
|
||||
qq.cache_enabled = bool(data['cache_enabled'])
|
||||
if 'is_enabled' in data:
|
||||
qq.is_enabled = bool(data['is_enabled'])
|
||||
if 'expires_at' in data:
|
||||
qq.expires_at = parse_expires_at(data['expires_at'])
|
||||
if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
if data.get('clear_stale'):
|
||||
from app.services.faq_kb_invalidation import clear_faq_stale
|
||||
|
||||
clear_faq_stale(qq)
|
||||
|
||||
if qq.cache_enabled and not str(qq.answer or '').strip():
|
||||
raise ValidationError('启用 FAQ 缓存时必须填写标准答案')
|
||||
if require_answer and (not qq.title or not qq.question or not qq.agent_id):
|
||||
raise ValidationError('Missing required fields')
|
||||
|
||||
|
||||
def list_quick_questions(*, stale_only: bool = False) -> list[dict]:
|
||||
"""列出全局常用问题(user_id IS NULL)。"""
|
||||
query = (
|
||||
db.session.query(QuickQuestion)
|
||||
.filter(QuickQuestion.user_id.is_(None))
|
||||
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||
)
|
||||
if stale_only:
|
||||
query = query.filter(QuickQuestion.stale_at.isnot(None))
|
||||
rows = []
|
||||
for q in query.all():
|
||||
agent = db.session.get(Agent, q.agent_id)
|
||||
stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None
|
||||
rows.append(serialize_quick_question(q, agent.name if agent else 'Unknown', stale_doc))
|
||||
return rows
|
||||
|
||||
|
||||
def create_quick_question(data: dict[str, Any]) -> dict:
|
||||
"""创建全局 QuickQuestion。"""
|
||||
qq = QuickQuestion(user_id=None)
|
||||
apply_quick_question_payload(qq, data, require_answer=True)
|
||||
if isinstance(data.get('retriever_resources'), list):
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
|
||||
apply_retriever_resources_to_faq(qq, data['retriever_resources'])
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
return {'id': qq.id}
|
||||
|
||||
|
||||
def update_quick_question(question_id: int, data: dict[str, Any]) -> None:
|
||||
"""更新全局 QuickQuestion。"""
|
||||
qq = db.session.get(QuickQuestion, question_id)
|
||||
if not qq or qq.user_id is not None:
|
||||
raise NotFoundError('Not found')
|
||||
apply_quick_question_payload(qq, data)
|
||||
qq.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_quick_question(question_id: int) -> None:
|
||||
"""删除 QuickQuestion(不存在时静默成功)。"""
|
||||
qq = db.session.get(QuickQuestion, question_id)
|
||||
if qq:
|
||||
db.session.delete(qq)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def list_faq_candidates(*, agent_id: int | None = None) -> dict:
|
||||
"""列出热点 FAQ 候选及统计。"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
items = HotFaqCandidateStore.list_candidates(agent_id)
|
||||
return {
|
||||
'items': items,
|
||||
'stats': HotFaqCandidateStore.summarize(items),
|
||||
'rules': HotFaqAggregator.get_rules_document(),
|
||||
}
|
||||
|
||||
|
||||
def refresh_faq_candidates(*, agent_id: int | None, dry_run: bool) -> dict:
|
||||
"""手动触发离线热点聚合。"""
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
return HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
|
||||
|
||||
def promote_faq_candidate(data: dict[str, Any]) -> dict:
|
||||
"""将热点候选晋升为全局 QuickQuestion。"""
|
||||
from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
agent_id = data.get('agent_id')
|
||||
q_norm = normalize_faq_query(str(data.get('q_norm') or ''))
|
||||
if not agent_id or not q_norm:
|
||||
raise ValidationError('agent_id and q_norm are required')
|
||||
|
||||
candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm)
|
||||
if not candidate:
|
||||
raise NotFoundError('FAQ candidate not found')
|
||||
|
||||
title = str(data.get('title') or candidate.get('canonical_query') or q_norm).strip()[:100]
|
||||
question = str(candidate.get('canonical_query') or q_norm).strip()
|
||||
answer = str(candidate.get('answer') or '').strip()
|
||||
if not answer:
|
||||
raise ValidationError('Candidate has no answer')
|
||||
|
||||
aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm]
|
||||
retriever_resources = candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None
|
||||
qq = QuickQuestion(
|
||||
user_id=None,
|
||||
agent_id=int(agent_id),
|
||||
title=title,
|
||||
question=question,
|
||||
answer=answer,
|
||||
aliases=aliases or None,
|
||||
cache_enabled=True,
|
||||
is_enabled=True,
|
||||
retriever_resources=retriever_resources,
|
||||
sort_order=int(data.get('sort_order') or 0),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
apply_retriever_resources_to_faq(qq, retriever_resources)
|
||||
db.session.add(qq)
|
||||
db.session.flush()
|
||||
if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id):
|
||||
db.session.rollback()
|
||||
raise NotFoundError('FAQ candidate not found')
|
||||
db.session.commit()
|
||||
return {'id': qq.id, 'status': 'ok'}
|
||||
|
||||
|
||||
def dismiss_faq_candidate(*, agent_id: int, q_norm: str) -> dict:
|
||||
"""忽略热点 FAQ 候选。"""
|
||||
from app.services.faq_text_utils import normalize_faq_query
|
||||
from app.services.hot_faq_candidate_store import HotFaqCandidateStore
|
||||
|
||||
normalized = normalize_faq_query(q_norm)
|
||||
if not agent_id or not normalized:
|
||||
raise ValidationError('agent_id and q_norm are required')
|
||||
HotFaqCandidateStore.dismiss(int(agent_id), normalized)
|
||||
return {'status': 'ok'}
|
||||
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
backend/app/services/admin/guide_service.py
|
||||
|
||||
用途:Agent 引导资料(视频/PDF/图片)CRUD 与 MinIO 上传。
|
||||
依赖:models.AgentGuide、minio_service。
|
||||
逻辑:由 api/admin/guides.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.models import AgentGuide
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
|
||||
GUIDE_USAGE_GENERAL = 'general'
|
||||
GUIDE_USAGE_TRAINING_VIDEO = 'training_video'
|
||||
GUIDE_USAGE_TRAINING_EXAM_PDF = 'training_exam_pdf'
|
||||
ALLOWED_GUIDE_USAGES = {
|
||||
GUIDE_USAGE_GENERAL,
|
||||
GUIDE_USAGE_TRAINING_VIDEO,
|
||||
GUIDE_USAGE_TRAINING_EXAM_PDF,
|
||||
}
|
||||
|
||||
|
||||
def _infer_file_type(content_type: str | None) -> str:
|
||||
ct = str(content_type or '')
|
||||
if ct.startswith('video'):
|
||||
return 'video'
|
||||
if 'pdf' in ct:
|
||||
return 'pdf'
|
||||
return 'image'
|
||||
|
||||
|
||||
def serialize_guide(guide: AgentGuide) -> dict:
|
||||
"""AgentGuide ORM → API dict(含公开 URL)。"""
|
||||
return {
|
||||
'id': guide.id,
|
||||
'agent_id': guide.agent_id,
|
||||
'file_name': guide.file_name,
|
||||
'file_type': guide.file_type,
|
||||
'file_path': guide.file_path,
|
||||
'file_url': minio_service.get_public_url(guide.file_path),
|
||||
'file_size': guide.file_size,
|
||||
'guide_usage': guide.guide_usage,
|
||||
'remark': guide.remark,
|
||||
'sort_order': guide.sort_order,
|
||||
'status': guide.status,
|
||||
'created_at': guide.created_at.isoformat() if guide.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _normalize_guide_usage(raw_usage: Any, *, file_type: str) -> str:
|
||||
"""
|
||||
归一化指南用途并校验与文件类型是否匹配。
|
||||
|
||||
用途:给后台上传/编辑指南时统一约束“培训视频”“培训试题 PDF”等资料用途,避免前端再靠排序或文件名猜测。
|
||||
参数约束:training_video 仅允许 video 文件;training_exam_pdf 仅允许 pdf 文件。
|
||||
"""
|
||||
usage = str(raw_usage or GUIDE_USAGE_GENERAL).strip() or GUIDE_USAGE_GENERAL
|
||||
if usage not in ALLOWED_GUIDE_USAGES:
|
||||
raise ValidationError('Invalid guide usage')
|
||||
if usage == GUIDE_USAGE_TRAINING_VIDEO and file_type != 'video':
|
||||
raise ValidationError('Training video usage requires a video file')
|
||||
if usage == GUIDE_USAGE_TRAINING_EXAM_PDF and file_type != 'pdf':
|
||||
raise ValidationError('Training exam PDF usage requires a PDF file')
|
||||
return usage
|
||||
|
||||
|
||||
def upload_guide_file(file_storage: FileStorage | None) -> dict:
|
||||
"""
|
||||
上传引导文件至 MinIO。
|
||||
Returns:
|
||||
file_path、file_name、file_size、file_type。
|
||||
Raises:
|
||||
ValidationError: 无文件。
|
||||
AppError: 上传失败。
|
||||
"""
|
||||
if not file_storage or file_storage.filename == '':
|
||||
raise ValidationError('No selected file' if file_storage else 'No file part')
|
||||
content_type = file_storage.content_type
|
||||
|
||||
# 更高效地获取文件大小,不一次性读取全部内容到内存
|
||||
file_storage.seek(0, 2) # 移动到文件末尾
|
||||
file_size = file_storage.tell() # 获取当前位置(即文件大小)
|
||||
file_storage.seek(0) # 重置到文件开头
|
||||
|
||||
try:
|
||||
object_name = minio_service.upload_file(file_storage, file_storage.filename, content_type, file_size)
|
||||
return {
|
||||
'file_path': object_name,
|
||||
'file_name': file_storage.filename,
|
||||
'file_size': file_size,
|
||||
'file_type': _infer_file_type(content_type),
|
||||
}
|
||||
except Exception as exc:
|
||||
raise AppError(f'Upload failed: {str(exc)}')
|
||||
|
||||
|
||||
def list_guides(*, agent_id: int | None = None) -> list[dict]:
|
||||
"""按 agent_id 可选过滤返回引导列表。"""
|
||||
query = db.session.query(AgentGuide)
|
||||
if agent_id is not None:
|
||||
query = query.filter_by(agent_id=agent_id)
|
||||
guides = query.order_by(AgentGuide.sort_order).all()
|
||||
return [serialize_guide(g) for g in guides]
|
||||
|
||||
|
||||
def create_guide(data: dict[str, Any], *, created_by_id: int | None) -> dict:
|
||||
"""创建 AgentGuide 记录。"""
|
||||
file_type = str(data['file_type'])
|
||||
guide = AgentGuide(
|
||||
agent_id=data['agent_id'],
|
||||
file_name=data['file_name'],
|
||||
file_type=file_type,
|
||||
file_path=data['file_path'],
|
||||
file_size=data.get('file_size'),
|
||||
guide_usage=_normalize_guide_usage(data.get('guide_usage'), file_type=file_type),
|
||||
remark=data.get('remark'),
|
||||
sort_order=data.get('sort_order', 0),
|
||||
status=data.get('status', 1),
|
||||
created_by=created_by_id,
|
||||
)
|
||||
db.session.add(guide)
|
||||
db.session.commit()
|
||||
return {'id': guide.id}
|
||||
|
||||
|
||||
def update_guide(guide_id: int, data: dict[str, Any]) -> None:
|
||||
"""更新引导元数据。"""
|
||||
guide = db.session.get(AgentGuide, guide_id)
|
||||
if not guide:
|
||||
raise NotFoundError('Guide not found')
|
||||
if 'file_name' in data:
|
||||
guide.file_name = data['file_name']
|
||||
if 'remark' in data:
|
||||
guide.remark = data['remark']
|
||||
if 'sort_order' in data:
|
||||
guide.sort_order = data['sort_order']
|
||||
if 'status' in data:
|
||||
guide.status = data['status']
|
||||
if 'guide_usage' in data:
|
||||
guide.guide_usage = _normalize_guide_usage(data.get('guide_usage'), file_type=guide.file_type)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_guide(guide_id: int) -> None:
|
||||
"""删除引导并移除 MinIO 对象。"""
|
||||
guide = db.session.get(AgentGuide, guide_id)
|
||||
if not guide:
|
||||
raise NotFoundError('Guide not found')
|
||||
minio_service.delete_file(guide.file_path)
|
||||
db.session.delete(guide)
|
||||
db.session.commit()
|
||||
@@ -1,5 +1,174 @@
|
||||
"""
|
||||
backend/app/services/admin/permission_service.py
|
||||
|
||||
用途:权限申请、批量授权业务逻辑。
|
||||
用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。
|
||||
依赖:models、wecom_notify.send_wecom_event_message。
|
||||
逻辑:由 api/admin/permissions.py 调用;users 路由 /users/<id>/permissions 亦委托本模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, PermissionRequest, User
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
|
||||
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
|
||||
|
||||
|
||||
def serialize_permission_request(req: PermissionRequest) -> dict:
|
||||
"""PermissionRequest ORM → 管理端列表 JSON。"""
|
||||
return {
|
||||
'id': req.id,
|
||||
'user_id': req.user_id,
|
||||
'agent_id': req.agent_id,
|
||||
'reason': req.reason,
|
||||
'status': req.status,
|
||||
'created_at': req.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def _load_users_and_agents(user_ids: list[Any], agent_ids: list[Any]) -> tuple[list[User], list[Agent]]:
|
||||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
|
||||
return users, agents
|
||||
|
||||
|
||||
def _apply_user_agent_action(user: User, agents: list[Agent], action: str) -> None:
|
||||
"""对单个用户执行 add / remove / set 权限变更。"""
|
||||
if action == 'set':
|
||||
user.agents = agents
|
||||
elif action == 'add':
|
||||
for agent in agents:
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
elif action == 'remove':
|
||||
for agent in agents:
|
||||
if agent in user.agents:
|
||||
user.agents.remove(agent)
|
||||
|
||||
|
||||
def _notify_batch_permission_update(user: User, agents: list[Agent], action: str) -> None:
|
||||
"""批量权限变更后向已绑定企微的用户推送通知。"""
|
||||
if not user.wecom_userid:
|
||||
return
|
||||
action_label = _BATCH_ACTION_LABELS.get(action, action)
|
||||
agent_names = '、'.join([a.name for a in agents]) if agents else '无'
|
||||
send_wecom_event_message(
|
||||
event_type='permission_batch_updated',
|
||||
user=user,
|
||||
title='应用权限已更新',
|
||||
content=f'管理员已{action_label}你的应用权限:{agent_names}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
|
||||
|
||||
def batch_update_permissions(data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
批量更新多用户的 Agent 权限(add / remove / set)。
|
||||
Returns:
|
||||
{ status, updated_count }。
|
||||
Raises:
|
||||
ValidationError: 未选择用户。
|
||||
"""
|
||||
user_ids = data.get('user_ids', [])
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
action = data.get('action', 'add')
|
||||
if not user_ids:
|
||||
raise ValidationError('No users selected')
|
||||
|
||||
users, agents = _load_users_and_agents(user_ids, agent_ids)
|
||||
if not agents and action != 'set':
|
||||
if action == 'remove':
|
||||
return {'status': 'ok', 'updated_count': 0}
|
||||
|
||||
for user in users:
|
||||
_apply_user_agent_action(user, agents, action)
|
||||
_notify_batch_permission_update(user, agents, action)
|
||||
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'updated_count': len(users)}
|
||||
|
||||
|
||||
def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict:
|
||||
"""
|
||||
将指定用户的 Agent 权限重置为 agent_ids 列表(全量替换)。
|
||||
Returns:
|
||||
{ status }。
|
||||
Raises:
|
||||
NotFoundError: 用户不存在。
|
||||
"""
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('Not found')
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all()
|
||||
user.agents = agents
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def list_permission_requests() -> list[dict]:
|
||||
"""返回全部权限申请(按 created_at 降序)。"""
|
||||
reqs = (
|
||||
db.session.query(PermissionRequest)
|
||||
.order_by(PermissionRequest.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
return [serialize_permission_request(r) for r in reqs]
|
||||
|
||||
|
||||
def approve_permission_request(request_id: int) -> dict:
|
||||
"""
|
||||
批准权限申请:更新状态并将 Agent 加入用户权限。
|
||||
Raises:
|
||||
NotFoundError: 申请不存在。
|
||||
"""
|
||||
req = db.session.get(PermissionRequest, request_id)
|
||||
if not req:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
req.status = 'approved'
|
||||
req.reviewed_at = datetime.utcnow()
|
||||
user = db.session.get(User, req.user_id)
|
||||
agent = db.session.get(Agent, req.agent_id)
|
||||
if user and agent and (agent not in user.agents):
|
||||
user.agents.append(agent)
|
||||
if user and user.wecom_userid:
|
||||
send_wecom_event_message(
|
||||
event_type='permission_request_approved',
|
||||
user=user,
|
||||
title='权限申请已通过',
|
||||
content=f'你申请的应用权限已通过:{(agent.name if agent else req.agent_id)}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def reject_permission_request(request_id: int) -> dict:
|
||||
"""
|
||||
拒绝权限申请并通知用户(若已绑定企微)。
|
||||
Raises:
|
||||
NotFoundError: 申请不存在。
|
||||
"""
|
||||
req = db.session.get(PermissionRequest, request_id)
|
||||
if not req:
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
req.status = 'rejected'
|
||||
req.reviewed_at = datetime.utcnow()
|
||||
user = db.session.get(User, req.user_id)
|
||||
agent = db.session.get(Agent, req.agent_id)
|
||||
if user and user.wecom_userid:
|
||||
send_wecom_event_message(
|
||||
event_type='permission_request_rejected',
|
||||
user=user,
|
||||
title='权限申请未通过',
|
||||
content=f'你申请的应用权限未通过:{(agent.name if agent else req.agent_id)}',
|
||||
jump_path='/workspace',
|
||||
)
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
@@ -0,0 +1,505 @@
|
||||
"""
|
||||
backend/app/services/admin/report_service.py
|
||||
|
||||
用途:管理后台报表(使用分析、应用运营、反馈、聊天日志)数据聚合。
|
||||
依赖:models、SQLAlchemy func、user_agent_permissions。
|
||||
逻辑:由 api/admin/reports.py、database_admin_service 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import asc, desc, func, or_
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, PermissionRequest, User
|
||||
from app.models.base import user_agent_permissions
|
||||
|
||||
USAGE_BY_USER_TOP_LIMIT = 50
|
||||
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
|
||||
APPLICATION_REPORT_SORT_KEYS = frozenset({
|
||||
'name',
|
||||
'chat_count',
|
||||
'unique_users',
|
||||
'last_active_at',
|
||||
'authorized_users',
|
||||
'pending_requests',
|
||||
'avg_score',
|
||||
'tokens_used',
|
||||
})
|
||||
DEFAULT_APPLICATION_SORT = 'chat_count'
|
||||
# 运营提醒:启用应用在范围内对话次数 ≤ 该阈值视为低使用(含零使用)
|
||||
USAGE_LOW_AGENT_MAX_CHATS = 2
|
||||
# 运营提醒:低使用应用最多返回条数
|
||||
USAGE_LOW_AGENT_LIST_LIMIT = 5
|
||||
|
||||
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
||||
USAGE_RANGE_DAYS = {
|
||||
'7d': 7,
|
||||
'30d': 30,
|
||||
'90d': 90,
|
||||
'180d': 180,
|
||||
'365d': 365,
|
||||
}
|
||||
DEFAULT_USAGE_RANGE = '30d'
|
||||
|
||||
|
||||
def resolve_usage_range_start(range_key: str | None) -> tuple[str, datetime]:
|
||||
"""
|
||||
解析使用分析时间范围,返回规范化 key 与起始 UTC 时间。
|
||||
|
||||
Args:
|
||||
range_key: 前端传入的 range(7d/30d/90d/180d/365d),非法值回退近一月。
|
||||
|
||||
Returns:
|
||||
(normalized_key, since_utc)
|
||||
"""
|
||||
key = (range_key or DEFAULT_USAGE_RANGE).strip().lower()
|
||||
days = USAGE_RANGE_DAYS.get(key)
|
||||
if days is None:
|
||||
key = DEFAULT_USAGE_RANGE
|
||||
days = USAGE_RANGE_DAYS[key]
|
||||
since = datetime.utcnow() - timedelta(days=days)
|
||||
return key, since
|
||||
|
||||
|
||||
def build_usage_report(*, user_page: int, user_page_size: int, range_key: str | None = None) -> dict:
|
||||
"""
|
||||
聊天使用分析报表(按应用 / 按用户),限定时间范围内的 ChatLog。
|
||||
|
||||
核心逻辑:按 Agent / User 聚合 ChatLog 次数;按用户统计同时返回 username 与 real_name;
|
||||
另对启用 Agent 左连接对话量,产出含零使用的低使用应用列表(与应用运营口径对齐)。
|
||||
|
||||
Args:
|
||||
user_page: 按用户统计分页页码。
|
||||
user_page_size: 每页条数(上限 USAGE_BY_USER_TOP_LIMIT)。
|
||||
range_key: 时间范围 key,见 USAGE_RANGE_DAYS。
|
||||
|
||||
Returns:
|
||||
含 total / by_user / by_agent / by_day / low_agents 及用户分页字段的字典。
|
||||
"""
|
||||
normalized_range, since = resolve_usage_range_start(range_key)
|
||||
base_filter = ChatLog.created_at >= since
|
||||
|
||||
total = db.session.query(ChatLog).filter(base_filter).count()
|
||||
by_agent = (
|
||||
db.session.query(Agent.name, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.filter(base_filter)
|
||||
.group_by(Agent.name)
|
||||
.order_by(desc(func.count(ChatLog.id)), Agent.name)
|
||||
.all()
|
||||
)
|
||||
# [STEP 1] 按日期聚合趋势,供管理端判断近几天是否出现使用高峰或低谷。
|
||||
by_day = (
|
||||
db.session.query(func.date(ChatLog.created_at), func.count(ChatLog.id))
|
||||
.filter(base_filter)
|
||||
.group_by(func.date(ChatLog.created_at))
|
||||
.order_by(asc(func.date(ChatLog.created_at)))
|
||||
.all()
|
||||
)
|
||||
# [STEP 2] 低使用应用:以启用 Agent 为主表左连接范围内对话量,含零使用(by_agent 只有有对话的应用)
|
||||
agent_chat_counts = (
|
||||
db.session.query(
|
||||
ChatLog.agent_id.label('agent_id'),
|
||||
func.count(ChatLog.id).label('chat_count'),
|
||||
)
|
||||
.filter(base_filter)
|
||||
.group_by(ChatLog.agent_id)
|
||||
.subquery()
|
||||
)
|
||||
chat_count_col = func.coalesce(agent_chat_counts.c.chat_count, 0)
|
||||
low_agents = (
|
||||
db.session.query(Agent.name, chat_count_col.label('count'))
|
||||
.outerjoin(agent_chat_counts, agent_chat_counts.c.agent_id == Agent.id)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.filter(chat_count_col <= USAGE_LOW_AGENT_MAX_CHATS)
|
||||
.order_by(asc(chat_count_col), Agent.name)
|
||||
.limit(USAGE_LOW_AGENT_LIST_LIMIT)
|
||||
.all()
|
||||
)
|
||||
user_page = max(1, user_page)
|
||||
user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT))
|
||||
# [STEP 3] 按用户聚合对话量,一并选出真实姓名供管理端展示
|
||||
by_user_top = (
|
||||
db.session.query(User.username, User.real_name, func.count(ChatLog.id))
|
||||
.join(ChatLog)
|
||||
.filter(base_filter)
|
||||
.group_by(User.username, User.real_name)
|
||||
.order_by(desc(func.count(ChatLog.id)), User.username)
|
||||
.limit(USAGE_BY_USER_TOP_LIMIT)
|
||||
.all()
|
||||
)
|
||||
user_total = len(by_user_top)
|
||||
user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1
|
||||
user_page = min(user_page, user_pages)
|
||||
offset = (user_page - 1) * user_page_size
|
||||
by_user_page = by_user_top[offset:offset + user_page_size]
|
||||
return {
|
||||
'total': total,
|
||||
'range': normalized_range,
|
||||
'by_user': [
|
||||
{'username': u, 'real_name': rn or '', 'count': c}
|
||||
for u, rn, c in by_user_page
|
||||
],
|
||||
'by_agent': [{'agent': a, 'count': c} for a, c in by_agent],
|
||||
'by_day': [{'date': str(day), 'count': c} for day, c in by_day],
|
||||
'low_agents': [{'agent': a, 'count': int(c)} for a, c in low_agents],
|
||||
'low_agent_max_chats': USAGE_LOW_AGENT_MAX_CHATS,
|
||||
'low_agent_list_limit': USAGE_LOW_AGENT_LIST_LIMIT,
|
||||
'user_total': user_total,
|
||||
'user_page': user_page,
|
||||
'user_page_size': user_page_size,
|
||||
'user_pages': user_pages,
|
||||
'user_top_limit': USAGE_BY_USER_TOP_LIMIT,
|
||||
}
|
||||
|
||||
|
||||
def build_feedback_report() -> dict:
|
||||
"""反馈评分分布报表。"""
|
||||
total = db.session.query(Feedback).count()
|
||||
avg = db.session.query(func.avg(Feedback.score)).scalar() or 0
|
||||
dist = db.session.query(Feedback.score, func.count(Feedback.id)).group_by(Feedback.score).all()
|
||||
return {
|
||||
'total': total,
|
||||
'avg_score': float(avg),
|
||||
'distribution': [{'score': s, 'count': c} for s, c in dist],
|
||||
}
|
||||
|
||||
|
||||
def build_application_report(
|
||||
*,
|
||||
range_key: str | None = None,
|
||||
status: str | None = None,
|
||||
usage: str | None = None,
|
||||
q: str | None = None,
|
||||
sort: str | None = None,
|
||||
order: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict:
|
||||
"""
|
||||
应用运营报表:以 Agent 为主表,聚合时间范围内的使用 / 权限 / 评分指标。
|
||||
|
||||
核心逻辑:ChatLog 聚合对话与用户;user_agent_permissions 统计授权人数;
|
||||
PermissionRequest 统计待审;Feedback JOIN ChatLog 统计均分。不含 API Key 等配置敏感字段。
|
||||
|
||||
Args:
|
||||
range_key: 时间范围 key(7d/30d/90d/180d/365d),非法值回退近一月。
|
||||
status: all | active | inactive,按 is_active 过滤。
|
||||
usage: all | used | unused,按时间范围内是否有对话过滤。
|
||||
q: 应用名称模糊搜索。
|
||||
sort: 排序字段,见 APPLICATION_REPORT_SORT_KEYS。
|
||||
order: asc | desc,默认 desc。
|
||||
page: 页码(从 1 起)。
|
||||
page_size: 每页条数,上限 APPLICATION_REPORT_PAGE_SIZE_MAX。
|
||||
|
||||
Returns:
|
||||
含 summary / items / 分页字段的字典。
|
||||
"""
|
||||
normalized_range, since = resolve_usage_range_start(range_key)
|
||||
status_key = (status or 'all').strip().lower()
|
||||
if status_key not in {'all', 'active', 'inactive'}:
|
||||
status_key = 'all'
|
||||
usage_key = (usage or 'all').strip().lower()
|
||||
if usage_key not in {'all', 'used', 'unused'}:
|
||||
usage_key = 'all'
|
||||
sort_key = (sort or DEFAULT_APPLICATION_SORT).strip().lower()
|
||||
if sort_key not in APPLICATION_REPORT_SORT_KEYS:
|
||||
sort_key = DEFAULT_APPLICATION_SORT
|
||||
order_key = (order or 'desc').strip().lower()
|
||||
if order_key not in {'asc', 'desc'}:
|
||||
order_key = 'desc'
|
||||
page = max(1, int(page or 1))
|
||||
page_size = max(1, min(int(page_size or 20), APPLICATION_REPORT_PAGE_SIZE_MAX))
|
||||
keyword = (q or '').strip()
|
||||
|
||||
# [STEP 1] 子查询:时间范围内对话 / 授权 / 待审 / 评分
|
||||
chat_stats = (
|
||||
db.session.query(
|
||||
ChatLog.agent_id.label('agent_id'),
|
||||
func.count(ChatLog.id).label('chat_count'),
|
||||
func.count(func.distinct(ChatLog.user_id)).label('unique_users'),
|
||||
func.max(ChatLog.created_at).label('last_active_at'),
|
||||
func.coalesce(func.sum(ChatLog.tokens_used), 0).label('tokens_used'),
|
||||
func.avg(ChatLog.latency).label('avg_latency_ms'),
|
||||
)
|
||||
.filter(ChatLog.created_at >= since)
|
||||
.group_by(ChatLog.agent_id)
|
||||
.subquery()
|
||||
)
|
||||
auth_stats = (
|
||||
db.session.query(
|
||||
user_agent_permissions.c.agent_id.label('agent_id'),
|
||||
func.count(user_agent_permissions.c.user_id).label('authorized_users'),
|
||||
)
|
||||
.group_by(user_agent_permissions.c.agent_id)
|
||||
.subquery()
|
||||
)
|
||||
pending_stats = (
|
||||
db.session.query(
|
||||
PermissionRequest.agent_id.label('agent_id'),
|
||||
func.count(PermissionRequest.id).label('pending_requests'),
|
||||
)
|
||||
.filter(PermissionRequest.status == 'pending')
|
||||
.group_by(PermissionRequest.agent_id)
|
||||
.subquery()
|
||||
)
|
||||
feedback_stats = (
|
||||
db.session.query(
|
||||
ChatLog.agent_id.label('agent_id'),
|
||||
func.avg(Feedback.score).label('avg_score'),
|
||||
func.count(Feedback.id).label('feedback_count'),
|
||||
)
|
||||
.join(Feedback, Feedback.chat_log_id == ChatLog.id)
|
||||
.filter(ChatLog.created_at >= since)
|
||||
.group_by(ChatLog.agent_id)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
chat_count_col = func.coalesce(chat_stats.c.chat_count, 0)
|
||||
unique_users_col = func.coalesce(chat_stats.c.unique_users, 0)
|
||||
authorized_col = func.coalesce(auth_stats.c.authorized_users, 0)
|
||||
pending_col = func.coalesce(pending_stats.c.pending_requests, 0)
|
||||
tokens_col = func.coalesce(chat_stats.c.tokens_used, 0)
|
||||
|
||||
# [STEP 2] Agent 左连接各聚合,应用筛选
|
||||
query = (
|
||||
db.session.query(
|
||||
Agent.id,
|
||||
Agent.name,
|
||||
Agent.is_active,
|
||||
Agent.category,
|
||||
chat_count_col.label('chat_count'),
|
||||
unique_users_col.label('unique_users'),
|
||||
chat_stats.c.last_active_at,
|
||||
authorized_col.label('authorized_users'),
|
||||
pending_col.label('pending_requests'),
|
||||
feedback_stats.c.avg_score,
|
||||
func.coalesce(feedback_stats.c.feedback_count, 0).label('feedback_count'),
|
||||
tokens_col.label('tokens_used'),
|
||||
chat_stats.c.avg_latency_ms,
|
||||
)
|
||||
.outerjoin(chat_stats, chat_stats.c.agent_id == Agent.id)
|
||||
.outerjoin(auth_stats, auth_stats.c.agent_id == Agent.id)
|
||||
.outerjoin(pending_stats, pending_stats.c.agent_id == Agent.id)
|
||||
.outerjoin(feedback_stats, feedback_stats.c.agent_id == Agent.id)
|
||||
)
|
||||
if status_key == 'active':
|
||||
query = query.filter(Agent.is_active.is_(True))
|
||||
elif status_key == 'inactive':
|
||||
query = query.filter(Agent.is_active.is_(False))
|
||||
if usage_key == 'used':
|
||||
query = query.filter(chat_count_col > 0)
|
||||
elif usage_key == 'unused':
|
||||
query = query.filter(or_(chat_stats.c.chat_count.is_(None), chat_stats.c.chat_count == 0))
|
||||
if keyword:
|
||||
query = query.filter(Agent.name.ilike(f'%{keyword}%'))
|
||||
|
||||
# [STEP 3] 一次拉取筛选结果,内存排序分页(应用数量通常较小;兼容 SQLite 测试)
|
||||
filtered_rows = list(query.all())
|
||||
agent_total = len(filtered_rows)
|
||||
active_agents = sum(1 for row in filtered_rows if row.is_active)
|
||||
used_agents = sum(1 for row in filtered_rows if int(row.chat_count or 0) > 0)
|
||||
unused_agents = agent_total - used_agents
|
||||
pending_permission_total = sum(int(row.pending_requests or 0) for row in filtered_rows)
|
||||
|
||||
def _row_sort_key(row: Any) -> tuple:
|
||||
"""
|
||||
构造排序键:(是否空值, 业务值, 名称, id)。
|
||||
空值(无最近活跃 / 无评分)始终排在末尾。
|
||||
"""
|
||||
if sort_key == 'name':
|
||||
return (0, (row.name or '').lower(), row.name or '', row.id)
|
||||
if sort_key in {'chat_count', 'unique_users', 'authorized_users', 'pending_requests', 'tokens_used'}:
|
||||
return (0, int(getattr(row, sort_key) or 0), row.name or '', row.id)
|
||||
raw = getattr(row, sort_key, None)
|
||||
if raw is None:
|
||||
return (1, None, row.name or '', row.id)
|
||||
if sort_key == 'avg_score':
|
||||
return (0, float(raw), row.name or '', row.id)
|
||||
return (0, raw, row.name or '', row.id)
|
||||
|
||||
reverse = order_key == 'desc'
|
||||
non_null = [r for r in filtered_rows if _row_sort_key(r)[0] == 0]
|
||||
nulls = [r for r in filtered_rows if _row_sort_key(r)[0] == 1]
|
||||
non_null.sort(key=_row_sort_key, reverse=reverse)
|
||||
nulls.sort(key=lambda r: (r.name or '', r.id))
|
||||
filtered_rows = non_null + nulls
|
||||
|
||||
pages = max(1, math.ceil(agent_total / page_size)) if agent_total else 1
|
||||
page = min(page, pages)
|
||||
offset = (page - 1) * page_size
|
||||
page_rows = filtered_rows[offset:offset + page_size]
|
||||
|
||||
items = []
|
||||
for row in page_rows:
|
||||
avg_score = float(row.avg_score) if row.avg_score is not None else None
|
||||
avg_latency = float(row.avg_latency_ms) if row.avg_latency_ms is not None else None
|
||||
last_active = row.last_active_at.isoformat() if row.last_active_at else None
|
||||
items.append({
|
||||
'agent_id': row.id,
|
||||
'name': row.name,
|
||||
'is_active': bool(row.is_active),
|
||||
'category': row.category or '',
|
||||
'chat_count': int(row.chat_count or 0),
|
||||
'unique_users': int(row.unique_users or 0),
|
||||
'last_active_at': last_active,
|
||||
'authorized_users': int(row.authorized_users or 0),
|
||||
'pending_requests': int(row.pending_requests or 0),
|
||||
'avg_score': round(avg_score, 2) if avg_score is not None else None,
|
||||
'feedback_count': int(row.feedback_count or 0),
|
||||
'tokens_used': int(row.tokens_used or 0),
|
||||
'avg_latency_ms': round(avg_latency, 1) if avg_latency is not None else None,
|
||||
})
|
||||
|
||||
return {
|
||||
'range': normalized_range,
|
||||
'status': status_key,
|
||||
'usage': usage_key,
|
||||
'q': keyword,
|
||||
'sort': sort_key,
|
||||
'order': order_key,
|
||||
'summary': {
|
||||
'agent_total': agent_total,
|
||||
'active_agents': active_agents,
|
||||
'used_agents': used_agents,
|
||||
'unused_agents': unused_agents,
|
||||
'pending_permission_total': pending_permission_total,
|
||||
},
|
||||
'items': items,
|
||||
'total': agent_total,
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': pages,
|
||||
}
|
||||
|
||||
|
||||
def _apply_general_feedback_filters(query, query_params: dict[str, str]):
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in query_params.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if hasattr(GeneralFeedback, key):
|
||||
col = getattr(GeneralFeedback, key)
|
||||
elif key == 'real_name':
|
||||
col = User.real_name
|
||||
elif key == 'department':
|
||||
col = User.department
|
||||
else:
|
||||
continue
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
||||
"""通用反馈列表(报表页)。"""
|
||||
query = (
|
||||
db.session.query(
|
||||
GeneralFeedback,
|
||||
User.real_name.label('real_name'),
|
||||
User.department.label('department'),
|
||||
)
|
||||
.outerjoin(User, User.id == GeneralFeedback.user_id)
|
||||
)
|
||||
query = _apply_general_feedback_filters(query, query_params)
|
||||
query = query.order_by(desc(GeneralFeedback.created_at), desc(GeneralFeedback.id))
|
||||
try:
|
||||
limit = int(query_params.get('limit', 200))
|
||||
except (TypeError, ValueError):
|
||||
limit = 200
|
||||
limit = max(1, min(limit, 1000))
|
||||
items = query.limit(limit).all()
|
||||
rows = []
|
||||
for item, real_name, department in items:
|
||||
row = {}
|
||||
for col in item.__table__.columns:
|
||||
val = getattr(item, col.name)
|
||||
if isinstance(val, datetime):
|
||||
val = val.isoformat()
|
||||
row[col.name] = val
|
||||
row['real_name'] = real_name
|
||||
row['department'] = department
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def count_general_feedbacks_report(query_params: dict[str, str]) -> dict:
|
||||
"""通用反馈计数。"""
|
||||
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
||||
query = _apply_general_feedback_filters(query, query_params)
|
||||
total = query.count()
|
||||
return {'table': 'general_feedbacks', 'total': int(total)}
|
||||
|
||||
|
||||
def chat_logs_report_query():
|
||||
"""ChatLog JOIN User、Agent 基础查询。"""
|
||||
return (
|
||||
db.session.query(
|
||||
ChatLog,
|
||||
User.username.label('username'),
|
||||
User.real_name.label('real_name'),
|
||||
Agent.name.label('agent_name'),
|
||||
)
|
||||
.join(User, User.id == ChatLog.user_id)
|
||||
.join(Agent, Agent.id == ChatLog.agent_id)
|
||||
)
|
||||
|
||||
|
||||
def serialize_chat_log_report_row(
|
||||
log: ChatLog,
|
||||
username: str | None,
|
||||
real_name: str | None,
|
||||
agent_name: str | None,
|
||||
) -> dict:
|
||||
"""ChatLog 报表行序列化。"""
|
||||
return {
|
||||
'id': log.id,
|
||||
'agent_name': agent_name or '',
|
||||
'username': username or '',
|
||||
'real_name': real_name or '',
|
||||
'created_at': log.created_at.isoformat() if log.created_at else None,
|
||||
'query': log.query,
|
||||
'answer': log.answer,
|
||||
'tokens_used': log.tokens_used,
|
||||
}
|
||||
|
||||
|
||||
def apply_chat_logs_report_filters(query, query_params: dict[str, str]):
|
||||
"""对聊天日志报表查询应用列筛选。"""
|
||||
reserved = {'limit', 'offset', 'page', 'page_size'}
|
||||
for key, value in query_params.items():
|
||||
if key in reserved or not value:
|
||||
continue
|
||||
if key == 'agent_name':
|
||||
query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'agent_id' and value.isdigit():
|
||||
query = query.filter(ChatLog.agent_id == int(value))
|
||||
elif key == 'username':
|
||||
query = query.filter(User.username.cast(db.String).ilike(f'%{value}%'))
|
||||
elif key == 'real_name':
|
||||
query = query.filter(User.real_name.cast(db.String).ilike(f'%{value}%'))
|
||||
elif hasattr(ChatLog, key):
|
||||
col = getattr(ChatLog, key)
|
||||
query = query.filter(col.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
def list_chat_logs_report(query_params: dict[str, str]) -> list[dict]:
|
||||
"""聊天日志报表列表(最多 100 条)。"""
|
||||
query = apply_chat_logs_report_filters(chat_logs_report_query(), query_params)
|
||||
query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
|
||||
items = query.limit(100).all()
|
||||
return [
|
||||
serialize_chat_log_report_row(log, username, real_name, agent_name)
|
||||
for log, username, real_name, agent_name in items
|
||||
]
|
||||
|
||||
|
||||
def count_chat_logs_report(query_params: dict[str, str]) -> dict:
|
||||
"""聊天日志报表计数。"""
|
||||
query = apply_chat_logs_report_filters(chat_logs_report_query(), query_params)
|
||||
total = query.count()
|
||||
return {'table': 'chat_logs', 'total': int(total or 0)}
|
||||
@@ -0,0 +1,445 @@
|
||||
"""
|
||||
backend/app/services/admin/training_exam_pdf_service.py
|
||||
|
||||
用途:把员工培训试题 PDF 解析成结构化题库,供 Agent extra_config.training_config 回填。
|
||||
依赖:models.AgentGuide、minio_service、pypdf、edkb_system PDF/OCR 技能。
|
||||
逻辑:优先读取已标记为 training_exam_pdf 的指南文件,先抽取 PDF 原生文本;若文本缺失或解析失败,再回退到 OCR 识别,最终把题目、选项、答案与解析返回给管理端表单继续人工校验。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from pypdf import PdfReader
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import AgentGuide
|
||||
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
|
||||
from app.services.minio_service import minio_service
|
||||
from edkb_system.contracts import Block, Context
|
||||
from edkb_system.skills import loader_pdf, ocr
|
||||
|
||||
_QUESTION_START_PATTERN = re.compile(r'^\s*(\d{1,3})\s*[\.\、\.\)]\s*(.+?)\s*$')
|
||||
_OPTION_PATTERN = re.compile(r'([A-D])\s*[\.\、\.\)\::]\s*')
|
||||
_INLINE_ANSWER_PATTERN = re.compile(r'答案\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
|
||||
_INLINE_EXPLANATION_PATTERN = re.compile(r'解析\s*[::]?\s*(.+)$', re.IGNORECASE)
|
||||
_ANSWER_PAIR_PATTERN = re.compile(r'(?:^|(?<=[\s,,;;]))(\d{1,3})\s*[\.\、\.\)]?\s*[::]?\s*(A|B|C|D|正确|错误|对|错|T|F|√|×)', re.IGNORECASE)
|
||||
_SECTION_HEADING_PATTERN = re.compile(r'^[一二三四五六七八九十]+[\.\、\.\)]\s*[^\n]*题')
|
||||
_BOOLEAN_PROMPT_HINT_PATTERN = re.compile(r'正确还是错误|对还是错|判断题|[\((]\s*[\))]|是否')
|
||||
_ANSWER_RANGE_PATTERN = re.compile(r'^(\d{1,3})\s*[-~-—至到]\s*(\d{1,3})\s+(.+)$')
|
||||
_BOOLEAN_TOKEN_PATTERN = re.compile(r'正确|错误|对|错|T|F|V|X|√|×', re.IGNORECASE)
|
||||
|
||||
|
||||
def _normalize_line_breaks(text: str) -> str:
|
||||
return str(text or '').replace('\r\n', '\n').replace('\r', '\n')
|
||||
|
||||
|
||||
def _normalize_spaces(text: str) -> str:
|
||||
return re.sub(r'[ \t\u3000]+', ' ', str(text or '')).strip()
|
||||
|
||||
|
||||
def _normalize_answer_token(raw_answer: str) -> str:
|
||||
answer = str(raw_answer or '').strip().upper()
|
||||
if answer in {'A', 'B', 'C', 'D'}:
|
||||
return answer.lower()
|
||||
if answer in {'正确', '对', 'T', 'V', '√', 'TRUE'}:
|
||||
return 'true'
|
||||
if answer in {'错误', '错', 'F', 'X', '×', 'FALSE'}:
|
||||
return 'false'
|
||||
return ''
|
||||
|
||||
|
||||
def _extract_pdf_text(raw_bytes: bytes) -> str:
|
||||
"""
|
||||
从 PDF 原始字节中抽取纯文本。
|
||||
|
||||
用途:为培训试题导入提供统一文本输入,避免每个管理接口重复组装 PdfReader。
|
||||
参数约束:raw_bytes 必须是 PDF 文件内容;若整份文件无可读文本,将由上层决定是否报错。
|
||||
"""
|
||||
reader = PdfReader(io.BytesIO(raw_bytes))
|
||||
page_texts: list[str] = []
|
||||
for page in reader.pages:
|
||||
text = _normalize_spaces(_normalize_line_breaks(page.extract_text() or ''))
|
||||
if text:
|
||||
page_texts.append(text)
|
||||
return '\n'.join(page_texts).strip()
|
||||
|
||||
|
||||
def _blocks_to_text(blocks: list[Block]) -> str:
|
||||
"""
|
||||
把 edkb_system 的段落/OCR 结果统一折叠成纯文本。
|
||||
|
||||
用途:扫描件 PDF 会先被 loader_pdf 切成 paragraph/image/ocr_text block,这里负责收敛成后续题库解析可消费的文本。
|
||||
参数约束:只拼接 paragraph 与 ocr_text,避免把图片元数据等噪音混入题干。
|
||||
"""
|
||||
lines: list[str] = []
|
||||
for block in blocks:
|
||||
if block.type not in {'paragraph', 'ocr_text'}:
|
||||
continue
|
||||
text = _normalize_line_breaks(block.text or '').strip()
|
||||
if not text:
|
||||
continue
|
||||
if block.type == 'ocr_text':
|
||||
if text.startswith('OCR_TEXT:'):
|
||||
text = text[len('OCR_TEXT:') :].strip()
|
||||
text = re.sub(r'(?m)^\s*-\s*', '', text).strip()
|
||||
if text:
|
||||
lines.append(text)
|
||||
return '\n'.join(lines).strip()
|
||||
|
||||
|
||||
def _extract_pdf_text_via_ocr(raw_bytes: bytes) -> tuple[str, list[str]]:
|
||||
"""
|
||||
使用仓库内置 PDF loader + OCR 管线提取扫描件文本。
|
||||
|
||||
用途:当 pypdf 拿不到可读文本,或题目结构解析失败时,回退到这条路径兼容图片型 PDF。
|
||||
参数约束:raw_bytes 必须是完整 PDF 字节;若当前环境未安装 rapidocr 相关依赖,会在 warnings 中返回原因而不是直接抛异常。
|
||||
"""
|
||||
temp_path: Path | None = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as temp_file:
|
||||
temp_file.write(raw_bytes)
|
||||
temp_path = Path(temp_file.name)
|
||||
|
||||
context = Context(file_type='pdf')
|
||||
blocks = loader_pdf.run({'file_path': str(temp_path)}, context)
|
||||
if any(block.type == 'image' for block in blocks):
|
||||
blocks = ocr.run(blocks, context)
|
||||
return _blocks_to_text(blocks), list(context.warnings)
|
||||
finally:
|
||||
if temp_path is not None:
|
||||
try:
|
||||
temp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _collect_candidate_lines(text: str) -> list[str]:
|
||||
normalized_text = _normalize_line_breaks(text)
|
||||
lines: list[str] = []
|
||||
for raw_line in normalized_text.split('\n'):
|
||||
line = _normalize_spaces(raw_line)
|
||||
if line:
|
||||
lines.append(line)
|
||||
return lines
|
||||
|
||||
|
||||
def _is_answer_sheet_line(line: str) -> bool:
|
||||
"""
|
||||
判断当前行是否更像“答案表”而不是题干。
|
||||
|
||||
用途:很多培训试卷会在末尾给出“1.B 2.A 3.正确”这类答案表;这些行不能再被当成题目块切进去,否则会污染上一题或额外生成伪题目。
|
||||
参数约束:仅识别高置信度答案行,避免误伤正常题干。
|
||||
"""
|
||||
normalized_line = _normalize_spaces(line)
|
||||
if not normalized_line:
|
||||
return False
|
||||
if '答案' in normalized_line:
|
||||
return True
|
||||
range_match = _ANSWER_RANGE_PATTERN.match(normalized_line)
|
||||
if range_match:
|
||||
token_matches = _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3))
|
||||
expected_count = int(range_match.group(2)) - int(range_match.group(1)) + 1
|
||||
if len(token_matches) >= max(expected_count - 1, 2):
|
||||
return True
|
||||
matches = list(_ANSWER_PAIR_PATTERN.finditer(normalized_line))
|
||||
return len(matches) >= 2
|
||||
|
||||
|
||||
def _extract_answer_sequence(lines: list[str]) -> list[str]:
|
||||
"""
|
||||
按文本顺序提取整卷答案序列。
|
||||
|
||||
用途:当 PDF 内部“单选题/判断题”分别从 1 重新编号,或答案表使用整卷顺序编号时,单靠题号已无法稳定对齐,这里保留顺序型答案用于按题目出现顺序兜底匹配。
|
||||
参数约束:只从明确的答案行提取,避免把题干中的 A/B/C/D 选项误收进答案序列。
|
||||
"""
|
||||
answers: list[str] = []
|
||||
for line in lines:
|
||||
if not _is_answer_sheet_line(line):
|
||||
continue
|
||||
range_match = _ANSWER_RANGE_PATTERN.match(_normalize_spaces(line))
|
||||
if range_match:
|
||||
for raw_token in _BOOLEAN_TOKEN_PATTERN.findall(range_match.group(3)):
|
||||
answer = _normalize_answer_token(raw_token)
|
||||
if answer:
|
||||
answers.append(answer)
|
||||
continue
|
||||
for match in _ANSWER_PAIR_PATTERN.finditer(line):
|
||||
answer = _normalize_answer_token(match.group(2))
|
||||
if answer:
|
||||
answers.append(answer)
|
||||
return answers
|
||||
|
||||
|
||||
def _extract_answer_map(lines: list[str]) -> dict[int, str]:
|
||||
"""
|
||||
从“参考答案”区域提取题号与答案映射。
|
||||
|
||||
用途:很多试卷会把题目和答案分成两段展示,这里先把独立答案表收集出来,供后续题目块回填正确答案。
|
||||
参数约束:只解析明显的答案行,避免把题干里的选项误判成答案。
|
||||
"""
|
||||
answer_map: dict[int, str] = {}
|
||||
for line in lines:
|
||||
matches = list(_ANSWER_PAIR_PATTERN.finditer(line))
|
||||
if not _is_answer_sheet_line(line):
|
||||
continue
|
||||
for match in matches:
|
||||
question_no = int(match.group(1))
|
||||
answer = _normalize_answer_token(match.group(2))
|
||||
if answer and question_no not in answer_map:
|
||||
answer_map[question_no] = answer
|
||||
return answer_map
|
||||
|
||||
|
||||
def _split_question_blocks(lines: list[str]) -> list[tuple[int, str]]:
|
||||
blocks: list[tuple[int, str]] = []
|
||||
current_no: int | None = None
|
||||
current_lines: list[str] = []
|
||||
|
||||
for line in lines:
|
||||
if _SECTION_HEADING_PATTERN.match(line):
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
current_no = None
|
||||
current_lines = []
|
||||
continue
|
||||
question_match = _QUESTION_START_PATTERN.match(line)
|
||||
if question_match:
|
||||
if _is_answer_sheet_line(line) and '答案' not in line:
|
||||
continue
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
current_no = int(question_match.group(1))
|
||||
current_lines = [question_match.group(2)]
|
||||
continue
|
||||
if _is_answer_sheet_line(line):
|
||||
continue
|
||||
if current_no is not None:
|
||||
current_lines.append(line)
|
||||
|
||||
if current_no is not None and current_lines:
|
||||
blocks.append((current_no, ' '.join(current_lines).strip()))
|
||||
return blocks
|
||||
|
||||
|
||||
def _extract_inline_answer(block_text: str) -> str:
|
||||
match = _INLINE_ANSWER_PATTERN.search(block_text)
|
||||
if not match:
|
||||
return ''
|
||||
return _normalize_answer_token(match.group(1))
|
||||
|
||||
|
||||
def _extract_inline_explanation(block_text: str) -> str:
|
||||
match = _INLINE_EXPLANATION_PATTERN.search(block_text)
|
||||
return _normalize_spaces(match.group(1)) if match else ''
|
||||
|
||||
|
||||
def _strip_inline_meta(block_text: str) -> str:
|
||||
cleaned = _INLINE_EXPLANATION_PATTERN.sub('', block_text)
|
||||
cleaned = _INLINE_ANSWER_PATTERN.sub('', cleaned)
|
||||
return _normalize_spaces(cleaned)
|
||||
|
||||
|
||||
def _build_boolean_question(question_no: int, prompt: str, answer: str, explanation: str) -> dict[str, Any] | None:
|
||||
if answer not in {'true', 'false'}:
|
||||
return None
|
||||
return {
|
||||
'id': f'q{question_no}',
|
||||
'type': 'boolean',
|
||||
'prompt': prompt,
|
||||
'answer': answer,
|
||||
'explanation': explanation,
|
||||
}
|
||||
|
||||
|
||||
def _build_answer_candidates(
|
||||
*,
|
||||
inline_answer: str,
|
||||
mapped_answer: str,
|
||||
ordered_answer: str,
|
||||
) -> list[str]:
|
||||
"""
|
||||
组合单题可用的答案候选,并按可信度排序。
|
||||
|
||||
用途:优先使用题干内联答案,其次使用题号映射;若 PDF 存在分节重编号,再退回整卷顺序答案,尽量把判断题补齐。
|
||||
参数约束:返回结果会去重,避免同一答案在多种来源下重复尝试。
|
||||
"""
|
||||
candidates: list[str] = []
|
||||
for raw in (inline_answer, mapped_answer, ordered_answer):
|
||||
value = _normalize_answer_token(raw)
|
||||
if value and value not in candidates:
|
||||
candidates.append(value)
|
||||
return candidates
|
||||
|
||||
|
||||
def _looks_like_boolean_question(prompt: str, option_matches: list[re.Match[str]], answer_candidates: list[str]) -> bool:
|
||||
"""
|
||||
判断题型是否更接近判断题。
|
||||
|
||||
用途:避免答案表错位时把带 A/B/C/D 选项的单选题误判成判断题,同时允许“句子 + ( )”这类常见判断题格式被识别。
|
||||
参数约束:只在没有完整选项结构时才考虑判断题,单选题仍以选项结构为主。
|
||||
"""
|
||||
if len(option_matches) >= 2:
|
||||
return False
|
||||
if any(answer in {'true', 'false'} for answer in answer_candidates):
|
||||
return True
|
||||
return bool(_BOOLEAN_PROMPT_HINT_PATTERN.search(prompt))
|
||||
|
||||
|
||||
def _build_single_choice_question(question_no: int, prompt: str, option_matches: list[re.Match[str]], answer: str, explanation: str) -> dict[str, Any] | None:
|
||||
if len(option_matches) < 2:
|
||||
return None
|
||||
|
||||
options: list[dict[str, str]] = []
|
||||
for index, match in enumerate(option_matches):
|
||||
start = match.end()
|
||||
end = option_matches[index + 1].start() if index + 1 < len(option_matches) else len(prompt)
|
||||
label = _normalize_spaces(prompt[start:end])
|
||||
option_id = match.group(1).lower()
|
||||
if not label:
|
||||
continue
|
||||
options.append({'id': option_id, 'label': f"{match.group(1).upper()}. {label}"})
|
||||
|
||||
if len(options) < 2 or answer not in {item['id'] for item in options}:
|
||||
return None
|
||||
|
||||
prompt_text = _normalize_spaces(prompt[:option_matches[0].start()])
|
||||
if not prompt_text:
|
||||
return None
|
||||
|
||||
return {
|
||||
'id': f'q{question_no}',
|
||||
'type': 'single',
|
||||
'prompt': prompt_text,
|
||||
'answer': answer,
|
||||
'explanation': explanation,
|
||||
'options': options,
|
||||
}
|
||||
|
||||
|
||||
def parse_training_question_bank_text(text: str) -> dict[str, Any]:
|
||||
"""
|
||||
将 PDF 抽出的纯文本解析成培训题库。
|
||||
|
||||
用途:给管理后台的“从试题 PDF 导入题库”提供核心解析逻辑;优先保证答题链路可用,无法确定答案的题目宁可跳过也不乱导入。
|
||||
参数约束:text 应来自同一份试卷文本;若完全无法识别题目或答案,调用方应直接提示人工处理。
|
||||
"""
|
||||
lines = _collect_candidate_lines(text)
|
||||
answer_map = _extract_answer_map(lines)
|
||||
answer_sequence = _extract_answer_sequence(lines)
|
||||
question_blocks = _split_question_blocks(lines)
|
||||
question_bank: list[dict[str, Any]] = []
|
||||
skipped_questions: list[int] = []
|
||||
|
||||
# [STEP 1] 先按题号切块,再对每一块做题型、答案和解析判定,避免跨题串行污染。
|
||||
for index, (question_no, raw_block) in enumerate(question_blocks):
|
||||
inline_answer = _extract_inline_answer(raw_block)
|
||||
explanation = _extract_inline_explanation(raw_block)
|
||||
block_text = _strip_inline_meta(raw_block)
|
||||
option_matches = list(_OPTION_PATTERN.finditer(block_text))
|
||||
answer_candidates = _build_answer_candidates(
|
||||
inline_answer=inline_answer,
|
||||
mapped_answer=answer_map.get(question_no, ''),
|
||||
ordered_answer=answer_sequence[index] if index < len(answer_sequence) else '',
|
||||
)
|
||||
|
||||
if _looks_like_boolean_question(block_text, option_matches, answer_candidates):
|
||||
for answer in answer_candidates:
|
||||
question_payload = _build_boolean_question(
|
||||
question_no=question_no,
|
||||
prompt=block_text,
|
||||
answer=answer,
|
||||
explanation=explanation,
|
||||
)
|
||||
if question_payload:
|
||||
question_payload['id'] = f'q{len(question_bank) + 1}'
|
||||
question_bank.append(question_payload)
|
||||
break
|
||||
else:
|
||||
question_payload = None
|
||||
if question_payload:
|
||||
continue
|
||||
|
||||
for answer in answer_candidates:
|
||||
question_payload = _build_single_choice_question(
|
||||
question_no=question_no,
|
||||
prompt=block_text,
|
||||
option_matches=option_matches,
|
||||
answer=answer,
|
||||
explanation=explanation,
|
||||
)
|
||||
if question_payload:
|
||||
question_payload['id'] = f'q{len(question_bank) + 1}'
|
||||
question_bank.append(question_payload)
|
||||
break
|
||||
else:
|
||||
question_payload = None
|
||||
if question_payload:
|
||||
continue
|
||||
|
||||
skipped_questions.append(question_no)
|
||||
|
||||
if not question_bank:
|
||||
raise ValidationError('未能从试题 PDF 中识别出可用题目,请检查 PDF 是否包含可复制文本与标准答案')
|
||||
|
||||
return {
|
||||
'question_bank': question_bank,
|
||||
'parsed_count': len(question_bank),
|
||||
'skipped_question_numbers': skipped_questions,
|
||||
}
|
||||
|
||||
|
||||
def parse_training_question_bank_from_guide(agent_id: int, guide_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
从指定 Agent 的试题 PDF 指南中解析题库。
|
||||
|
||||
用途:管理后台点击“从已上传试题 PDF 导入”时使用,优先读取显式标记为 training_exam_pdf 的资料。
|
||||
参数约束:guide_id 若传入,必须属于当前 agent 且文件类型为 pdf。
|
||||
"""
|
||||
query = db.session.query(AgentGuide).filter(AgentGuide.agent_id == agent_id)
|
||||
if guide_id is not None:
|
||||
query = query.filter(AgentGuide.id == guide_id)
|
||||
query = query.filter(AgentGuide.file_type == 'pdf')
|
||||
guide = query.order_by(AgentGuide.sort_order.asc(), AgentGuide.id.desc()).first()
|
||||
if not guide:
|
||||
raise NotFoundError('Training exam PDF guide not found')
|
||||
if guide.guide_usage != GUIDE_USAGE_TRAINING_EXAM_PDF:
|
||||
raise ValidationError('Selected guide is not marked as training exam PDF')
|
||||
|
||||
raw_bytes = minio_service.get_file_bytes(guide.file_path)
|
||||
text = _extract_pdf_text(raw_bytes)
|
||||
ocr_text = ''
|
||||
ocr_warnings: list[str] = []
|
||||
extraction_mode = 'pdf_text'
|
||||
|
||||
# [STEP 1] 先尝试 PDF 原生文本,速度快且不会引入 OCR 噪音。
|
||||
if text:
|
||||
try:
|
||||
parsed = parse_training_question_bank_text(text)
|
||||
except ValidationError as primary_error:
|
||||
# [STEP 2] 原生文本存在但结构解析失败时,再尝试 OCR,兼容“页面能选中文本但题号/答案错位”的扫描型 PDF。
|
||||
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
|
||||
if not ocr_text or ocr_text == text:
|
||||
raise primary_error
|
||||
parsed = parse_training_question_bank_text(ocr_text)
|
||||
extraction_mode = 'ocr_fallback'
|
||||
else:
|
||||
# [STEP 2] 完全拿不到 PDF 文本时,直接走 OCR;若 OCR 依旧为空,则给管理端明确报错并带回诊断 warnings。
|
||||
ocr_text, ocr_warnings = _extract_pdf_text_via_ocr(raw_bytes)
|
||||
if not ocr_text:
|
||||
raise ValidationError(
|
||||
'试题 PDF 未提取到可读文本,请检查是否为扫描件或图片 PDF,并确认 OCR 依赖已正确安装',
|
||||
details={'ocr_warnings': ocr_warnings},
|
||||
)
|
||||
parsed = parse_training_question_bank_text(ocr_text)
|
||||
extraction_mode = 'ocr'
|
||||
|
||||
parsed['guide_id'] = guide.id
|
||||
parsed['guide_file_name'] = guide.file_name
|
||||
parsed['extraction_mode'] = extraction_mode
|
||||
parsed['extraction_warnings'] = ocr_warnings
|
||||
return parsed
|
||||
@@ -1,5 +1,339 @@
|
||||
"""
|
||||
backend/app/services/admin/user_service.py
|
||||
|
||||
用途:管理端用户 CRUD、权限分配。
|
||||
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service。
|
||||
逻辑:由 api/admin/users.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.services.auth import casdoor_service
|
||||
from app.services.user_admin import delete_admin_users
|
||||
|
||||
|
||||
def empty_to_none(value):
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str) and value.strip() == '':
|
||||
return None
|
||||
return value
|
||||
|
||||
|
||||
def is_valid_email(email: str) -> bool:
|
||||
if not isinstance(email, str):
|
||||
return False
|
||||
email = email.strip()
|
||||
if len(email) > 254:
|
||||
return False
|
||||
pattern = r'^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$'
|
||||
return re.match(pattern, email) is not None
|
||||
|
||||
|
||||
def raise_user_integrity_conflict(exc: IntegrityError) -> None:
|
||||
message = str(getattr(exc, 'orig', exc))
|
||||
if 'users_email_key' in message:
|
||||
raise ConflictError('Email already exists', code='USER.EMAIL_EXISTS')
|
||||
if 'users_employee_id_key' in message:
|
||||
raise ConflictError('Employee ID already exists', code='USER.EMPLOYEE_ID_EXISTS')
|
||||
if 'users_phone_number_key' in message:
|
||||
raise ConflictError('Phone number already exists', code='USER.PHONE_EXISTS')
|
||||
if 'users_username_key' in message or 'ix_users_username' in message:
|
||||
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS')
|
||||
raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT')
|
||||
|
||||
|
||||
def assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None:
|
||||
checks = (
|
||||
('email', 'USER.EMAIL_EXISTS', 'Email already exists'),
|
||||
('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'),
|
||||
('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'),
|
||||
)
|
||||
for field, code, message in checks:
|
||||
value = fields.get(field)
|
||||
if value is None:
|
||||
continue
|
||||
query = db.session.query(User.id).filter(getattr(User, field) == value)
|
||||
if exclude_user_id is not None:
|
||||
query = query.filter(User.id != exclude_user_id)
|
||||
if query.first():
|
||||
raise ConflictError(message, code=code, details={'field': field})
|
||||
|
||||
|
||||
def serialize_admin_user(user: User) -> dict:
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'email': user.email,
|
||||
'department': user.department,
|
||||
'role': user.role,
|
||||
'status': user.status,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'phone_number': user.phone_number,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'agent_ids': [agent.id for agent in user.agents],
|
||||
}
|
||||
|
||||
|
||||
def apply_users_filters(query, query_params: dict[str, str]):
|
||||
if query_params.get('hide_rejected', 'false').lower() == 'true':
|
||||
query = query.filter(User.status != 'rejected')
|
||||
filter_columns = {
|
||||
'username': User.username,
|
||||
'email': User.email,
|
||||
'department': User.department,
|
||||
'role': User.role,
|
||||
'status': User.status,
|
||||
'real_name': User.real_name,
|
||||
'employee_id': User.employee_id,
|
||||
'phone_number': User.phone_number,
|
||||
}
|
||||
for key, column in filter_columns.items():
|
||||
value = (query_params.get(key) or '').strip()
|
||||
if value:
|
||||
query = query.filter(column.cast(db.String).ilike(f'%{value}%'))
|
||||
return query
|
||||
|
||||
|
||||
# 用户列表允许的排序列(与前端「用户 / 部门」表头对应)
|
||||
USER_SORT_COLUMNS = {
|
||||
'username': User.username,
|
||||
'department': User.department,
|
||||
}
|
||||
|
||||
|
||||
def resolve_users_order_by(query_params: dict[str, str]):
|
||||
"""
|
||||
解析 sort_by / sort_dir,返回 order_by 列元组。
|
||||
|
||||
核心逻辑:仅允许 username、department;非法值回退按 id 升序;同值用 id 稳定次序。
|
||||
|
||||
Args:
|
||||
query_params: 请求查询参数(含 sort_by、sort_dir)。
|
||||
|
||||
Returns:
|
||||
可直接传入 Query.order_by(*...) 的列表达式元组。
|
||||
"""
|
||||
sort_by = (query_params.get('sort_by') or '').strip().lower()
|
||||
sort_dir = (query_params.get('sort_dir') or 'asc').strip().lower()
|
||||
column = USER_SORT_COLUMNS.get(sort_by)
|
||||
if column is None:
|
||||
return (User.id.asc(),)
|
||||
primary = column.desc() if sort_dir == 'desc' else column.asc()
|
||||
return (primary, User.id.asc())
|
||||
|
||||
|
||||
def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
||||
query = apply_users_filters(db.session.query(User), query_params)
|
||||
order_by = resolve_users_order_by(query_params)
|
||||
if 'page' not in query_params:
|
||||
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
||||
return [serialize_admin_user(u) for u in users]
|
||||
|
||||
try:
|
||||
page = int(query_params.get('page') or 1)
|
||||
except (TypeError, ValueError):
|
||||
page = 1
|
||||
try:
|
||||
page_size = int(query_params.get('page_size') or 20)
|
||||
except (TypeError, ValueError):
|
||||
page_size = 20
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(100, page_size))
|
||||
|
||||
total = query.count()
|
||||
pages = max(1, (total + page_size - 1) // page_size) if total else 1
|
||||
if page > pages:
|
||||
page = pages
|
||||
|
||||
users = (
|
||||
query.options(joinedload(User.agents))
|
||||
.order_by(*order_by)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
'items': [serialize_admin_user(u) for u in users],
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': pages,
|
||||
}
|
||||
|
||||
|
||||
def create_user(data: dict[str, Any]) -> dict:
|
||||
required_field_errors = (
|
||||
('username', 'USER.USERNAME_REQUIRED', 'Username is required'),
|
||||
('password', 'USER.PASSWORD_REQUIRED', 'Password is required'),
|
||||
('email', 'USER.EMAIL_REQUIRED', 'Email is required'),
|
||||
('real_name', 'USER.REAL_NAME_REQUIRED', 'Real name is required'),
|
||||
('employee_id', 'USER.EMPLOYEE_ID_REQUIRED', 'Employee ID is required'),
|
||||
('phone_number', 'USER.PHONE_REQUIRED', 'Phone number is required'),
|
||||
)
|
||||
for field, code, message in required_field_errors:
|
||||
if empty_to_none(data.get(field)) is None:
|
||||
raise AppError(code=code, message=message, http_status=400, details={'field': field})
|
||||
if db.session.query(User).filter_by(username=data['username']).first():
|
||||
raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS', details={'field': 'username'})
|
||||
email = empty_to_none(data.get('email'))
|
||||
if not is_valid_email(email):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
assert_user_unique_fields(
|
||||
None,
|
||||
email=email,
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user = User(
|
||||
username=data['username'],
|
||||
email=email,
|
||||
department=empty_to_none(data.get('department')),
|
||||
role=data.get('role', 'user'),
|
||||
status=data.get('status', 'active'),
|
||||
real_name=empty_to_none(data.get('real_name')),
|
||||
employee_id=empty_to_none(data.get('employee_id')),
|
||||
phone_number=empty_to_none(data.get('phone_number')),
|
||||
)
|
||||
user.set_feature_permissions(data.get('feature_permissions'))
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
try:
|
||||
if data.get('agent_ids'):
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
casdoor_service.sync_create_user(
|
||||
username=user.username,
|
||||
password=data['password'],
|
||||
email=email,
|
||||
real_name=user.real_name,
|
||||
phone_number=user.phone_number,
|
||||
status=user.status,
|
||||
department=user.department,
|
||||
)
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise_user_integrity_conflict(exc)
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
db.session.rollback()
|
||||
casdoor_service.raise_add_user_error(exc)
|
||||
return {'id': user.id}
|
||||
|
||||
|
||||
def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
if 'email' in data:
|
||||
email = empty_to_none(data.get('email'))
|
||||
if email is not None and (not is_valid_email(email)):
|
||||
raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'})
|
||||
unique_updates = {
|
||||
field: empty_to_none(data[field])
|
||||
for field in ('email', 'employee_id', 'phone_number')
|
||||
if field in data
|
||||
}
|
||||
assert_user_unique_fields(user_id, **unique_updates)
|
||||
new_password = empty_to_none(data.get('password'))
|
||||
try:
|
||||
for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||
if key in data:
|
||||
if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||
setattr(user, key, empty_to_none(data[key]))
|
||||
else:
|
||||
setattr(user, key, data[key])
|
||||
if 'feature_permissions' in data or 'role' in data:
|
||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||
user.set_feature_permissions(permissions_payload)
|
||||
if new_password:
|
||||
user.set_password(new_password)
|
||||
if 'agent_ids' in data:
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||
user.agents = agents
|
||||
if new_password:
|
||||
casdoor_service.sync_update_user(user, new_password=new_password)
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise_user_integrity_conflict(exc)
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
db.session.rollback()
|
||||
casdoor_service.raise_set_password_error(exc)
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def cleanup_rejected_users() -> dict:
|
||||
rejected_ids = [row[0] for row in db.session.query(User.id).filter_by(status='rejected').all()]
|
||||
cnt = delete_admin_users(rejected_ids)
|
||||
db.session.commit()
|
||||
return {'deleted_count': cnt}
|
||||
|
||||
|
||||
def batch_delete_users(user_ids: list[Any], *, current_user_id: int | None) -> dict:
|
||||
target_ids = [uid for uid in user_ids if str(uid) != str(current_user_id)]
|
||||
if not target_ids:
|
||||
raise ValidationError('No valid users')
|
||||
try:
|
||||
cnt = delete_admin_users(target_ids)
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(
|
||||
code='USER.DELETE_BLOCKED',
|
||||
message='Unable to delete user because related records still exist',
|
||||
http_status=409,
|
||||
details={'reason': str(getattr(exc, 'orig', exc))},
|
||||
) from exc
|
||||
return {'deleted_count': cnt}
|
||||
|
||||
|
||||
def delete_user(user_id: int, *, current_user_id: int | None) -> dict:
|
||||
if current_user_id is not None and str(current_user_id) == str(user_id):
|
||||
raise ValidationError('Cannot delete current user')
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
try:
|
||||
delete_admin_users([user_id])
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(
|
||||
code='USER.DELETE_BLOCKED',
|
||||
message='Unable to delete user because related records still exist',
|
||||
http_status=409,
|
||||
details={'reason': str(getattr(exc, 'orig', exc))},
|
||||
) from exc
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def approve_user(user_id: int) -> dict:
|
||||
user = db.session.get(User, user_id)
|
||||
if user:
|
||||
user.status = 'active'
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
|
||||
|
||||
def reject_user(user_id: int) -> dict:
|
||||
user = db.session.get(User, user_id)
|
||||
if user:
|
||||
user.status = 'rejected'
|
||||
db.session.commit()
|
||||
return {'status': 'ok'}
|
||||
@@ -0,0 +1,576 @@
|
||||
"""
|
||||
backend/app/services/admin/wecom_admin_service.py
|
||||
|
||||
用途:管理端企微绑定、配置、诊断与 OA userid 同步。
|
||||
依赖:wecom_auth_service、oa_wecom_sync、env_persistence、models。
|
||||
逻辑:由 api/admin/wecom.py 调用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.config.env_persistence import persist_env_settings
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, LoginAudit, User, WecomNotifyAudit
|
||||
from app.services.auth import wecom_auth_service
|
||||
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
|
||||
|
||||
|
||||
def serialize_debug_match_user(user: User) -> dict:
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'real_name': user.real_name,
|
||||
'employee_id': user.employee_id,
|
||||
'phone_number': user.phone_number,
|
||||
'email': user.email,
|
||||
'status': user.status,
|
||||
'wecom_userid': user.wecom_userid,
|
||||
'wecom_unionid': user.wecom_unionid,
|
||||
}
|
||||
|
||||
|
||||
def build_match_preview(identity: dict, rules: list[str], operator: str) -> dict:
|
||||
bind_mode = wecom_auth_service.get_first_login_bind_mode()
|
||||
preview = {
|
||||
'bind_mode': bind_mode,
|
||||
'rules': {'fields': rules, 'operator': operator},
|
||||
'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)),
|
||||
}
|
||||
bound_user = None
|
||||
if identity.get('wecom_userid'):
|
||||
bound_user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first()
|
||||
if not bound_user and identity.get('wecom_unionid'):
|
||||
bound_user = db.session.query(User).filter_by(wecom_unionid=identity['wecom_unionid']).first()
|
||||
if bound_user:
|
||||
preview['decision'] = 'already_bound'
|
||||
preview['bound_user'] = serialize_debug_match_user(bound_user)
|
||||
return preview
|
||||
if bind_mode == 'input_verify':
|
||||
preview['decision'] = 'input_verification_required'
|
||||
preview['allowed_fields'] = wecom_auth_service.get_first_login_input_fields()
|
||||
return preview
|
||||
matched_users, missing_fields = wecom_auth_service.find_users_by_match_rules(identity, rules, operator)
|
||||
preview['missing_fields'] = missing_fields
|
||||
preview['matched_users'] = [serialize_debug_match_user(user) for user in matched_users]
|
||||
if missing_fields:
|
||||
preview['decision'] = 'missing_match_fields'
|
||||
elif len(matched_users) == 1:
|
||||
preview['decision'] = 'matched_existing_user'
|
||||
elif len(matched_users) > 1:
|
||||
preview['decision'] = 'ambiguous_match'
|
||||
elif preview['auto_create_user']:
|
||||
preview['decision'] = 'would_auto_create_user'
|
||||
else:
|
||||
preview['decision'] = 'bind_required'
|
||||
return preview
|
||||
|
||||
|
||||
def debug_user_by_code(code: str) -> dict:
|
||||
"""通过 OAuth code 拉取企微用户并返回匹配预览(管理端诊断)。"""
|
||||
if not wecom_auth_service.is_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
code = str(code or '').strip()
|
||||
if not code:
|
||||
raise ValidationError('code is required')
|
||||
|
||||
access_token = wecom_auth_service.get_access_token()
|
||||
info_resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo',
|
||||
params={'access_token': access_token, 'code': code},
|
||||
timeout=8,
|
||||
)
|
||||
auth_info = info_resp.json()
|
||||
userid = auth_info.get('userid') or auth_info.get('UserId')
|
||||
openid = auth_info.get('openid') or auth_info.get('OpenId')
|
||||
payload = {'auth_info': auth_info}
|
||||
if auth_info.get('errcode') != 0:
|
||||
raise AppError(
|
||||
code='WECOM_AUTH_FAILED',
|
||||
message=f"WeCom auth failed: {auth_info.get('errmsg', 'unknown error')}",
|
||||
http_status=401,
|
||||
details={'auth_info': auth_info},
|
||||
)
|
||||
if not userid:
|
||||
raise AppError(
|
||||
code='WECOM_NOT_IN_AGENT_SCOPE',
|
||||
message='当前 code 对应的账号不在应用可见范围内,或不是本企业成员。',
|
||||
http_status=401,
|
||||
details={'auth_info': auth_info, 'openid': openid},
|
||||
)
|
||||
user_resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/user/get',
|
||||
params={'access_token': access_token, 'userid': userid},
|
||||
timeout=8,
|
||||
)
|
||||
wecom_user = user_resp.json()
|
||||
payload['wecom_user'] = wecom_user
|
||||
if wecom_user.get('errcode') != 0:
|
||||
raise AppError(
|
||||
code='WECOM_USER_FETCH_FAILED',
|
||||
message=f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}",
|
||||
http_status=401,
|
||||
details={'auth_info': auth_info, 'wecom_user': wecom_user},
|
||||
)
|
||||
identity = wecom_auth_service.extract_identity(wecom_user)
|
||||
rules, operator = wecom_auth_service.get_match_config()
|
||||
payload['normalized_identity'] = identity
|
||||
payload['match_preview'] = build_match_preview(identity, rules, operator)
|
||||
return payload
|
||||
|
||||
|
||||
def list_bindings(query_params: dict[str, str]) -> dict:
|
||||
bound_only = query_params.get('bound_only', 'false').lower() == 'true'
|
||||
keyword = (query_params.get('keyword') or '').strip()
|
||||
try:
|
||||
page = int(query_params.get('page') or 1)
|
||||
except (TypeError, ValueError):
|
||||
page = 1
|
||||
try:
|
||||
page_size = int(query_params.get('page_size') or 20)
|
||||
except (TypeError, ValueError):
|
||||
page_size = 20
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(100, page_size))
|
||||
|
||||
query = db.session.query(User)
|
||||
if bound_only:
|
||||
query = query.filter(User.wecom_userid.isnot(None))
|
||||
if keyword:
|
||||
pattern = f'%{keyword}%'
|
||||
query = query.filter(or_(
|
||||
User.username.ilike(pattern),
|
||||
User.real_name.ilike(pattern),
|
||||
User.employee_id.ilike(pattern),
|
||||
User.wecom_userid.ilike(pattern),
|
||||
))
|
||||
|
||||
total = query.count()
|
||||
pages = max(1, (total + page_size - 1) // page_size) if total else 1
|
||||
if page > pages:
|
||||
page = pages
|
||||
|
||||
users = (
|
||||
query.order_by(User.id.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
{
|
||||
'id': u.id,
|
||||
'username': u.username,
|
||||
'real_name': u.real_name,
|
||||
'employee_id': u.employee_id,
|
||||
'email': u.email,
|
||||
'role': u.role,
|
||||
'status': u.status,
|
||||
'wecom_userid': u.wecom_userid,
|
||||
'wecom_unionid': u.wecom_unionid,
|
||||
'bound': bool(u.wecom_userid),
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
return {
|
||||
'items': items,
|
||||
'total': int(total),
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'pages': pages,
|
||||
}
|
||||
|
||||
|
||||
def bind_user(data: dict[str, Any]) -> dict:
|
||||
user_id = data.get('user_id')
|
||||
wecom_userid = data.get('wecom_userid')
|
||||
wecom_unionid = data.get('wecom_unionid')
|
||||
if not user_id or not wecom_userid:
|
||||
raise ValidationError('user_id and wecom_userid are required')
|
||||
try:
|
||||
user_id = int(user_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('user_id must be integer')
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
||||
if dup:
|
||||
raise ValidationError(f'wecom_userid already bound to user {dup.username}')
|
||||
if wecom_unionid:
|
||||
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
||||
if dup_union:
|
||||
raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}')
|
||||
user.wecom_userid = wecom_userid
|
||||
if wecom_unionid is not None:
|
||||
user.wecom_unionid = wecom_unionid
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'message': 'WeCom binding updated'}
|
||||
|
||||
|
||||
def unbind_user(data: dict[str, Any]) -> dict:
|
||||
user_id = data.get('user_id')
|
||||
if not user_id:
|
||||
raise ValidationError('user_id is required')
|
||||
try:
|
||||
user_id = int(user_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('user_id must be integer')
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
user.wecom_userid = None
|
||||
user.wecom_unionid = None
|
||||
db.session.commit()
|
||||
return {'status': 'ok', 'message': 'WeCom account unbound'}
|
||||
|
||||
|
||||
def provision_user(data: dict[str, Any]) -> tuple[dict, int]:
|
||||
create_user_flag = bool(data.get('create_user', True))
|
||||
user_data = data.get('user') or {}
|
||||
bind_data = data.get('bind') or {}
|
||||
user_id = data.get('user_id')
|
||||
permission_updated = False
|
||||
wecom_userid = (bind_data.get('wecom_userid') or '').strip()
|
||||
wecom_unionid = (bind_data.get('wecom_unionid') or '').strip()
|
||||
if not wecom_userid:
|
||||
raise ValidationError('bind.wecom_userid is required')
|
||||
|
||||
if create_user_flag:
|
||||
username = (user_data.get('username') or '').strip()
|
||||
if not username:
|
||||
raise ValidationError('user.username is required when create_user=true')
|
||||
if db.session.query(User).filter_by(username=username).first():
|
||||
raise ValidationError('Username exists')
|
||||
email = (user_data.get('email') or '').strip() or None
|
||||
employee_id = (user_data.get('employee_id') or '').strip() or None
|
||||
phone_number = (user_data.get('phone_number') or '').strip() or None
|
||||
if email and db.session.query(User).filter_by(email=email).first():
|
||||
raise ValidationError('Email already exists')
|
||||
if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first():
|
||||
raise ValidationError('Employee ID already exists')
|
||||
if phone_number and db.session.query(User).filter_by(phone_number=phone_number).first():
|
||||
raise ValidationError('Phone number already exists')
|
||||
user = User(
|
||||
username=username,
|
||||
email=email,
|
||||
department=user_data.get('department'),
|
||||
role=user_data.get('role', 'user'),
|
||||
status=user_data.get('status', 'active'),
|
||||
real_name=user_data.get('real_name'),
|
||||
employee_id=employee_id,
|
||||
phone_number=phone_number,
|
||||
)
|
||||
password = user_data.get('password')
|
||||
user.set_password(password or uuid.uuid4().hex)
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
binding_status = 'created'
|
||||
status_code = 201
|
||||
else:
|
||||
if user_id is None:
|
||||
user_id = user_data.get('id')
|
||||
if user_id is None:
|
||||
raise ValidationError('user_id is required when create_user=false')
|
||||
try:
|
||||
user_id = int(user_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('user_id must be integer')
|
||||
user = db.session.get(User, user_id)
|
||||
if not user:
|
||||
raise NotFoundError('User not found')
|
||||
binding_status = 'updated'
|
||||
status_code = 200
|
||||
|
||||
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
||||
if dup:
|
||||
db.session.rollback()
|
||||
raise ValidationError(f'wecom_userid already bound to user {dup.username}')
|
||||
if wecom_unionid:
|
||||
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
||||
if dup_union:
|
||||
db.session.rollback()
|
||||
raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}')
|
||||
user.wecom_userid = wecom_userid
|
||||
if wecom_unionid:
|
||||
user.wecom_unionid = wecom_unionid
|
||||
|
||||
if 'agent_ids' in data:
|
||||
agent_ids = data.get('agent_ids', [])
|
||||
if not isinstance(agent_ids, list):
|
||||
db.session.rollback()
|
||||
raise ValidationError('agent_ids must be array')
|
||||
if agent_ids:
|
||||
try:
|
||||
unique_ids = sorted({int(i) for i in agent_ids})
|
||||
except (TypeError, ValueError):
|
||||
db.session.rollback()
|
||||
raise ValidationError('agent_ids must be integer array')
|
||||
agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all()
|
||||
if len(agents) != len(unique_ids):
|
||||
db.session.rollback()
|
||||
raise ValidationError('Some agent_ids are invalid')
|
||||
user.agents = agents
|
||||
else:
|
||||
user.agents = []
|
||||
permission_updated = True
|
||||
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Provision failed due to data uniqueness conflict')
|
||||
|
||||
return (
|
||||
{
|
||||
'status': 'ok',
|
||||
'user_id': user.id,
|
||||
'binding': binding_status,
|
||||
'permission_updated': permission_updated,
|
||||
},
|
||||
status_code,
|
||||
)
|
||||
|
||||
|
||||
def list_login_audits(query_params: dict[str, str]) -> list[dict]:
|
||||
source = query_params.get('source')
|
||||
status = query_params.get('status')
|
||||
try:
|
||||
limit = max(1, min(int(query_params.get('limit', 100)), 500))
|
||||
except (TypeError, ValueError):
|
||||
limit = 100
|
||||
query = db.session.query(LoginAudit)
|
||||
if source:
|
||||
query = query.filter(LoginAudit.source == source)
|
||||
if status:
|
||||
query = query.filter(LoginAudit.status == status)
|
||||
rows = query.order_by(LoginAudit.created_at.desc()).limit(limit).all()
|
||||
return [
|
||||
{
|
||||
'id': r.id,
|
||||
'user_id': r.user_id,
|
||||
'username': r.username,
|
||||
'source': r.source,
|
||||
'status': r.status,
|
||||
'reason': r.reason,
|
||||
'error_code': r.error_code,
|
||||
'match_rules': r.match_rules,
|
||||
'match_operator': r.match_operator,
|
||||
'match_result': r.match_result,
|
||||
'wecom_userid': r.wecom_userid,
|
||||
'ip': r.ip,
|
||||
'user_agent': r.user_agent,
|
||||
'created_at': r.created_at.isoformat() if r.created_at else None,
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
|
||||
def serialize_notify_settings() -> dict:
|
||||
return {
|
||||
'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)),
|
||||
'base_url': current_app.config.get('WECOM_NOTIFY_BASE_URL') or '',
|
||||
'events': [x for x in str(current_app.config.get('WECOM_NOTIFY_EVENTS', '')).split(',') if x],
|
||||
}
|
||||
|
||||
|
||||
def update_notify_settings(data: dict[str, Any]) -> dict:
|
||||
updates = {}
|
||||
if 'enabled' in data:
|
||||
updates['WECOM_NOTIFY_ENABLED'] = bool(data.get('enabled'))
|
||||
if 'base_url' in data:
|
||||
updates['WECOM_NOTIFY_BASE_URL'] = str(data.get('base_url') or '').strip()
|
||||
if 'events' in data:
|
||||
events = data.get('events') or []
|
||||
if isinstance(events, list):
|
||||
updates['WECOM_NOTIFY_EVENTS'] = ','.join([str(x).strip() for x in events if str(x).strip()])
|
||||
for key, value in updates.items():
|
||||
current_app.config[key] = value
|
||||
persist_env_settings(updates)
|
||||
return {'status': 'ok', 'settings': serialize_notify_settings()}
|
||||
|
||||
|
||||
def serialize_system_settings() -> dict:
|
||||
return {
|
||||
'enabled': bool(current_app.config.get('WECOM_ENABLED', False)),
|
||||
'corp_id': current_app.config.get('WECOM_CORP_ID') or '',
|
||||
'agent_id': str(current_app.config.get('WECOM_AGENT_ID') or ''),
|
||||
'secret': current_app.config.get('WECOM_SECRET') or '',
|
||||
'redirect_uri': current_app.config.get('WECOM_REDIRECT_URI') or '',
|
||||
'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)),
|
||||
'match_rules': current_app.config.get('WECOM_MATCH_RULES') or 'employee_id,mobile',
|
||||
'match_operator': str(current_app.config.get('WECOM_MATCH_OPERATOR') or 'AND').upper(),
|
||||
'first_login_bind_mode': str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') or 'match_rules').lower(),
|
||||
'first_login_input_fields': current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS') or 'employee_id,mobile,email',
|
||||
'employee_id_source': current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE') or 'userid',
|
||||
'mobile_normalize': bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)),
|
||||
'callback_token': current_app.config.get('WECOM_CALLBACK_TOKEN') or '',
|
||||
'encoding_aes_key': current_app.config.get('WECOM_ENCODING_AES_KEY') or '',
|
||||
'callback_url': current_app.config.get('WECOM_CALLBACK_URL') or '',
|
||||
'homepage_url': current_app.config.get('WECOM_HOMEPAGE_URL') or '',
|
||||
'trusted_domain': current_app.config.get('WECOM_TRUSTED_DOMAIN') or '',
|
||||
'public_base_url': current_app.config.get('WECOM_PUBLIC_BASE_URL') or '',
|
||||
}
|
||||
|
||||
|
||||
def update_system_settings(data: dict[str, Any]) -> dict:
|
||||
bool_keys = {
|
||||
'enabled': 'WECOM_ENABLED',
|
||||
'auto_create_user': 'WECOM_AUTO_CREATE_USER',
|
||||
'mobile_normalize': 'WECOM_MOBILE_NORMALIZE',
|
||||
}
|
||||
str_keys = {
|
||||
'corp_id': 'WECOM_CORP_ID',
|
||||
'agent_id': 'WECOM_AGENT_ID',
|
||||
'secret': 'WECOM_SECRET',
|
||||
'redirect_uri': 'WECOM_REDIRECT_URI',
|
||||
'match_rules': 'WECOM_MATCH_RULES',
|
||||
'match_operator': 'WECOM_MATCH_OPERATOR',
|
||||
'first_login_bind_mode': 'WECOM_FIRST_LOGIN_BIND_MODE',
|
||||
'first_login_input_fields': 'WECOM_FIRST_LOGIN_INPUT_FIELDS',
|
||||
'employee_id_source': 'WECOM_EMPLOYEE_ID_SOURCE',
|
||||
'callback_token': 'WECOM_CALLBACK_TOKEN',
|
||||
'encoding_aes_key': 'WECOM_ENCODING_AES_KEY',
|
||||
'callback_url': 'WECOM_CALLBACK_URL',
|
||||
'homepage_url': 'WECOM_HOMEPAGE_URL',
|
||||
'trusted_domain': 'WECOM_TRUSTED_DOMAIN',
|
||||
'public_base_url': 'WECOM_PUBLIC_BASE_URL',
|
||||
}
|
||||
updates = {}
|
||||
for req_key, cfg_key in bool_keys.items():
|
||||
if req_key in data:
|
||||
updates[cfg_key] = bool(data.get(req_key))
|
||||
for req_key, cfg_key in str_keys.items():
|
||||
if req_key in data:
|
||||
updates[cfg_key] = str(data.get(req_key) or '').strip()
|
||||
for key, value in updates.items():
|
||||
current_app.config[key] = value
|
||||
if current_app.config.get('WECOM_MATCH_OPERATOR') not in {'AND', 'OR'}:
|
||||
current_app.config['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
updates['WECOM_MATCH_OPERATOR'] = 'AND'
|
||||
if current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') not in {'match_rules', 'input_verify'}:
|
||||
current_app.config['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules'
|
||||
updates['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules'
|
||||
persist_env_settings(updates)
|
||||
return {'status': 'ok', 'settings': serialize_system_settings()}
|
||||
|
||||
|
||||
def integration_manifest(*, host_url: str, host: str) -> dict:
|
||||
settings = serialize_system_settings()
|
||||
public_base = (settings.get('public_base_url') or '').rstrip('/')
|
||||
if not public_base:
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
configured = current_app.config.get(key) or ''
|
||||
if configured:
|
||||
public_base = configured.rstrip('/')
|
||||
break
|
||||
if not public_base:
|
||||
public_base = host_url.rstrip('/')
|
||||
callback_url = settings.get('callback_url') or f'{public_base}/api/user/wecom/callback'
|
||||
homepage_url = settings.get('homepage_url') or f'{public_base}/workspace'
|
||||
trusted_domain = settings.get('trusted_domain') or host.split(':')[0]
|
||||
return {
|
||||
'public_base_url': public_base,
|
||||
'callback_url': callback_url,
|
||||
'callback_token': settings.get('callback_token') or '',
|
||||
'encoding_aes_key': settings.get('encoding_aes_key') or '',
|
||||
'oauth_redirect_uri': settings.get('redirect_uri') or homepage_url,
|
||||
'homepage_url': homepage_url,
|
||||
'trusted_domain': trusted_domain,
|
||||
'authorize_api': f'{public_base}/api/user/wecom/authorize-url',
|
||||
'login_api': f'{public_base}/api/user/wecom/login',
|
||||
}
|
||||
|
||||
|
||||
def notify_metrics() -> dict:
|
||||
now = datetime.utcnow()
|
||||
from_time = now - timedelta(days=30)
|
||||
total = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time).scalar() or 0
|
||||
sent = db.session.query(func.count(WecomNotifyAudit.id)).filter(
|
||||
WecomNotifyAudit.created_at >= from_time,
|
||||
WecomNotifyAudit.status == 'sent',
|
||||
).scalar() or 0
|
||||
opened_24h = db.session.query(func.count(WecomNotifyAudit.id)).filter(
|
||||
WecomNotifyAudit.created_at >= from_time,
|
||||
WecomNotifyAudit.opened_at.isnot(None),
|
||||
).scalar() or 0
|
||||
by_event_rows = (
|
||||
db.session.query(WecomNotifyAudit.event_type, WecomNotifyAudit.status, func.count(WecomNotifyAudit.id))
|
||||
.filter(WecomNotifyAudit.created_at >= from_time)
|
||||
.group_by(WecomNotifyAudit.event_type, WecomNotifyAudit.status)
|
||||
.all()
|
||||
)
|
||||
by_event = {}
|
||||
for event_type, status, cnt in by_event_rows:
|
||||
if event_type not in by_event:
|
||||
by_event[event_type] = {'sent': 0, 'failed': 0}
|
||||
by_event[event_type][status] = int(cnt)
|
||||
return {
|
||||
'window_days': 30,
|
||||
'total': int(total),
|
||||
'sent': int(sent),
|
||||
'failed': int(total - sent),
|
||||
'send_success_rate': round(sent / total * 100, 2) if total else 0,
|
||||
'opened_24h': int(opened_24h),
|
||||
'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0,
|
||||
'by_event': by_event,
|
||||
}
|
||||
|
||||
|
||||
def binding_stats() -> dict:
|
||||
total_active = db.session.query(func.count(User.id)).filter(User.status == 'active').scalar() or 0
|
||||
bound = (
|
||||
db.session.query(func.count(User.id))
|
||||
.filter(User.status == 'active', User.wecom_userid.isnot(None), User.wecom_userid != '')
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
total_active = int(total_active)
|
||||
bound = int(bound)
|
||||
return {
|
||||
'total_active': total_active,
|
||||
'bound': bound,
|
||||
'unbound': max(total_active - bound, 0),
|
||||
'bound_rate': round(bound / total_active * 100, 2) if total_active else 0,
|
||||
}
|
||||
|
||||
|
||||
def sync_userids(*, apply: bool) -> dict:
|
||||
try:
|
||||
summary = sync_wecom_userids_from_oa(apply=apply)
|
||||
current_app.logger.info(
|
||||
'[wecom_sync] oa apply=%s updated=%s would_update=%s conflicts=%s local_matched=%s',
|
||||
apply,
|
||||
summary.get('updated'),
|
||||
summary.get('would_update'),
|
||||
len(summary.get('conflicts') or []),
|
||||
summary.get('local_matched'),
|
||||
)
|
||||
return summary
|
||||
except RuntimeError as exc:
|
||||
message = str(exc)
|
||||
if 'conflicts detected' in message.lower():
|
||||
raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'})
|
||||
if '未找到可用的 SQL Server ODBC 驱动' in message or 'pyodbc' in message.lower():
|
||||
raise AppError(
|
||||
code='SYSTEM.SERVICE_UNAVAILABLE',
|
||||
message='OA SQL Server driver is not available on this server',
|
||||
http_status=503,
|
||||
details={'error_code': 'OA_SQLSERVER_DRIVER_MISSING', 'technical': message[:300]},
|
||||
)
|
||||
raise AppError(
|
||||
code='SYSTEM.HTTP_ERROR',
|
||||
message='OA SQL Server sync failed. Check OA_SQLSERVER_* env and network access.',
|
||||
http_status=502,
|
||||
details={'error_code': 'OA_SQLSERVER_SYNC_FAILED', 'technical': message[:300]},
|
||||
)
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[wecom_sync] oa unexpected failure: %s', exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500)
|
||||
@@ -1,105 +1,72 @@
|
||||
"""
|
||||
services/agent_category.py
|
||||
|
||||
用途:从 Agent.extra_config 解析 P1 分类字段(category / sub_category / sort_order),并提供排序与序列化。
|
||||
依赖:无外部服务;由 api/agents、api/user 在返回列表时调用。
|
||||
逻辑:分类信息暂存 extra_config,P2 可迁移至独立 agent_categories 表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def parse_agent_category_meta(extra_config: dict | None) -> dict[str, Any]:
|
||||
"""
|
||||
从 extra_config 解析 Agent 分类元数据。
|
||||
核心逻辑:category / sub_category 去首尾空白;sort_order 非法值回退为 0。
|
||||
|
||||
Args:
|
||||
extra_config: Agent.extra_config JSON 字典,可为 None。
|
||||
|
||||
Returns:
|
||||
含 category (str)、sub_category (str)、sort_order (int) 的字典。
|
||||
"""
|
||||
extra = extra_config if isinstance(extra_config, dict) else {}
|
||||
category = str(extra.get('category') or '').strip()
|
||||
sub_category = str(extra.get('sub_category') or '').strip()
|
||||
sort_raw = extra.get('sort_order')
|
||||
try:
|
||||
sort_order = int(sort_raw) if sort_raw is not None and sort_raw != '' else 0
|
||||
except (TypeError, ValueError):
|
||||
sort_order = 0
|
||||
return {
|
||||
'category': category,
|
||||
'sub_category': sub_category,
|
||||
'sort_order': sort_order,
|
||||
}
|
||||
|
||||
|
||||
def _row_extra_config(row: Any) -> dict | None:
|
||||
"""从 ORM 行或 dict 行读取 extra_config。"""
|
||||
if hasattr(row, 'extra_config'):
|
||||
return row.extra_config
|
||||
if isinstance(row, dict):
|
||||
return row.get('extra_config')
|
||||
return None
|
||||
|
||||
|
||||
def _row_id(row: Any) -> int:
|
||||
"""从 ORM 行或 dict 行读取主键 id。"""
|
||||
if hasattr(row, 'id'):
|
||||
return int(row.id)
|
||||
if isinstance(row, dict):
|
||||
return int(row.get('id') or 0)
|
||||
return 0
|
||||
|
||||
|
||||
def agent_category_sort_key(row: Any) -> tuple:
|
||||
"""
|
||||
生成分类排序键:sort_order → category → sub_category → id。
|
||||
核心逻辑:未配置 category 的 Agent 排在同 sort_order 下的末尾(用 \\uffff 占位)。
|
||||
"""
|
||||
meta = parse_agent_category_meta(_row_extra_config(row))
|
||||
category_key = meta['category'] or '\uffff'
|
||||
sub_key = meta['sub_category'] or '\uffff'
|
||||
return (meta['sort_order'], category_key, sub_key, _row_id(row))
|
||||
|
||||
|
||||
def sort_agent_rows(rows: list) -> list:
|
||||
"""
|
||||
按分类元数据对 Agent 行列表原地排序并返回。
|
||||
"""
|
||||
return sorted(rows, key=agent_category_sort_key)
|
||||
|
||||
|
||||
def serialize_agent_category_fields(row: Any) -> dict[str, Any]:
|
||||
"""
|
||||
序列化分类相关 API 字段。
|
||||
空字符串 category / sub_category 输出为 None,便于前端区分「未配置」。
|
||||
"""
|
||||
meta = parse_agent_category_meta(_row_extra_config(row))
|
||||
return {
|
||||
'category': meta['category'] or None,
|
||||
'sub_category': meta['sub_category'] or None,
|
||||
'sort_order': meta['sort_order'],
|
||||
}
|
||||
|
||||
|
||||
def serialize_agent_list_item(row: Any) -> dict[str, Any]:
|
||||
"""
|
||||
序列化用户可见 Agent 列表项(聊天侧栏、工作台首页共用)。
|
||||
核心逻辑:合并基础字段、dify_app_type 与分类元数据。
|
||||
"""
|
||||
extra = _row_extra_config(row) or {}
|
||||
name = row.name if hasattr(row, 'name') else row.get('name')
|
||||
description = row.description if hasattr(row, 'description') else row.get('description')
|
||||
icon_url = row.icon_url if hasattr(row, 'icon_url') else row.get('icon_url')
|
||||
return {
|
||||
'id': _row_id(row),
|
||||
'name': name,
|
||||
'description': description,
|
||||
'icon_url': icon_url,
|
||||
'dify_app_type': extra.get('dify_app_type') or 'chatflow',
|
||||
**serialize_agent_category_fields(row),
|
||||
}
|
||||
"""
|
||||
services/agent_category.py
|
||||
|
||||
用途:Agent 分类字段解析、排序与序列化(只读结构化列)。
|
||||
依赖:agent_registry.serialization。
|
||||
逻辑:由 api/agents、api/user 在返回列表时调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_user_list
|
||||
|
||||
|
||||
def parse_agent_category_meta(row: Any) -> dict[str, Any]:
|
||||
"""
|
||||
解析 Agent 分类元数据;只读 category / sub_category / sort_order 列。
|
||||
"""
|
||||
if isinstance(row, dict):
|
||||
category = str(row.get('category') or '').strip()
|
||||
sub_category = str(row.get('sub_category') or '').strip()
|
||||
try:
|
||||
sort_order = int(row.get('sort_order') or 0)
|
||||
except (TypeError, ValueError):
|
||||
sort_order = 0
|
||||
else:
|
||||
category = str(getattr(row, 'category', None) or '').strip()
|
||||
sub_category = str(getattr(row, 'sub_category', None) or '').strip()
|
||||
try:
|
||||
sort_order = int(getattr(row, 'sort_order', 0) or 0)
|
||||
except (TypeError, ValueError):
|
||||
sort_order = 0
|
||||
|
||||
return {
|
||||
'category': category,
|
||||
'sub_category': sub_category,
|
||||
'sort_order': max(0, sort_order),
|
||||
}
|
||||
|
||||
|
||||
def _row_id(row: Any) -> int:
|
||||
if hasattr(row, 'id'):
|
||||
return int(row.id)
|
||||
if isinstance(row, dict):
|
||||
return int(row.get('id') or 0)
|
||||
return 0
|
||||
|
||||
|
||||
def agent_category_sort_key(row: Any) -> tuple:
|
||||
meta = parse_agent_category_meta(row)
|
||||
category_key = meta['category'] or '\uffff'
|
||||
sub_key = meta['sub_category'] or '\uffff'
|
||||
return (meta['sort_order'], category_key, sub_key, _row_id(row))
|
||||
|
||||
|
||||
def sort_agent_rows(rows: list) -> list:
|
||||
return sorted(rows, key=agent_category_sort_key)
|
||||
|
||||
|
||||
def serialize_agent_category_fields(row: Any) -> dict[str, Any]:
|
||||
meta = parse_agent_category_meta(row)
|
||||
return {
|
||||
'category': meta['category'] or None,
|
||||
'sub_category': meta['sub_category'] or None,
|
||||
'sort_order': meta['sort_order'],
|
||||
}
|
||||
|
||||
|
||||
def serialize_agent_list_item(row: Any) -> dict[str, Any]:
|
||||
"""序列化用户可见 Agent 列表项(含 Registry 结构化字段)。"""
|
||||
return serialize_agent_for_user_list(row)
|
||||
Loaded 100 of 671 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user