Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5b65d9ed4 | ||
|
|
9600514b20 | ||
|
|
ac67b07107 | ||
|
|
4fa5ab4929 | ||
|
|
55188acbc2 | ||
|
|
a3a01592f4 | ||
|
|
1de4b78181 | ||
|
|
3837a8669e | ||
|
|
14caee4df6 | ||
|
|
c974566c34 | ||
|
|
ee90b66ff7 | ||
|
|
c18c0394d0 | ||
|
|
90700f1d59 | ||
|
|
f29dea2829 | ||
|
|
fcb2f88f1a | ||
|
|
1f32392eac | ||
|
|
4ce4d75524 | ||
|
|
d039fc255c | ||
|
|
6057069c1c | ||
|
|
900a13722c | ||
|
|
c7f25ec8a1 | ||
|
|
0890c79070 | ||
|
|
2d59be2f92 | ||
|
|
dd6e7b8cb0 | ||
|
|
f036182650 | ||
|
|
955faed27d | ||
|
|
7eaff3c8bf | ||
|
|
b35e19fe37 | ||
|
|
35901425c7 | ||
|
|
8c98438370 | ||
|
|
c58ed37cc1 | ||
|
|
7a21775dcb | ||
|
|
a3123cd602 | ||
|
|
01173e0a0e | ||
|
|
c3b63df2f5 | ||
|
|
faedb625c7 | ||
|
|
81e5cbea1f | ||
|
|
61ebb46c0f | ||
|
|
21a5316319 | ||
|
|
d06915dfab | ||
|
|
0e3085725a | ||
|
|
541d3bc7b1 | ||
|
|
89d4c6e45d | ||
|
|
eab7929270 | ||
|
|
e23da3f170 | ||
|
|
b0ff3efba9 | ||
|
|
2ce5256483 | ||
|
|
8deae3146b | ||
|
|
90da630eed | ||
|
|
0bb1946b7e | ||
|
|
6fed283e4c | ||
|
|
0baa3921bc | ||
|
|
d96008df02 | ||
|
|
f8de4630a5 | ||
|
|
bee3139824 | ||
|
|
cc53d29e76 | ||
|
|
b62082758b | ||
|
|
8f69131872 | ||
|
|
445763e144 | ||
|
|
6f8b7d3982 | ||
|
|
dfdbb20255 | ||
|
|
8206630823 | ||
|
|
93304a1803 | ||
|
|
2607f4a9f6 | ||
|
|
34dc8d2664 | ||
|
|
55ce8dd949 | ||
|
|
1f96d6fccc | ||
|
|
61693d014d | ||
|
|
a4232aec3b | ||
|
|
fed1b103e6 | ||
|
|
c6afe36a24 | ||
|
|
07a1494a1e | ||
|
|
c61a80c362 | ||
|
|
854bc8e4db | ||
|
|
b3c6ebad2e | ||
|
|
5e06bd173c | ||
|
|
f877f61efd | ||
|
|
c61f74866c | ||
|
|
86d1bd4588 | ||
|
|
1b56810cc7 | ||
|
|
3826c9a503 | ||
|
|
14c5903aef | ||
|
|
a5cc48b6aa | ||
|
|
6253476930 | ||
|
|
a1e0fa9404 | ||
|
|
654582f3f4 | ||
|
|
b0ba0b9df5 | ||
|
|
2d7bdecc43 | ||
|
|
8c9d96be74 | ||
|
|
2a036764e3 | ||
|
|
7f126cfd52 | ||
|
|
93e99793d8 | ||
|
|
23badf7456 | ||
|
|
0c5cfcaa4a | ||
|
|
be6155d4aa | ||
|
|
79a2a63b5d | ||
|
|
55ccb16bb2 | ||
|
|
7402621ded | ||
|
|
693443bef1 | ||
|
|
a148f76217 | ||
|
|
744d623f2f | ||
|
|
7f66d6f20c | ||
|
|
f91d44ca24 | ||
|
|
e559473fff | ||
|
|
55e9085a38 | ||
|
|
4daf8dfcaa | ||
|
|
2b40d7f507 | ||
|
|
eda185beb0 | ||
|
|
be7916d2a3 | ||
|
|
fbf5537dcd | ||
|
|
d33f6e3980 | ||
|
|
39507ba1cb | ||
|
|
0eb577df1a | ||
|
|
fcb979ec33 | ||
|
|
1d72018eb7 | ||
|
|
def791ff59 | ||
|
|
05af299e33 | ||
|
|
4cb65337d7 | ||
|
|
a9753fd10f | ||
|
|
1e07b0fb1f | ||
|
|
858fb91f41 | ||
|
|
86999f0b83 | ||
|
|
2721b9d00b | ||
|
|
24f99070a3 | ||
|
|
d85736de71 | ||
|
|
71e09d0857 | ||
|
|
d3fa1cc243 | ||
|
|
d71d54a278 | ||
|
|
0c5939ed7a | ||
|
|
eae9886ece | ||
|
|
0c6f1c0ffc | ||
|
|
42908b42f1 | ||
|
|
c866b1f85e | ||
|
|
97e482fb74 | ||
|
|
cf70d5c480 | ||
|
|
fabb96013c | ||
|
|
5eb36e53ae | ||
|
|
f707e78bed | ||
|
|
63ea9d7ed7 | ||
|
|
3642ed8529 | ||
|
|
c7abb89149 | ||
|
|
71dcfd8ca4 | ||
|
|
3fe3ba63b9 | ||
|
|
041c2d033f | ||
|
|
bacff38ef7 | ||
|
|
b25c4c6797 | ||
|
|
736dab2c4e | ||
|
|
f3bd1334d0 | ||
|
|
03570dbf5a | ||
|
|
dbef371b75 | ||
|
|
c14046f9f3 | ||
|
|
4ff07f8f9b | ||
|
|
ff2d02051f | ||
|
|
4cb0c5839c | ||
|
|
6bc93490d4 | ||
|
|
1689347494 | ||
|
|
02d0c1dcd6 | ||
|
|
452f6ebc6d | ||
|
|
7d046862f7 | ||
|
|
2b773eaac6 | ||
|
|
fa7827f69e | ||
|
|
4a90954a38 | ||
|
|
23e058e662 | ||
|
|
642b71a007 | ||
|
|
01b095e900 | ||
|
|
c22091a0e1 | ||
|
|
211763908a | ||
|
|
c0cb55dce6 | ||
|
|
8e263a1d76 | ||
|
|
05913f742f | ||
|
|
dc8ad4de52 | ||
|
|
b1613824ce | ||
|
|
718c5a18d2 | ||
|
|
a6f35b375c | ||
|
|
0cc9f487e6 | ||
|
|
240b5105bf | ||
|
|
54810f514a | ||
|
|
8da487aac6 | ||
|
|
39a089a424 | ||
|
|
be0b40bfae | ||
|
|
88051db91e | ||
|
|
d012099013 | ||
|
|
fd70a2f519 | ||
|
|
73c93a497b | ||
|
|
e48f67335c | ||
|
|
007a01313d | ||
|
|
e1b103090c | ||
|
|
abd200c735 | ||
|
|
83f958f272 | ||
|
|
ae6ced00b5 | ||
|
|
e3ca34077f | ||
|
|
4f92464b03 | ||
|
|
175812c1a1 | ||
|
|
ddc461f548 | ||
|
|
3cc556b9fd | ||
|
|
4b5eaf4644 | ||
|
|
40b25ec988 | ||
|
|
79401eb445 | ||
|
|
57c3e5f858 | ||
|
|
6ada6810c5 | ||
|
|
40c80eaacb | ||
|
|
e70e17efd4 | ||
|
|
e0d91e53e7 | ||
|
|
72642b981e | ||
|
|
67c16b5121 | ||
|
|
46d7fff01e | ||
|
|
f42f0a39a5 | ||
|
|
4d05b5674e | ||
|
|
d473ca9a22 | ||
|
|
316b8f326e | ||
|
|
fdaeda0812 | ||
|
|
3612e89f37 | ||
|
|
09b5e62861 | ||
|
|
092192b824 | ||
|
|
3e467b4a94 | ||
|
|
fb8189ef13 | ||
|
|
097821e12b | ||
|
|
ea56e8bf65 | ||
|
|
1971f01666 | ||
|
|
5e21ce46d1 | ||
|
|
51b466d4ab | ||
|
|
fed57cc3cf | ||
|
|
c8571b35a2 | ||
|
|
7511226ba1 | ||
|
|
97aa204850 | ||
|
|
df539f4ac1 | ||
|
|
03366965e7 | ||
|
|
36f2468419 | ||
|
|
ac04409e79 | ||
|
|
b745a9c803 | ||
|
|
315637b9c4 | ||
|
|
20dce979a7 | ||
|
|
f978a8701b | ||
|
|
09bf8d33e6 | ||
|
|
655d7e3d7d | ||
|
|
16dad48143 | ||
|
|
bd453e408c | ||
|
|
6a98cd89ec | ||
|
|
3d4b2647ae | ||
|
|
08776feef2 | ||
|
|
83e623fae0 | ||
|
|
fd049f98db | ||
|
|
18ba84de2e | ||
|
|
f2c6269832 | ||
|
|
c0dde055cd | ||
|
|
2ba846460a | ||
|
|
059346f1ac | ||
|
|
fed26821b7 | ||
|
|
b1905c56cc | ||
|
|
cd3d31bf11 | ||
|
|
8c877e871a | ||
|
|
eb17ca8bc2 | ||
|
|
844eb30747 | ||
|
|
2d41fc3c6e | ||
|
|
01c8b0320f | ||
|
|
d7e69e02fb | ||
|
|
92018f3366 | ||
|
|
d342bba458 | ||
|
|
05abffc5f0 | ||
|
|
cbc9f070ec | ||
|
|
729ec2908d | ||
|
|
3d005ba833 | ||
|
|
3b31867319 | ||
|
|
be6aeb2f56 | ||
|
|
bf37948db6 | ||
|
|
9356796244 | ||
|
|
a3ec47412d | ||
|
|
f634b67f82 | ||
|
|
566077ca6b | ||
|
|
d0955d25fa | ||
|
|
c1df261e2f | ||
|
|
1673106950 | ||
|
|
7151388c9c | ||
|
|
2b33acee85 | ||
|
|
db5fbe1697 | ||
|
|
367c20eb09 | ||
|
|
aeb6b66513 | ||
|
|
9de63c916c | ||
|
|
d895754d70 | ||
|
|
65b7ea8fa1 | ||
|
|
ab60a7da52 | ||
|
|
964e4925c0 | ||
|
|
bf5f735404 | ||
|
|
26f618341c | ||
|
|
e2510c0565 | ||
|
|
19d2f9d595 | ||
|
|
6cf905c855 | ||
|
|
46394abf91 | ||
|
|
48683f7b93 | ||
|
|
49f4ea1281 | ||
|
|
d168d67353 | ||
|
|
3b3caf5b1b | ||
|
|
3a7e97ff67 | ||
|
|
4e56387f31 | ||
|
|
efbb3f77d8 | ||
|
|
dcbbf0e05d | ||
|
|
5b9dffd4fb | ||
|
|
f108c350c3 | ||
|
|
5c40cfb18e | ||
|
|
46d90a0e9a | ||
|
|
037fb499e5 | ||
|
|
a7d2d75bda | ||
|
|
a676353b6c | ||
|
|
a819a7a187 | ||
|
|
b2a336a107 | ||
|
|
8d73343bd8 | ||
|
|
adab06ead1 | ||
|
|
348031d2a5 | ||
|
|
489c79758d | ||
|
|
2e9a70933d | ||
|
|
016f992346 | ||
|
|
da42832087 | ||
|
|
ebf115e1c3 | ||
|
|
d010156397 | ||
|
|
8c8a65d838 | ||
|
|
f851e5d3ff | ||
|
|
3144489f34 | ||
|
|
c03bfe1b34 | ||
|
|
9b7f26f0df | ||
|
|
6003a98754 | ||
|
|
f3a2007299 | ||
|
|
fcb70b85f4 | ||
|
|
47c926bd4a | ||
|
|
8a4f6990e7 | ||
|
|
178f24af97 | ||
|
|
10d0f5bad8 | ||
|
|
c32d5e1c2f | ||
|
|
d00d549bd9 | ||
|
|
bde9824ece | ||
|
|
958ce5abc5 | ||
|
|
7ecc88e234 | ||
|
|
1ebd307853 | ||
|
|
cb88f02b40 | ||
|
|
f6cda775be | ||
|
|
3f25de0e4f | ||
|
|
13ecfc3e42 | ||
|
|
dea3b39048 | ||
|
|
5da6c464b9 | ||
|
|
08a19ebe96 | ||
|
|
86f07cdd5b | ||
|
|
a9276cc89c | ||
|
|
2b639513cb | ||
|
|
84010c25bf | ||
|
|
e76cb197d0 | ||
|
|
67f637125b | ||
|
|
ca4142ef0e | ||
|
|
c05689a140 | ||
|
|
c21a831796 | ||
|
|
ffc00af9fa | ||
|
|
b30c867087 | ||
|
|
f61dbf7611 | ||
|
|
7f542f54a5 | ||
|
|
c91d4ff3c7 | ||
|
|
c0937bda34 | ||
|
|
3062ade15f | ||
|
|
eaf518a01d | ||
|
|
933cd321be | ||
|
|
7eed474125 | ||
|
|
b5c8a72728 | ||
|
|
10ececfd91 | ||
|
|
4426567da4 | ||
|
|
283ec9e7b3 | ||
|
|
fec2fc096e | ||
|
|
2736224ed7 | ||
|
|
8647537f2f | ||
|
|
fbb9f310af | ||
|
|
6543d3ad7d | ||
|
|
b39eb04a33 | ||
|
|
66b108f9d8 | ||
|
|
bf01b95c9b | ||
|
|
6e5ef8f6c0 | ||
|
|
cf70f2d579 | ||
|
|
47ab49cf04 | ||
|
|
61fa96d686 | ||
|
|
a5f0ec645d | ||
|
|
5cd767161d | ||
|
|
2c85508336 | ||
|
|
23f9533124 | ||
|
|
aa01e6a5f0 | ||
|
|
dc805b250f | ||
|
|
a4a083658e | ||
|
|
380492b7e0 | ||
|
|
0875623605 | ||
|
|
fb71def840 | ||
|
|
550aeb0d6c | ||
|
|
0bb063bf67 | ||
|
|
6cd2ac9bd1 | ||
|
|
f6ee3cba50 | ||
|
|
a77b61fb9f | ||
|
|
3f5b6292ba | ||
|
|
d710a88d04 | ||
|
|
2a6d2ea681 | ||
|
|
2675f447bb | ||
|
|
c5f868a8ef | ||
|
|
6b2ab65436 | ||
|
|
2bd27ed70d | ||
|
|
ef0ae7fe08 | ||
|
|
d2bd33d0db | ||
|
|
1d9f854ce4 | ||
|
|
a9fc852abb | ||
|
|
7b0ed4e88b | ||
|
|
e56c7db4d7 | ||
|
|
8336bc9480 | ||
|
|
7bc6a8072b | ||
|
|
9313ff769d | ||
|
|
b0fda9f081 | ||
|
|
5df6957e15 | ||
|
|
658ab92706 | ||
|
|
9c0934b397 | ||
|
|
2ee4e1dca7 | ||
|
|
46ac70f4c5 | ||
|
|
1022abe55d | ||
|
|
8857c94cca | ||
|
|
3b35a66307 | ||
|
|
52ab6767bf | ||
|
|
deb94b757c | ||
|
|
8ecc6def48 | ||
|
|
6e8f27b809 | ||
|
|
a3f6ada815 | ||
|
|
fdbfb28ee8 | ||
|
|
3d22e050f3 | ||
|
|
45ed2ed72a | ||
|
|
482d2d73a3 | ||
|
|
62ec5a3513 | ||
|
|
e72889acdb | ||
|
|
63dfe1687a | ||
|
|
57ee1e522c | ||
|
|
c380248502 | ||
|
|
70f95e9f5c | ||
|
|
f5d3e275ac |
No files matched your search
@@ -0,0 +1,18 @@
|
||||
.git
|
||||
.gitignore
|
||||
.venv
|
||||
venv
|
||||
**/__pycache__/
|
||||
**/*.pyc
|
||||
**/*.pyo
|
||||
**/*.log
|
||||
frontend/node_modules
|
||||
frontend/dist
|
||||
backend/venv
|
||||
backend/local_test.db
|
||||
deploy
|
||||
docs/*
|
||||
!docs/
|
||||
!docs/(表+字段).md
|
||||
tmp_restore
|
||||
tests
|
||||
@@ -0,0 +1,111 @@
|
||||
# =============================================================================
|
||||
# Development — docker compose / deploy_compose.sh dev
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# =============================================================================
|
||||
ENV_NAME=dev
|
||||
FLASK_ENV=development
|
||||
DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops
|
||||
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
AUTH_LOGIN_MODE=password
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
|
||||
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
|
||||
# 共用 IdP(可与生产 Casdoor 同机)
|
||||
CASDOOR_BASE_URL=http://192.168.100.192:8870
|
||||
# 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用)
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 本地开发常用;若用其它入口访问前端,请在 Casdoor 该应用的 Redirect URLs 中一并登记
|
||||
CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可)
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=sync
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=10
|
||||
|
||||
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
|
||||
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
|
||||
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致
|
||||
MINIO_ENDPOINT=192.168.100.192:9000
|
||||
MINIO_ACCESS_KEY=minio_testing_admin
|
||||
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||
MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2)
|
||||
# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# OpenAPI / Dify Tool 调用基地址(默认等于 PUBLIC_BASE_URL + /api/shipping-notice)
|
||||
SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.108:5052/
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
|
||||
# 解析与文本上限
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=6
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 shipping_notice.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(相对 backend/ 根目录)
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
|
||||
# Dify Chatflow(seed_shipping_notice_agents.py)
|
||||
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_MOCK=true
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
@@ -0,0 +1,56 @@
|
||||
# =============================================================================
|
||||
# Production — docker compose env_file + deploy_compose.sh prod
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# =============================================================================
|
||||
ENV_NAME=prod
|
||||
FLASK_ENV=production
|
||||
DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db
|
||||
ORACLE_CLIENT_MOUNT_DIR=/data/ai-platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
AUTH_LOGIN_MODE=password
|
||||
|
||||
AUTH_JWT_ISSUER=http://ai.well-trust.com:8870
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=http://ai.well-trust.com:8870
|
||||
# 与 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_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.230:8891
|
||||
DIFY_API_BASE=http://192.168.100.230:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
MINIO_ENDPOINT=host.docker.internal:9000
|
||||
MINIO_ACCESS_KEY=admin
|
||||
MINIO_SECRET_KEY=difyai123456
|
||||
MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
# Shared environment variables for all environments (dev/test/prod)
|
||||
# Keep only values that are truly identical across all environments.
|
||||
|
||||
# Runtime selector fallback (actual deployment still sets ENV_NAME explicitly)
|
||||
ENV_NAME=dev
|
||||
# Common runtime defaults
|
||||
FLASK_APP=run.py
|
||||
|
||||
# 知识库管理(后续需要修改此地址)
|
||||
# 查「Dify 文档对应原始源文件下载地址」时,要连的那台 Integration API 的根 URL
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
# 连接文档清洗系统的API KEY
|
||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
SECRET_KEY=hxops-dify
|
||||
|
||||
# Knowledge base runtime
|
||||
# KB_STORAGE_ROOT=backend/data/kb
|
||||
KB_TASK_EXECUTION_MODE=worker
|
||||
KB_WORKER_POLL_SECONDS=2
|
||||
KB_WORKER_CONCURRENCY=3
|
||||
# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径)
|
||||
EDKB_SOFFICE=/usr/bin/soffice
|
||||
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
|
||||
EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
|
||||
EDKB_WORD_TIMEOUT_SEC=300
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||
EDKB_FILE_TIMEOUT_SEC=180
|
||||
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
|
||||
EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
|
||||
|
||||
# chat回答的评分与评论
|
||||
FEEDBACK_ENABLED=true
|
||||
|
||||
# Common auth defaults
|
||||
AUTH_LEGACY_HEADER_ENABLED=true
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# 是否保留本地密码登录/本地TWT兼容
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
|
||||
AUTH_ALLOW_LOCAL_JWT=true
|
||||
AUTH_LOCAL_JWT_ISSUER=hxops-backend
|
||||
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
|
||||
|
||||
# WeCom
|
||||
WECOM_ENABLED=false
|
||||
WECOM_CORP_ID=
|
||||
WECOM_AGENT_ID=
|
||||
WECOM_SECRET=
|
||||
WECOM_REDIRECT_URI=
|
||||
WECOM_AUTO_CREATE_USER=true
|
||||
WECOM_MATCH_RULES=employee_id,mobile
|
||||
WECOM_MATCH_OPERATOR=AND
|
||||
WECOM_FIRST_LOGIN_BIND_MODE=match_rules
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS=employee_id,mobile,email
|
||||
WECOM_EMPLOYEE_ID_SOURCE=userid
|
||||
WECOM_MOBILE_NORMALIZE=true
|
||||
WECOM_CALLBACK_TOKEN=
|
||||
WECOM_ENCODING_AES_KEY=
|
||||
WECOM_CALLBACK_URL=
|
||||
WECOM_HOMEPAGE_URL=
|
||||
WECOM_TRUSTED_DOMAIN=
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host)
|
||||
WECOM_PUBLIC_BASE_URL=
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_BASE_URL=
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed
|
||||
|
||||
|
||||
# Common integration defaults
|
||||
INTEGRATION_API_MODE=local
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
|
||||
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
|
||||
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
|
||||
# MINIO_AGENT_GUIDES_BUCKET — Agent 指南文件上传(Flask minio_service)
|
||||
MINIO_KB_IMAGE_BUCKET=image-hosting-service
|
||||
MINIO_AGENT_GUIDES_BUCKET=agent-guides
|
||||
|
||||
# 硅基流动相关
|
||||
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
|
||||
GJL_API_BASE=https://api.siliconflow.cn/v1
|
||||
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
||||
# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR
|
||||
ASR_MODEL=FunAudioLLM/SenseVoiceSmall
|
||||
|
||||
# HR SQL Server Configuration
|
||||
HR_SQLSERVER_HOST=192.168.100.191
|
||||
HR_SQLSERVER_PORT=1433
|
||||
HR_SQLSERVER_DATABASE=NH_N8_HEXIN
|
||||
HR_SQLSERVER_USERNAME=AI_Knowledge_Base_Hr
|
||||
HR_SQLSERVER_PASSWORD=hoo-thai@123_AI_HR
|
||||
HR_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
|
||||
HR_SQLSERVER_ENCRYPT=no
|
||||
HR_SQLSERVER_TRUST_CERT=yes
|
||||
HR_SQLSERVER_TIMEOUT=10
|
||||
|
||||
# PLM Oracle
|
||||
PLM_ORACLE_HOST=192.168.0.11
|
||||
PLM_ORACLE_PORT=1521
|
||||
PLM_ORACLE_SID=orcl
|
||||
PLM_ORACLE_USERNAME=PLM
|
||||
PLM_ORACLE_PASSWORD=PLM
|
||||
|
||||
# SRM SQL Server Configuration
|
||||
SRM_SQLSERVER_HOST=192.168.55.106
|
||||
SRM_SQLSERVER_PORT=1433
|
||||
SRM_SQLSERVER_DATABASE=HX-SRM
|
||||
SRM_SQLSERVER_USERNAME=sa
|
||||
SRM_SQLSERVER_PASSWORD=sa@moreyou456
|
||||
SRM_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
|
||||
SRM_SQLSERVER_ENCRYPT=no
|
||||
SRM_SQLSERVER_TRUST_CERT=yes
|
||||
SRM_SQLSERVER_TIMEOUT=10
|
||||
|
||||
# ERP
|
||||
ERP_DB_DSN=192.168.8.24:1521/topprod
|
||||
TEXT2SQL_SCHEMA_PATH=
|
||||
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=120
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=
|
||||
@@ -0,0 +1,60 @@
|
||||
# =============================================================================
|
||||
# Test — docker compose / deploy_compose.sh test
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# =============================================================================
|
||||
ENV_NAME=test
|
||||
FLASK_ENV=test
|
||||
DATABASE_URL=postgresql://postgres:8je2olWwHj28fCfVTgRWmankoTQORjqyBn6iIK3dG2q10vAq@192.168.100.192:5432/hxops_testing
|
||||
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_23_26
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_23_26:/app/oracle_client
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
|
||||
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=http://192.168.100.192:8870
|
||||
# 与 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_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.192:8891
|
||||
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=6
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD(及 DIFY_S3_ACCESS_KEY)保持一致
|
||||
MINIO_ENDPOINT=host.docker.internal:9000
|
||||
MINIO_ACCESS_KEY=minio_testing_admin
|
||||
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||
MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
@@ -0,0 +1,130 @@
|
||||
# shellcheck shell=bash
|
||||
# 供 pre-commit / pre-push 引用;勿直接执行。
|
||||
|
||||
hook_should_skip() {
|
||||
[[ "${SKIP_GIT_HOOKS:-}" == "1" ]] || [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]]
|
||||
}
|
||||
|
||||
frontend_paths_in() {
|
||||
local file_list="${1:-}"
|
||||
echo "${file_list}" | grep -qE '^frontend/'
|
||||
}
|
||||
|
||||
ensure_frontend_deps() {
|
||||
local frontend_dir="${1}/frontend"
|
||||
if [[ ! -d "${frontend_dir}/node_modules" ]]; then
|
||||
echo "[git-hook] frontend/node_modules 不存在,请先执行:"
|
||||
echo " cd frontend && npm install"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
run_frontend_typecheck() {
|
||||
local root_dir="${1}"
|
||||
echo "[pre-commit] 检测到 frontend/ 变更,运行 vue-tsc 类型检查..."
|
||||
if ! ensure_frontend_deps "${root_dir}"; then
|
||||
return 1
|
||||
fi
|
||||
(
|
||||
cd "${root_dir}/frontend"
|
||||
npx vue-tsc -b --pretty false
|
||||
)
|
||||
}
|
||||
|
||||
run_frontend_build() {
|
||||
local root_dir="${1}"
|
||||
echo "[pre-push] 检测到将要推送的提交包含 frontend/ 变更,运行 npm run build..."
|
||||
if ! ensure_frontend_deps "${root_dir}"; then
|
||||
return 1
|
||||
fi
|
||||
(
|
||||
cd "${root_dir}/frontend"
|
||||
npm run build
|
||||
)
|
||||
}
|
||||
|
||||
ensure_commitlint_deps() {
|
||||
local root_dir="${1}"
|
||||
if [[ ! -d "${root_dir}/node_modules/@commitlint/cli" ]]; then
|
||||
echo "[commit-msg] 根目录 node_modules 不存在,请先执行:"
|
||||
echo " cd ${root_dir}"
|
||||
echo " npm install"
|
||||
echo " 或重新运行: ./scripts/install_git_hooks.sh"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
run_commitlint() {
|
||||
local root_dir="${1}"
|
||||
local msg_file="${2}"
|
||||
if ! ensure_commitlint_deps "${root_dir}"; then
|
||||
return 1
|
||||
fi
|
||||
(
|
||||
cd "${root_dir}"
|
||||
npx --no-install commitlint --edit "${msg_file}"
|
||||
)
|
||||
}
|
||||
|
||||
resolve_python_cmd() {
|
||||
# 优先使用 backend 虚拟环境内的 Python,与日常 flask 开发环境一致
|
||||
local root_dir="${1}"
|
||||
local candidates=(
|
||||
"${root_dir}/backend/.venv/bin/python"
|
||||
"${root_dir}/backend/.venv/Scripts/python.exe"
|
||||
"${root_dir}/backend/venv/bin/python"
|
||||
"${root_dir}/backend/venv/Scripts/python.exe"
|
||||
)
|
||||
local candidate
|
||||
for candidate in "${candidates[@]}"; do
|
||||
if [[ -x "${candidate}" ]]; then
|
||||
echo "${candidate}"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
if command -v python3 >/dev/null 2>&1; then
|
||||
echo "python3"
|
||||
return 0
|
||||
fi
|
||||
if command -v python >/dev/null 2>&1; then
|
||||
echo "python"
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
run_migration_heads_check() {
|
||||
# 调用 scripts/check_migration_heads.py:
|
||||
# - 校验 Alembic 仅 1 个 head
|
||||
# - 可选传入本次新增的 migration 路径,校验 down_revision
|
||||
# 注意:不可被 SKIP_FRONTEND_HOOKS 跳过(见 pre-commit 调用处)
|
||||
local root_dir="${1}"
|
||||
local staged_new_migrations="${2:-}"
|
||||
local python_cmd
|
||||
local -a check_args=()
|
||||
|
||||
if ! python_cmd="$(resolve_python_cmd "${root_dir}")"; then
|
||||
echo "[pre-commit] 未找到 Python,无法校验 migration heads。"
|
||||
echo "[pre-commit] 请先配置 backend 虚拟环境,或确保 python/python3 在 PATH 中。"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "[pre-commit] 校验 Alembic migration 链(必须仅 1 个 head)..."
|
||||
if [[ -n "${staged_new_migrations}" ]]; then
|
||||
while IFS= read -r migration_file; do
|
||||
[[ -n "${migration_file}" ]] || continue
|
||||
check_args+=("${root_dir}/${migration_file}")
|
||||
done <<< "${staged_new_migrations}"
|
||||
fi
|
||||
|
||||
if ! "${python_cmd}" "${root_dir}/scripts/check_migration_heads.py" "${check_args[@]}"; then
|
||||
echo "[pre-commit] migration heads 校验失败,已阻止提交。"
|
||||
echo "[pre-commit] migration 检查不可通过 SKIP_FRONTEND_HOOKS 跳过;仅可使用 git commit --no-verify"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "[pre-commit] migration heads 校验通过。"
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
cd "${ROOT_DIR}"
|
||||
# shellcheck source=_common.sh
|
||||
source "${ROOT_DIR}/.githooks/_common.sh"
|
||||
|
||||
COMMIT_MSG_FILE="${1:-}"
|
||||
|
||||
if [[ -z "${COMMIT_MSG_FILE}" ]]; then
|
||||
echo "[commit-msg] missing commit message file path."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ -f "${ROOT_DIR}/.git/MERGE_HEAD" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! run_commitlint "${ROOT_DIR}" "${COMMIT_MSG_FILE}"; then
|
||||
echo "[commit-msg] 提交信息不符合规范,详见 docs/convention/COMMIT_CONVENTION.md"
|
||||
echo "[commit-msg] 示例: feat(auth): add SMS login support"
|
||||
echo "[commit-msg] 跳过校验: git commit --no-verify"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -3,6 +3,8 @@ set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
cd "${ROOT_DIR}"
|
||||
# shellcheck source=_common.sh
|
||||
source "${ROOT_DIR}/.githooks/_common.sh"
|
||||
|
||||
STAGED_FILES="$(git diff --cached --name-only --diff-filter=ACMR || true)"
|
||||
if [[ -z "${STAGED_FILES}" ]]; then
|
||||
@@ -30,4 +32,27 @@ if [[ "${MODELS_CHANGED}" -eq 1 && "${MIGRATION_CHANGED}" -eq 0 ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# migration 链校验:防止多人并行 migration 合并后出现多 head,部署时 db upgrade 失败
|
||||
# 实现见 scripts/check_migration_heads.py(离线读文件,无需数据库)
|
||||
if [[ "${MIGRATION_CHANGED}" -eq 1 ]]; then
|
||||
STAGED_NEW_MIGRATIONS="$(git diff --cached --name-only --diff-filter=A -- 'backend/migrations/versions/*.py' || true)"
|
||||
if ! run_migration_heads_check "${ROOT_DIR}" "${STAGED_NEW_MIGRATIONS}"; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if hook_should_skip; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if frontend_paths_in "${STAGED_FILES}"; then
|
||||
if ! run_frontend_typecheck "${ROOT_DIR}"; then
|
||||
echo "[pre-commit] vue-tsc 失败,已阻止提交。"
|
||||
echo "[pre-commit] 跳过前端检查: SKIP_FRONTEND_HOOKS=1 git commit"
|
||||
echo "[pre-commit] 或跳过全部 hook: git commit --no-verify"
|
||||
exit 1
|
||||
fi
|
||||
echo "[pre-commit] frontend 类型检查通过。"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
# shellcheck source=_common.sh
|
||||
source "${ROOT_DIR}/.githooks/_common.sh"
|
||||
|
||||
if hook_should_skip; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
zero="0000000000000000000000000000000000000000"
|
||||
need_frontend_build=0
|
||||
|
||||
while read -r local_ref local_sha remote_ref remote_sha; do
|
||||
[[ "${local_sha}" == "${zero}" ]] && continue
|
||||
|
||||
changed_files=""
|
||||
if [[ "${remote_sha}" == "${zero}" ]]; then
|
||||
upstream_ref="$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)"
|
||||
if [[ -n "${upstream_ref}" ]]; then
|
||||
remote_branch="${upstream_ref#*/}"
|
||||
remote_name="${upstream_ref%%/*}"
|
||||
merge_base="$(git merge-base "${local_sha}" "${remote_name}/${remote_branch}" 2>/dev/null || true)"
|
||||
if [[ -n "${merge_base}" ]]; then
|
||||
changed_files="$(git diff --name-only --diff-filter=ACMR "${merge_base}" "${local_sha}" || true)"
|
||||
fi
|
||||
fi
|
||||
if [[ -z "${changed_files}" ]]; then
|
||||
changed_files="$(git diff-tree --no-commit-id --name-only --diff-filter=ACMR -r "${local_sha}" || true)"
|
||||
fi
|
||||
else
|
||||
changed_files="$(git diff --name-only --diff-filter=ACMR "${remote_sha}" "${local_sha}" || true)"
|
||||
fi
|
||||
|
||||
if frontend_paths_in "${changed_files}"; then
|
||||
need_frontend_build=1
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ "${need_frontend_build}" -eq 0 ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! run_frontend_build "${ROOT_DIR}"; then
|
||||
echo "[pre-push] 前端 build 失败,已阻止 push。"
|
||||
echo "[pre-push] 跳过检查可设置: SKIP_FRONTEND_HOOKS=1 git push"
|
||||
echo "[pre-push] 或跳过全部 hook: git push --no-verify"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[pre-push] 前端 build 通过。"
|
||||
exit 0
|
||||
+23
-15
@@ -1,11 +1,12 @@
|
||||
# Environments
|
||||
deploy.sh
|
||||
deploy_docker_rsync.sh
|
||||
docs/
|
||||
#docs/
|
||||
venv/
|
||||
backend/venv/
|
||||
backend/instance/
|
||||
tmpwork/
|
||||
env/
|
||||
.env
|
||||
|
||||
# .env
|
||||
.venv
|
||||
build/
|
||||
develop-eggs/
|
||||
@@ -30,12 +31,19 @@ __pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# Root tooling (commitlint)
|
||||
/node_modules/
|
||||
package-lock.json
|
||||
|
||||
# Frontend
|
||||
frontend/node_modules/
|
||||
# frontend/dist/ <-- Commented out to allow committing dist
|
||||
frontend/dist/
|
||||
frontend/.DS_Store
|
||||
frontend/.env.local
|
||||
frontend/.env.*.local
|
||||
frontend/.npm-cache
|
||||
frontend/public/WW_verify_46MjWA55y3PBRLid.txt
|
||||
frontend/package-lock.json
|
||||
|
||||
# IDEs
|
||||
.vscode/
|
||||
@@ -52,17 +60,17 @@ Thumbs.db
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
# tmp
|
||||
.tmp/
|
||||
.tmp2/
|
||||
|
||||
docker-compose.yml
|
||||
nginx.conf
|
||||
deploy_docker_rsync.sh
|
||||
.npm-cache
|
||||
.npm-cache2
|
||||
.pip-cache
|
||||
|
||||
|
||||
# 忽略Oracle Instant Client本地目录
|
||||
oracle_client/
|
||||
|
||||
gunicorn_config.py
|
||||
hxops_menu.sh
|
||||
|
||||
nginx.conf
|
||||
docker-compose.yml
|
||||
gunicorn_config.py
|
||||
hxops_menu.sh
|
||||
# local env override
|
||||
.env.local
|
||||
@@ -1,63 +0,0 @@
|
||||
* Serving Flask app 'app'
|
||||
* Debug mode: on
|
||||
[31m[1mWARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.[0m
|
||||
* Running on all addresses (0.0.0.0)
|
||||
* Running on http://127.0.0.1:5002
|
||||
* Running on http://192.168.31.48:5002
|
||||
[33mPress CTRL+C to quit[0m
|
||||
* Restarting with stat
|
||||
* Debugger is active!
|
||||
* Debugger PIN: 679-745-431
|
||||
127.0.0.1 - - [28/Mar/2026 23:45:02] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:45:08] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:45:37] "[35m[1mPOST /api/admin/agents HTTP/1.1[0m" 201 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:47:50] "[31m[1mGET /api/admin/agents HTTP/1.1[0m" 403 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:47:55] "[31m[1mGET /api/admin/agents HTTP/1.1[0m" 403 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:48:02] "GET /api/admin/agents HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:00] "GET /api/agents/public HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:10] "[31m[1mPOST /api/user/login HTTP/1.1[0m" 401 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:17] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:18] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:20] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:20] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:30] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:30] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:31] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:31] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:49:31] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:50:02] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:50:45] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:50:51] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "GET /api/user/announcements HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:32] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:34] "GET /api/agents/public HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:43] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:43] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:46] "GET /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:57] "POST /api/user/change-password HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:59] "GET /api/user/announcements HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:55:59] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:02] "GET /api/agents/public HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:07] "POST /api/user/login HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:07] "GET /api/user/home HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/agents HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/permission-requests HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/reports/usage HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/departments HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/user/announcements HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/quick-questions HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/users HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/wecom/bindings?bound_only=false HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/wecom/login-audits?limit=200 HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:56:14] "GET /api/admin/reports/feedback HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:05] "GET /api/admin/quick-questions HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:05] "GET /api/admin/wecom/bindings?bound_only=false HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:05] "GET /api/admin/wecom/login-audits?limit=200 HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:16] "GET /api/admin/quick-questions HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:17] "GET /api/admin/wecom/login-audits?limit=200 HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:17] "GET /api/admin/wecom/bindings?bound_only=false HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:27] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
127.0.0.1 - - [28/Mar/2026 23:57:28] "PUT /api/user/profile HTTP/1.1" 200 -
|
||||
@@ -1 +0,0 @@
|
||||
4903
|
||||
@@ -1,10 +0,0 @@
|
||||
|
||||
> frontend@0.0.0 dev
|
||||
> vite
|
||||
|
||||
|
||||
VITE v8.0.0-beta.15 ready in 118 ms
|
||||
|
||||
➜ Local: http://localhost:8881/
|
||||
➜ Network: use --host to expose
|
||||
11:51:45 PM [vite] (client) page reload src/main.ts
|
||||
@@ -1 +0,0 @@
|
||||
4917
|
||||
@@ -1,12 +0,0 @@
|
||||
2026-03-28 23:44:52.265 CST [4865] LOG: starting PostgreSQL 18.1 (Homebrew) on aarch64-apple-darwin25.2.0, compiled by Apple clang version 17.0.0 (clang-1700.6.3.2), 64-bit
|
||||
2026-03-28 23:44:52.267 CST [4865] LOG: listening on IPv6 address "::1", port 5432
|
||||
2026-03-28 23:44:52.267 CST [4865] LOG: listening on IPv4 address "127.0.0.1", port 5432
|
||||
2026-03-28 23:44:52.267 CST [4865] LOG: listening on Unix socket "/tmp/.s.PGSQL.5432"
|
||||
2026-03-28 23:44:52.275 CST [4872] LOG: database system was shut down at 2026-03-28 23:37:09 CST
|
||||
2026-03-28 23:44:52.277 CST [4865] LOG: database system is ready to accept connections
|
||||
2026-03-28 23:49:52.269 CST [4870] LOG: checkpoint starting: time
|
||||
2026-03-28 23:49:53.685 CST [4870] LOG: checkpoint complete: wrote 14 buffers (0.1%), wrote 3 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=1.414 s, sync=0.002 s, total=1.416 s; sync files=16, longest=0.001 s, average=0.001 s; distance=40 kB, estimate=40 kB; lsn=0/3994578, redo lsn=0/39944E8
|
||||
2026-03-28 23:54:52.680 CST [4870] LOG: checkpoint starting: time
|
||||
2026-03-28 23:54:53.185 CST [4870] LOG: checkpoint complete: wrote 5 buffers (0.0%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=0.505 s, sync=0.001 s, total=0.506 s; sync files=6, longest=0.001 s, average=0.001 s; distance=11 kB, estimate=37 kB; lsn=0/3997280, redo lsn=0/3997228
|
||||
2026-03-28 23:59:52.181 CST [4870] LOG: checkpoint starting: time
|
||||
2026-03-28 23:59:52.687 CST [4870] LOG: checkpoint complete: wrote 5 buffers (0.0%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=0.505 s, sync=0.001 s, total=0.507 s; sync files=6, longest=0.001 s, average=0.001 s; distance=12 kB, estimate=34 kB; lsn=0/399A400, redo lsn=0/399A3A8
|
||||
@@ -1 +0,0 @@
|
||||
4865
|
||||
@@ -0,0 +1,159 @@
|
||||
# AGENTS.md — HXOPS 协作与开发规范
|
||||
|
||||
> 本文件是 **AI 编程助手(Cursor / Codex 等)和团队成员的统一入口**。
|
||||
> 原则:**只写最关键的强约束、速览与索引,详细内容一律链接到 `docs/` 下的权威文档**,避免双份维护。
|
||||
> 修改本文件请走正常评审;规则若与 `docs/` 冲突,以 `docs/` 中的专项文档为准。
|
||||
|
||||
---
|
||||
|
||||
## 1. 项目速览
|
||||
|
||||
**Enterprise AI Gateway(HXOPS)**:企业级 AI 聚合网关,统一管理/分发 AI Agent(Dify 应用),提供统一对话入口、RBAC 权限、全链路审计与个性化工作台。
|
||||
|
||||
| 层 | 技术栈 |
|
||||
| --- | --- |
|
||||
| 前端 | Vue 3 (Composition API) + TypeScript + Vite + TailwindCSS + Pinia + Vue Router + Vue I18n |
|
||||
| 后端 | Flask (Python 3.12) + Gevent + SQLAlchemy 2.0 + Flask-Migrate(Alembic) + Gunicorn |
|
||||
| 数据/基建 | PostgreSQL + Redis + Nginx + Supervisor + Docker Compose |
|
||||
| 集成 | Dify、企业微信、OA/HR(SQLServer)、PLM(Oracle)、MinIO |
|
||||
| 研发协作 | Gitee 托管 + Jenkins CI/CD(dev/test/prod 多环境) |
|
||||
|
||||
完整背景见 **[docs/project_context.md](docs/project_context.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 技术架构统一(新功能选型)
|
||||
|
||||
> 仓库历史代码后端为 Flask,仍按原栈维护;**新功能/新模块**统一向以下技术栈收敛:
|
||||
|
||||
- **后端**:优先使用 **Python + FastAPI**(异步、Pydantic 校验、自动 OpenAPI 文档)。
|
||||
- **前端**:优先使用 **Vue 3 + TailwindCSS**(Composition API + TypeScript)。
|
||||
- 数据访问继续使用 **SQLAlchemy 2.0**;数据库迁移继续使用 **Alembic**(见 §8)。
|
||||
- 选型有特殊需要偏离上述约定时,须在评审/提交说明中给出理由。
|
||||
|
||||
---
|
||||
|
||||
## 3. 目录地图(改代码前先定位)
|
||||
|
||||
```text
|
||||
backend/app/
|
||||
api/ # Blueprint 路由(admin / chat / agents / knowledge_base / shipping_notice ...)
|
||||
services/ # 业务逻辑(dify、oa_*、plm_oracle、minio_service、wecom_* ...)
|
||||
models.py # SQLAlchemy 模型(改这里必须配套迁移,见 §8)
|
||||
response_utils.py / errors.py / decorators.py # 统一返回、异常、权限装饰器
|
||||
backend/migrations/ # Alembic 迁移文件
|
||||
frontend/src/
|
||||
features/ # 按业务域组织(admin / auth / chat)
|
||||
composables/# Hooks(如 useChat.ts)
|
||||
views/ components/ i18n.ts
|
||||
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
|
||||
docs/ # 权威文档(规范、上下文、流程、发布说明)
|
||||
```
|
||||
|
||||
**约定**:新逻辑优先放入对应 `services/`(后端)或 `features/composables/`(前端),复用既有 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
|
||||
|
||||
---
|
||||
|
||||
## 4. 常用命令
|
||||
|
||||
```bash
|
||||
# 后端
|
||||
cd backend && source venv/bin/activate
|
||||
python run.py # 启动开发服务器
|
||||
flask db migrate -m "msg" && flask db upgrade # 数据库迁移
|
||||
|
||||
# 前端
|
||||
cd frontend && npm run dev # 开发
|
||||
npm run build # 改动了 frontend/ 必须保证 build 通过
|
||||
|
||||
# 部署(与 Jenkins 一致,示例:prod)
|
||||
./scripts/deploy_compose.sh prod true true true
|
||||
docker compose logs -f hxops-backend
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 代码规范与注释
|
||||
|
||||
- **注释写「为什么」,不写「是什么」**:避免逐行复述代码(如 `// 自增 i`、`# 调用接口`);只对非显而易见的意图、权衡、约束、坑点、外部协议/边界条件加注释。
|
||||
- **公共接口必须有文档注释**:
|
||||
- 后端:对外的函数/类/接口使用 docstring,说明用途、参数、返回、可能抛出的异常;FastAPI 路由用类型注解 + Pydantic 模型,复杂逻辑补 docstring。
|
||||
- 前端:导出的 composable / 工具函数 / 复杂组件 props 用 JSDoc/TSDoc 说明。
|
||||
- **复杂或临时方案要留痕**:含业务规则、算法、兼容性处理的代码段加简要说明;临时方案用 `TODO:` / `FIXME:` 标注并附原因或关联任务号。
|
||||
- **注释与代码同步更新**:改逻辑必须同步改注释,禁止留下与实现不符的过期注释。
|
||||
- **统一语言**:注释可用中文,但术语/标识符保持与代码一致,避免中英混排导致歧义。
|
||||
- 不要用注释提交被注释掉的废弃代码(交给 Git 历史管理)。
|
||||
|
||||
---
|
||||
|
||||
## 6. Git 提交规范(强制 / 已自动校验)
|
||||
|
||||
- 提交信息必须符合 **Conventional Commits**,由 `commitlint.config.cjs` + `.githooks/commit-msg` **自动拦截**。
|
||||
- 首次拉取后需安装 hooks:`./scripts/install_git_hooks.sh`。
|
||||
- 格式:`<type>(<scope>): <subject>`,`subject` 用祈使语气、不以句号结尾、≤100 字符。
|
||||
- 允许的 `type`:`feat` `fix` `docs` `style` `refactor` `perf` `test` `build` `ci` `chore` `revert`。
|
||||
- 禁止无语义提交(`update`、`fix bug`、`111`);一个提交只做一件事。
|
||||
|
||||
详见 **[docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md)** 与 **[docs/GIT_HOOKS.md](docs/GIT_HOOKS.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 7. 分支与发布流程
|
||||
|
||||
- 分支主线:`dev`(日常开发)→ `test`(自测/交叉/质检)→ `prod`(生产发布)。
|
||||
- 功能分支从 `dev` 切出(`feature/xxx`、`fix/xxx`),完成后合回 `dev`。
|
||||
- **禁止**直接在 `prod` / 公共分支上开发或直推;`prod` 必须经合并请求。
|
||||
- 生产 hotfix 合入 `prod` 后须**反向同步**回 `dev`(必要时 `test`),避免分支漂移。
|
||||
- 发布完成对版本打 tag,格式 `V26.6.1`(26 年 6 月第 1 次发布)。
|
||||
|
||||
完整流程(含自测/交叉测试/质检/Review 卡点)见 **[docs/release_workflow.md](docs/release_workflow.md)** 与 **[docs/convention/开发标准流程.md](docs/convention/开发标准流程.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 8. 红线与高风险约束(agent 必须遵守)
|
||||
|
||||
- 🔒 **严禁提交任何密钥/密码/生产地址等敏感信息**。`.env.local` / `.env.*` 不进仓库的部分不得硬编码进代码或提交。
|
||||
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。
|
||||
- 🌐 **环境变量分层**:`.env.shared` + `.env.<env>`(dev/test/prod),不要在代码里写死环境值。规则见 **[docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md)** 与 **[docs/convention/环境变量规则.md](docs/convention/环境变量规则.md)**。
|
||||
- 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en-US / th-TH`,禁止硬编码中文。
|
||||
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
|
||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
|
||||
---
|
||||
|
||||
## 9. 需求与文档维护(开发前先查,开发后必更)
|
||||
|
||||
开发任何功能前,**优先查阅以下文档**了解背景与现状:
|
||||
|
||||
- **[docs/demand.md](docs/demand.md)** — 需求文档(要做什么、业务目标与范围)。
|
||||
- **[docs/tec.md](docs/tec.md)** — 技术架构文档(架构设计、技术选型与约束)。
|
||||
- **[docs/funclist.md](docs/funclist.md)** — 功能清单(已有/在建功能总览)。
|
||||
|
||||
**撰写或变更功能时,必须同步更新相关文档**:
|
||||
|
||||
- 新增/调整功能 → 更新 `funclist.md`(功能清单)。
|
||||
- 涉及需求变化 → 更新 `demand.md`。
|
||||
- 涉及架构/技术选型变化 → 更新 `tec.md`。
|
||||
- 文档更新与代码改动放在同一提交或同一 PR 中,保证「代码与文档一致」。
|
||||
|
||||
---
|
||||
|
||||
## 10. 文档索引(权威来源)
|
||||
|
||||
| 主题 | 文档 |
|
||||
| --- | --- |
|
||||
| 项目上下文 / 架构 / 数据模型 | [docs/project_context.md](docs/project_context.md) |
|
||||
| 需求文档 | [docs/demand.md](docs/demand.md) |
|
||||
| 技术架构文档 | [docs/tec.md](docs/tec.md) |
|
||||
| 功能清单 | [docs/funclist.md](docs/funclist.md) |
|
||||
| 新人环境搭建 / 分支原则 | [docs/新人环境搭建与配置文档.md](docs/新人环境搭建与配置文档.md) |
|
||||
| 发布流程(dev→test→prod) | [docs/release_workflow.md](docs/release_workflow.md) · [docs/convention/开发标准流程.md](docs/convention/开发标准流程.md) |
|
||||
| 提交规范 | [docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md) |
|
||||
| Git Hooks | [docs/GIT_HOOKS.md](docs/GIT_HOOKS.md) |
|
||||
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
|
||||
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
Vendored
+579
@@ -0,0 +1,579 @@
|
||||
import groovy.json.JsonOutput
|
||||
|
||||
// 企业微信群机器人部署通知(成功/失败/中止)。Webhook 完整 URL 存 Jenkins 凭据 WECOM_WEBHOOK_DEPLOY,勿写入 Git。
|
||||
// WeCom group-bot deploy notifications. Store webhook URL in Jenkins Secret text credential only.
|
||||
def notifyWecomDeploy(Map opts) {
|
||||
if ((env.DISABLE_DEPLOY_WECOM_NOTIFY ?: '').equalsIgnoreCase('true')) {
|
||||
echo '[WeCom] DISABLE_DEPLOY_WECOM_NOTIFY=true,跳过通知'
|
||||
return
|
||||
}
|
||||
|
||||
def credId = (opts.webhookCredId ?: env.WECOM_WEBHOOK_CRED ?: 'WECOM_WEBHOOK_DEPLOY').trim()
|
||||
def content = buildDeployNotifyMarkdown(opts)
|
||||
|
||||
try {
|
||||
withCredentials([string(credentialsId: credId, variable: 'WECOM_WEBHOOK_URL')]) {
|
||||
def webhookUrl = WECOM_WEBHOOK_URL?.trim()
|
||||
if (!webhookUrl) {
|
||||
echo "[WeCom] 凭据 ${credId} 为空,跳过通知"
|
||||
return
|
||||
}
|
||||
|
||||
def payload = [
|
||||
msgtype: 'markdown',
|
||||
markdown: [content: content.markdown],
|
||||
]
|
||||
writeFile(file: 'wecom-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
|
||||
|
||||
def httpCode = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
set +e
|
||||
code=$(curl -sS -o wecom-notify-response.txt -w "%{http_code}" \
|
||||
-X POST "$WECOM_WEBHOOK_URL" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @wecom-notify-payload.json)
|
||||
echo "[WeCom] HTTP ${code}" >&2
|
||||
cat wecom-notify-response.txt >&2 || true
|
||||
echo "${code}"
|
||||
'''
|
||||
).trim()
|
||||
|
||||
def resp = readFile('wecom-notify-response.txt').trim()
|
||||
if (httpCode == '200' && resp.contains('"errcode":0')) {
|
||||
echo '[WeCom] 通知已发送'
|
||||
} else {
|
||||
echo "[WeCom] 发送可能失败,HTTP=${httpCode},响应=${resp}"
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
echo "[WeCom] 通知发送异常(不影响构建结果): ${e.message}"
|
||||
}
|
||||
}
|
||||
|
||||
// PushPlus → 个人微信(方案3)。Token 存 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN,见 https://www.pushplus.plus/
|
||||
def buildDeployNotifyMarkdown(Map opts) {
|
||||
def envLabel = opts.envLabel ?: '部署环境'
|
||||
def host = opts.host ?: '-'
|
||||
def status = (opts.status ?: 'success').toString().toLowerCase()
|
||||
def isSuccess = status == 'success'
|
||||
def extraNote = (opts.extraNote ?: '').trim()
|
||||
def shortCommit = env.GIT_COMMIT ? env.GIT_COMMIT.take(8) : '-'
|
||||
def buildLink = env.BUILD_URL ?: '-'
|
||||
def title = isSuccess ? "✅ ${envLabel} 部署成功" : "❌ ${envLabel} 部署失败"
|
||||
def lines = [
|
||||
"## ${title}",
|
||||
"> **分支**: ${env.BRANCH_NAME ?: '-'}",
|
||||
"> **提交**: `${shortCommit}`",
|
||||
"> **目标主机**: ${host}",
|
||||
"> **构建**: [#${env.BUILD_NUMBER}](${buildLink})",
|
||||
"> **变更**: 前端=${env.FRONTEND_CHANGED ?: '-'} 后端=${env.BACKEND_CHANGED ?: '-'} 配置=${env.DEPLOY_CONFIG_CHANGED ?: '-'}",
|
||||
]
|
||||
if (env.FORCE_FULL_DEPLOY_USED == 'true') {
|
||||
lines << '> **备注**: 强制全量部署'
|
||||
}
|
||||
if (env.REMOTE_DRIFT_DETECTED == 'true') {
|
||||
lines << '> **备注**: 远端版本漂移触发部署'
|
||||
}
|
||||
if (env.ROLLBACK_IMAGE_TAG?.trim()) {
|
||||
lines << "> **备注**: 镜像回滚 → `${env.ROLLBACK_IMAGE_TAG.trim()}`(预构建模式,跳过 db upgrade)"
|
||||
}
|
||||
if (extraNote) {
|
||||
lines << "> **说明**: ${extraNote}"
|
||||
}
|
||||
if (!isSuccess) {
|
||||
lines << '> **处理**: 请打开 Jenkins 构建日志排查失败步骤'
|
||||
}
|
||||
return [title: title, markdown: lines.join('\n')]
|
||||
}
|
||||
|
||||
def notifyPushPlusDeploy(Map opts) {
|
||||
if ((env.DISABLE_DEPLOY_PUSHPLUS_NOTIFY ?: '').equalsIgnoreCase('true')) {
|
||||
echo '[PushPlus] DISABLE_DEPLOY_PUSHPLUS_NOTIFY=true,跳过通知'
|
||||
return
|
||||
}
|
||||
|
||||
def credId = (opts.tokenCredId ?: env.PUSHPLUS_TOKEN_CRED ?: 'PUSHPLUS_DEPLOY_TOKEN').trim()
|
||||
def content = buildDeployNotifyMarkdown(opts)
|
||||
|
||||
try {
|
||||
withCredentials([string(credentialsId: credId, variable: 'PUSHPLUS_TOKEN')]) {
|
||||
def token = PUSHPLUS_TOKEN?.trim()
|
||||
if (!token) {
|
||||
echo "[PushPlus] 凭据 ${credId} 为空,跳过通知"
|
||||
return
|
||||
}
|
||||
|
||||
def payload = [
|
||||
token: token,
|
||||
title: "[HxOps] ${content.title}",
|
||||
content: content.markdown,
|
||||
template: 'markdown',
|
||||
channel: 'wechat',
|
||||
]
|
||||
def topic = (env.PUSHPLUS_TOPIC ?: '').trim()
|
||||
if (topic) {
|
||||
payload.topic = topic
|
||||
}
|
||||
|
||||
writeFile(file: 'pushplus-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
|
||||
|
||||
def httpCode = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
set +e
|
||||
code=$(curl -sS -o pushplus-notify-response.txt -w "%{http_code}" \
|
||||
-X POST "https://www.pushplus.plus/send" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @pushplus-notify-payload.json)
|
||||
echo "[PushPlus] HTTP ${code}" >&2
|
||||
cat pushplus-notify-response.txt >&2 || true
|
||||
echo "${code}"
|
||||
'''
|
||||
).trim()
|
||||
|
||||
def resp = readFile('pushplus-notify-response.txt').trim()
|
||||
if (httpCode == '200' && (resp.contains('"code":200') || resp.contains('"code": 200'))) {
|
||||
echo '[PushPlus] 微信通知已发送'
|
||||
} else {
|
||||
echo "[PushPlus] 发送可能失败,HTTP=${httpCode},响应=${resp}"
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
echo "[PushPlus] 通知发送异常(不影响构建结果): ${e.message}"
|
||||
}
|
||||
}
|
||||
|
||||
// 企业微信 + PushPlus 微信双通道
|
||||
def notifyDeployAll(Map opts) {
|
||||
notifyWecomDeploy(opts)
|
||||
notifyPushPlusDeploy(opts)
|
||||
}
|
||||
|
||||
pipeline {
|
||||
agent any
|
||||
|
||||
// 构建参数:首次在 Jenkinsfile 中加入后需至少跑一次构建,后续才能在「Build with Parameters」中看到 / Build params appear after first run
|
||||
parameters {
|
||||
// 跳过变更检测,强制进入部署阶段(等同前后端与部署配置均有变更)
|
||||
booleanParam(
|
||||
name: 'FORCE_FULL_DEPLOY',
|
||||
defaultValue: false,
|
||||
description: '勾选则跳过 Git diff(以及下方的远端校验);仍会执行生产人工确认(除非 Job 环境变量 SKIP_PROD_DEPLOY_INPUT=true)。'
|
||||
)
|
||||
// 本地判定「无变更」时,SSH 读远端部署目录的提交与分支,不一致则触发部署
|
||||
booleanParam(
|
||||
name: 'VERIFY_REMOTE_WHEN_NO_DIFF',
|
||||
defaultValue: false,
|
||||
description: '仅当本地 diff 判定无前后端/部署配置变更时生效:额外 SSH 到本分支对应目标机执行 git rev-parse / branch --show-current,与本次 GIT_COMMIT、BRANCH_NAME 比对,不一致则视为需要部署。'
|
||||
)
|
||||
// 生产镜像回滚:填写历史 tag 后缀(如 prod-a1b2c3d4),走 deploy_compose.sh 预构建模式
|
||||
string(
|
||||
name: 'ROLLBACK_IMAGE_TAG',
|
||||
defaultValue: '',
|
||||
description: '【仅生产】非空时回滚到该镜像 tag(hxops-frontend:<tag> / hxops-backend:<tag>)。示例:prod-a1b2c3d4。不拉最新代码、不执行 db upgrade。留空为正常部署。'
|
||||
)
|
||||
}
|
||||
|
||||
options {
|
||||
// 打印时间戳,便于在 Jenkins 日志里定位耗时步骤 / Add timestamps to locate slow steps in Jenkins logs
|
||||
timestamps()
|
||||
// 禁止同一任务并发执行,避免部署相互覆盖 / Prevent concurrent runs to avoid deployment conflicts
|
||||
disableConcurrentBuilds()
|
||||
}
|
||||
|
||||
environment {
|
||||
// 环境服务器地址 / Environment hosts
|
||||
DEV_DEPLOY_HOST = '8.152.207.171'
|
||||
TEST_DEPLOY_HOST = '192.168.100.192'
|
||||
PROD_DEPLOY_HOST = '192.168.100.230'
|
||||
|
||||
// SSH 连接参数 / SSH connection settings
|
||||
DEV_SSH_USER = 'root'
|
||||
TEST_SSH_USER = 'lisq'
|
||||
PROD_SSH_USER = 'inspur'
|
||||
SSH_PORT = '22'
|
||||
|
||||
// 各环境统一部署目录 / Unified deploy root
|
||||
DEV_DEPLOY_ROOT = '/opt/hxops'
|
||||
TEST_DEPLOY_ROOT = '/home/lisq/ai/platform/hxops'
|
||||
PROD_DEPLOY_ROOT = '/data/ai-platform/hxops/'
|
||||
|
||||
// PushPlus 群组编码(一对多推送到个人微信);Token 仍用 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN
|
||||
PUSHPLUS_TOPIC = 'hxops666'
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Checkout') {
|
||||
steps {
|
||||
// 多分支流水线检出当前分支代码 / Checkout source from current branch in Multibranch Pipeline
|
||||
checkout scm
|
||||
echo "[Checkout] BRANCH_NAME=${env.BRANCH_NAME}, GIT_BRANCH=${env.GIT_BRANCH}, COMMIT=${env.GIT_COMMIT}"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Detect Changes') {
|
||||
steps {
|
||||
script {
|
||||
env.FORCE_FULL_DEPLOY_USED = 'false'
|
||||
env.REMOTE_DRIFT_DETECTED = 'false'
|
||||
env.REMOTE_VERIFY_SKIPPED = 'false'
|
||||
env.ROLLBACK_IMAGE_TAG = ''
|
||||
|
||||
def rollbackTag = params.ROLLBACK_IMAGE_TAG?.trim()
|
||||
if (rollbackTag) {
|
||||
env.ROLLBACK_IMAGE_TAG = rollbackTag
|
||||
env.FRONTEND_CHANGED = 'true'
|
||||
env.BACKEND_CHANGED = 'true'
|
||||
env.DEPLOY_CONFIG_CHANGED = 'false'
|
||||
echo "[Detect Changes] ROLLBACK_IMAGE_TAG=${rollbackTag},将使用预构建模式回滚(跳过 Git 更新与 db upgrade)"
|
||||
return
|
||||
}
|
||||
|
||||
// BRANCH_NAME 必须由 Multibranch Pipeline 提供 / BRANCH_NAME must be provided by Multibranch Pipeline
|
||||
def branchName = env.BRANCH_NAME?.trim()
|
||||
if (!branchName) {
|
||||
error('BRANCH_NAME is empty. Please run this as a Multibranch Pipeline job.')
|
||||
}
|
||||
|
||||
// 与 Deploy Prod 阶段一致:用于判断当前分支是否有对应部署目标(远端校验仅在这些分支上有意义)
|
||||
def extraBranches = (env.EXTRA_PROD_BRANCHES ?: '').split(',').collect { it.trim() }.findAll { it }
|
||||
def prodLikeBranches = (['prod', 'sophie', 'sophie-wecom'] + extraBranches).unique()
|
||||
|
||||
def getDeploySshTarget = { String b ->
|
||||
if (b == 'dev') {
|
||||
return [host: env.DEV_DEPLOY_HOST, user: env.DEV_SSH_USER, root: env.DEV_DEPLOY_ROOT, cred: 'SSH_DEV_DEPLOY']
|
||||
}
|
||||
if (b == 'test') {
|
||||
return [host: env.TEST_DEPLOY_HOST, user: env.TEST_SSH_USER, root: env.TEST_DEPLOY_ROOT, cred: 'SSH_TEST_DEPLOY']
|
||||
}
|
||||
if (prodLikeBranches.contains(b)) {
|
||||
return [host: env.PROD_DEPLOY_HOST, user: env.PROD_SSH_USER, root: env.PROD_DEPLOY_ROOT, cred: 'SSH_PROD_DEPLOY']
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 强制全量:跳过 Git diff 与远端校验,避免「换分支同 SHA」或纯重发时被跳过
|
||||
if (params.FORCE_FULL_DEPLOY == true) {
|
||||
env.FRONTEND_CHANGED = 'true'
|
||||
env.BACKEND_CHANGED = 'true'
|
||||
env.DEPLOY_CONFIG_CHANGED = 'true'
|
||||
env.FORCE_FULL_DEPLOY_USED = 'true'
|
||||
echo "[Detect Changes] FORCE_FULL_DEPLOY=true,已跳过 Git diff 与远端校验"
|
||||
echo "[Detect Changes] FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
return
|
||||
}
|
||||
|
||||
// 以上次成功构建为差异基线 / Use previous successful commit as diff base
|
||||
def baseCommit = env.GIT_PREVIOUS_SUCCESSFUL_COMMIT?.trim()
|
||||
if (!baseCommit) {
|
||||
baseCommit = sh(returnStdout: true, script: 'git rev-parse HEAD^ 2>/dev/null || true').trim()
|
||||
}
|
||||
|
||||
List<String> changedFiles = []
|
||||
if (baseCommit) {
|
||||
changedFiles = sh(
|
||||
returnStdout: true,
|
||||
script: "git diff --name-only ${baseCommit} ${env.GIT_COMMIT}"
|
||||
).trim().split('\\n').findAll { it?.trim() }
|
||||
} else {
|
||||
// 首次构建默认按前后端都变更处理 / First build defaults to full-scope deployment
|
||||
changedFiles = ['frontend/', 'backend/']
|
||||
}
|
||||
|
||||
// 目录级变更识别:用于前后端增量构建 / Directory-level change detection for incremental builds
|
||||
def frontendChanged = changedFiles.any { it.startsWith('frontend/') }
|
||||
def backendChanged = changedFiles.any {
|
||||
it.startsWith('backend/') || it == 'docs/(表+字段).md'
|
||||
}
|
||||
def deployConfigChanged = changedFiles.any {
|
||||
it == 'docker-compose.yml' ||
|
||||
it == 'Jenkinsfile' ||
|
||||
it == '.dockerignore' ||
|
||||
it == 'scripts/deploy_compose.sh' ||
|
||||
it == 'scripts/healthcheck.sh' ||
|
||||
it == '.env.dev' ||
|
||||
it == '.env.test' ||
|
||||
it == '.env.prod'
|
||||
}
|
||||
|
||||
// 本地判定无变更且开启远端校验:SSH 读部署目录提交与分支,与本次构建对齐(需目标机允许只读 git 命令)
|
||||
def noLocalDiff = !frontendChanged && !backendChanged && !deployConfigChanged
|
||||
if (noLocalDiff && params.VERIFY_REMOTE_WHEN_NO_DIFF == true) {
|
||||
def target = getDeploySshTarget(branchName)
|
||||
if (!target) {
|
||||
env.REMOTE_VERIFY_SKIPPED = 'true'
|
||||
echo "[Detect Changes] VERIFY_REMOTE_WHEN_NO_DIFF=true,但当前分支无对应部署目标,跳过远端校验"
|
||||
} else {
|
||||
def expectedCommit = env.GIT_COMMIT?.trim()
|
||||
def remoteOut = ''
|
||||
sshagent(credentials: [target.cred]) {
|
||||
// 仅查询:不 fetch,不改变远端工作区;cd 失败或仓库异常会导致 SSH 步骤失败
|
||||
remoteOut = sh(
|
||||
returnStdout: true,
|
||||
script: """ssh -p ${env.SSH_PORT} -o StrictHostKeyChecking=no ${target.user}@${target.host} 'set -e; cd "${target.root}"; git rev-parse HEAD; git branch --show-current 2>/dev/null || true'"""
|
||||
).trim()
|
||||
}
|
||||
def remoteLines = remoteOut.split('\n') as List
|
||||
def remoteCommit = remoteLines ? remoteLines[0].trim() : ''
|
||||
def remoteBranch = remoteLines.size() > 1 ? remoteLines[1..-1].join('\n').trim() : ''
|
||||
|
||||
def commitMismatch = remoteCommit && expectedCommit && remoteCommit != expectedCommit
|
||||
def branchMismatch = remoteBranch && remoteBranch != branchName
|
||||
|
||||
echo "[Detect Changes] 远端校验 host=${target.host} root=${target.root}"
|
||||
echo "[Detect Changes] 远端 HEAD=${remoteCommit}, 期望=${expectedCommit}"
|
||||
echo "[Detect Changes] 远端分支=${remoteBranch ?: '(空或 detached)'}, 期望=${branchName}"
|
||||
|
||||
if (commitMismatch || branchMismatch) {
|
||||
frontendChanged = true
|
||||
backendChanged = true
|
||||
deployConfigChanged = true
|
||||
env.REMOTE_DRIFT_DETECTED = 'true'
|
||||
echo '[Detect Changes] 远端与本次构建不一致,已强制视为需要部署(前后端+部署配置标志均为 true)'
|
||||
} else {
|
||||
echo '[Detect Changes] 远端与本次构建一致(或无法解析分支名),仍按本地无变更处理'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
env.FRONTEND_CHANGED = frontendChanged ? 'true' : 'false'
|
||||
env.BACKEND_CHANGED = backendChanged ? 'true' : 'false'
|
||||
env.DEPLOY_CONFIG_CHANGED = deployConfigChanged ? 'true' : 'false'
|
||||
|
||||
echo "[Detect Changes] branch=${branchName}"
|
||||
echo "[Detect Changes] baseCommit=${baseCommit ?: 'none'}"
|
||||
echo "[Detect Changes] files=${changedFiles.join(', ')}"
|
||||
echo "[Detect Changes] FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stage('Frontend Build (CI)') {
|
||||
// when {
|
||||
// expression { env.FRONTEND_CHANGED == 'true' }
|
||||
// }
|
||||
// steps {
|
||||
// echo '[Frontend Build] FRONTEND_CHANGED=true,容器内执行 npm ci && npm run build(与部署构建一致)'
|
||||
// sh '''
|
||||
// set -e
|
||||
// docker run --rm \
|
||||
// -v "${WORKSPACE}:/repo" \
|
||||
// -w /repo \
|
||||
// node:22-alpine sh -c "chmod +x scripts/ci_frontend_build.sh && ./scripts/ci_frontend_build.sh"
|
||||
// '''
|
||||
// }
|
||||
// }
|
||||
|
||||
stage('Deploy Dev') {
|
||||
when {
|
||||
expression {
|
||||
// dev 分支都部署到 dev 环境 / dev branches deploy to dev environment
|
||||
(env.BRANCH_NAME == 'dev') &&
|
||||
// 无变更不部署 / Skip deploy when no effective changes
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
echo "[Deploy Dev] start branch=${env.BRANCH_NAME} host=${env.DEV_DEPLOY_HOST}"
|
||||
|
||||
// 使用Jenkins中的SSH_DEV_DEPLOY私钥部署到开发服务器
|
||||
// Use SSH_DEV_DEPLOY credential to deploy to dev server
|
||||
sshagent(credentials: ['SSH_DEV_DEPLOY']) {
|
||||
sh """
|
||||
set -e
|
||||
# 远端更新代码并执行部署脚本 / Update repo on target host and run deploy script
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${DEV_SSH_USER}@${DEV_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${DEV_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
# 清掉工作区里对已跟踪文件的本地修改,否则改 deploy 脚本后 checkout 会报 “would be overwritten”
|
||||
git reset --hard HEAD
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
git reset --hard "origin/${BRANCH_NAME}"
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh dev "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
echo "[Deploy Dev] done"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy Test') {
|
||||
when {
|
||||
expression {
|
||||
// test / env 分支均部署到 test 环境主机;代码与当前构建分支一致(不再强制 origin/test)
|
||||
(env.BRANCH_NAME == 'test' || env.BRANCH_NAME == 'env') &&
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
echo "[Deploy Test] start branch=${env.BRANCH_NAME} host=${env.TEST_DEPLOY_HOST}"
|
||||
|
||||
// 使用Jenkins中的SSH_TEST_DEPLOY私钥部署到测试服务器
|
||||
// Use SSH_TEST_DEPLOY credential to deploy to test server
|
||||
sshagent(credentials: ['SSH_TEST_DEPLOY']) {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${TEST_SSH_USER}@${TEST_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${TEST_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
git reset --hard HEAD
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
git reset --hard "origin/${BRANCH_NAME}"
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh test "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
echo "[Deploy Test] done"
|
||||
}
|
||||
post {
|
||||
success {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '测试环境',
|
||||
host: env.TEST_DEPLOY_HOST,
|
||||
status: 'success',
|
||||
)
|
||||
}
|
||||
}
|
||||
failure {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '测试环境',
|
||||
host: env.TEST_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
)
|
||||
}
|
||||
}
|
||||
aborted {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '测试环境',
|
||||
host: env.TEST_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
extraNote: '阶段已中止(可能为人工取消)',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy Prod') {
|
||||
// 默认允许分支:prod、sophie。其它分支在 Job 环境变量设 EXTRA_PROD_BRANCHES=分支a,分支b
|
||||
// 临时免确认试跑:SKIP_PROD_DEPLOY_INPUT=true
|
||||
when {
|
||||
expression {
|
||||
def extra = (env.EXTRA_PROD_BRANCHES ?: '').split(',').collect { it.trim() }.findAll { it }
|
||||
def allowed = (['prod', 'sophie', 'sophie-wecom'] + extra).unique()
|
||||
allowed.contains(env.BRANCH_NAME) &&
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
def rollbackTag = env.ROLLBACK_IMAGE_TAG?.trim()
|
||||
// 临时免确认(仅无人使用的生产试跑):在 Job 环境变量设 SKIP_PROD_DEPLOY_INPUT=true;正式流程勿开启
|
||||
def skipInput = (env.SKIP_PROD_DEPLOY_INPUT ?: '').equalsIgnoreCase('true')
|
||||
if (!skipInput) {
|
||||
// 人工确认超时(分钟):超时未点「Proceed」构建将失败,避免任务永久挂在 input 上;可通过 Job 环境变量覆盖
|
||||
def inputTimeoutMin = 30
|
||||
try {
|
||||
def rawTm = (env.PROD_DEPLOY_INPUT_TIMEOUT_MINUTES ?: '30').trim()
|
||||
inputTimeoutMin = Integer.parseInt(rawTm)
|
||||
if (inputTimeoutMin <= 0) {
|
||||
inputTimeoutMin = 30
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
inputTimeoutMin = 30
|
||||
}
|
||||
echo "[Deploy Prod] 生产部署人工确认超时=${inputTimeoutMin} 分钟(环境变量 PROD_DEPLOY_INPUT_TIMEOUT_MINUTES 可覆盖)"
|
||||
def confirmMessage = rollbackTag ?
|
||||
"确认将生产回滚到镜像 tag ${rollbackTag} ?(预构建模式,不拉最新代码,不执行 db upgrade)" :
|
||||
"确认将分支 ${env.BRANCH_NAME} 部署到生产主机 ${env.PROD_DEPLOY_HOST} ?"
|
||||
timeout(time: inputTimeoutMin, unit: 'MINUTES') {
|
||||
input message: confirmMessage
|
||||
}
|
||||
} else {
|
||||
echo "[Deploy Prod] SKIP_PROD_DEPLOY_INPUT=true,已跳过人工确认"
|
||||
}
|
||||
|
||||
echo "[Deploy Prod] start branch=${env.BRANCH_NAME} host=${env.PROD_DEPLOY_HOST} rollbackTag=${rollbackTag ?: '(none)'}"
|
||||
|
||||
// 使用Jenkins中的SSH_PROD_DEPLOY私钥部署到生产服务器
|
||||
// Use SSH_PROD_DEPLOY credential to deploy to prod server
|
||||
sshagent(credentials: ['SSH_PROD_DEPLOY']) {
|
||||
if (rollbackTag) {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${PROD_SSH_USER}@${PROD_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${PROD_DEPLOY_ROOT}
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh prod "hxops-frontend:${rollbackTag}" "hxops-backend:${rollbackTag}" true true false true
|
||||
'
|
||||
"""
|
||||
} else {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${PROD_SSH_USER}@${PROD_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${PROD_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
git reset --hard HEAD
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
git reset --hard "origin/${BRANCH_NAME}"
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
GIT_COMMIT=${env.GIT_COMMIT} ./scripts/deploy_compose.sh prod "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
}
|
||||
echo "[Deploy Prod] done"
|
||||
}
|
||||
}
|
||||
post {
|
||||
success {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '生产环境',
|
||||
host: env.PROD_DEPLOY_HOST,
|
||||
status: 'success',
|
||||
)
|
||||
}
|
||||
}
|
||||
failure {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '生产环境',
|
||||
host: env.PROD_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
)
|
||||
}
|
||||
}
|
||||
aborted {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '生产环境',
|
||||
host: env.PROD_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
extraNote: '阶段已中止(可能为未确认生产部署或人工取消)',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
always {
|
||||
// 统一输出最终状态,便于回溯 / Print final flags for traceability
|
||||
echo "[Post] BRANCH_NAME=${env.BRANCH_NAME}, FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
echo "[Post] FORCE_FULL_DEPLOY_USED=${env.FORCE_FULL_DEPLOY_USED ?: 'false'}, REMOTE_DRIFT_DETECTED=${env.REMOTE_DRIFT_DETECTED ?: 'false'}, REMOTE_VERIFY_SKIPPED=${env.REMOTE_VERIFY_SKIPPED ?: 'false'}, ROLLBACK_IMAGE_TAG=${env.ROLLBACK_IMAGE_TAG ?: ''}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# hxops
|
||||
|
||||
#### 介绍
|
||||
hxops
|
||||
|
||||
#### 软件架构
|
||||
软件架构说明
|
||||
|
||||
|
||||
#### 安装教程
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 使用说明
|
||||
|
||||
1. xxxx
|
||||
2. xxxx
|
||||
3. xxxx
|
||||
|
||||
#### 参与贡献
|
||||
|
||||
1. Fork 本仓库
|
||||
2. 新建 Feat_xxx 分支
|
||||
3. 提交代码
|
||||
4. 新建 Pull Request
|
||||
|
||||
|
||||
#### 特技
|
||||
|
||||
1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
|
||||
2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com)
|
||||
3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目
|
||||
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
|
||||
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
|
||||
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
||||
## 环境配置
|
||||
|
||||
本项目依赖 Oracle Instant Client 19.30。
|
||||
|
||||
### 安装步骤:
|
||||
1. 访问 [Oracle Instant Client 下载页面](官方链接),并接受许可协议。
|
||||
2. 根据你的操作系统,下载对应的 **Basic Lite** 版本安装包。
|
||||
3. 将下载的压缩包解压到本地目录。
|
||||
4. 在项目根目录下创建名为 `oracle_client` 的文件夹,并将解压后的所有文件(`adrci.exe` 等)放入其中。
|
||||
|
||||
 *(可在此处放置一个目录结构截图,清晰地展示 `oracle_client` 文件夹的位置和内部文件)*
|
||||
@@ -0,0 +1,8 @@
|
||||
venv
|
||||
__pycache__
|
||||
*.pyc
|
||||
*.pyo
|
||||
local_test.db
|
||||
.git
|
||||
.vscode
|
||||
tests
|
||||
+64
-10
@@ -1,20 +1,74 @@
|
||||
FROM python:3.12-slim
|
||||
# syntax=docker/dockerfile:1.4
|
||||
ARG PYTHON_BASE_IMAGE=python:3.12-slim-bookworm
|
||||
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
|
||||
|
||||
# Install system dependencies
|
||||
# libpq-dev is required for psycopg2
|
||||
RUN apt-get update && apt-get install -y \
|
||||
gcc \
|
||||
libpq-dev \
|
||||
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||
--mount=type=cache,target=/var/lib/apt,sharing=locked \
|
||||
set -eux; \
|
||||
if [ -f /etc/apt/sources.list.d/debian.sources ]; then \
|
||||
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list.d/debian.sources; \
|
||||
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list.d/debian.sources; \
|
||||
fi; \
|
||||
if [ -f /etc/apt/sources.list ]; then \
|
||||
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list; \
|
||||
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list; \
|
||||
fi; \
|
||||
apt-get update && apt-get install -y --no-install-recommends \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
libxcb1 \
|
||||
libx11-6 \
|
||||
libxext6 \
|
||||
libnsl2 \
|
||||
libreoffice-nogui \
|
||||
fonts-noto-cjk \
|
||||
curl \
|
||||
ca-certificates \
|
||||
gnupg \
|
||||
unixodbc-dev \
|
||||
&& (apt-get install -y --no-install-recommends libaio1 || apt-get install -y --no-install-recommends libaio1t64) \
|
||||
&& if [ ! -e /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1 ] && [ -e /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1t64 ]; then ln -s /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1t64 /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1; fi \
|
||||
&& install -d -m 0755 /etc/apt/keyrings \
|
||||
&& curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor -o /etc/apt/keyrings/microsoft-prod.gpg \
|
||||
&& chmod a+r /etc/apt/keyrings/microsoft-prod.gpg \
|
||||
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/microsoft-prod.gpg] https://packages.microsoft.com/debian/12/prod bookworm main" > /etc/apt/sources.list.d/mssql-release.list \
|
||||
&& apt-get update \
|
||||
&& ACCEPT_EULA=Y apt-get install -y --no-install-recommends msodbcsql18 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python dependencies
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
COPY backend/requirements.txt backend/requirements-ocr.txt ./
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
set -eux; \
|
||||
PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \
|
||||
if [ -n "${PIP_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \
|
||||
fi; \
|
||||
if [ -n "${PIP_EXTRA_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --extra-index-url ${PIP_EXTRA_INDEX_URL}"; \
|
||||
fi; \
|
||||
pip install $PIP_ARGS -r requirements.txt && \
|
||||
pip install $PIP_ARGS \
|
||||
"$(grep '^opencv-python-headless' requirements-ocr.txt)" && \
|
||||
pip install $PIP_ARGS --no-deps \
|
||||
"$(grep '^rapidocr-onnxruntime' requirements-ocr.txt)" && \
|
||||
pip install $PIP_ARGS \
|
||||
pyclipper Shapely six onnxruntime && \
|
||||
python -c "import cv2; from rapidocr_onnxruntime import RapidOCR; import networkx, openpyxl"
|
||||
|
||||
# Copy backend code and the Text2SQL schema required at runtime
|
||||
COPY backend/ .
|
||||
RUN mkdir -p /app/docs
|
||||
COPY docs/(表+字段).md /app/docs/(表+字段).md
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Expose port 5000
|
||||
EXPOSE 5000
|
||||
|
||||
+189
-6
@@ -1,30 +1,64 @@
|
||||
|
||||
"""
|
||||
"""
|
||||
backend/app/__init__.py
|
||||
应用工厂
|
||||
应用工厂:创建 Flask 应用、注册蓝图并挂载全局异常与响应处理。
|
||||
"""
|
||||
from flask import Flask
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from flask import Flask, jsonify, request, g
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_cors import CORS
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from app.config import config
|
||||
from app.errors import AppError
|
||||
from app.response_utils import error_payload, utc_iso_now
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _apply_persisted_settings(app: Flask) -> None:
|
||||
"""Pull the latest runtime-editable settings into ``app.config``.
|
||||
|
||||
Reads from the database first, then ``backend/.env``. Tolerates the
|
||||
common case where the table does not yet exist (fresh deploy before
|
||||
``flask db upgrade`` runs).
|
||||
"""
|
||||
from app.env_persistence import apply_env_settings
|
||||
|
||||
try:
|
||||
applied = apply_env_settings()
|
||||
except Exception as exc: # pragma: no cover - defensive
|
||||
logger.warning('Failed to refresh persisted settings: %s', exc)
|
||||
return
|
||||
for key, value in applied.items():
|
||||
app.config[key] = value
|
||||
|
||||
|
||||
def create_app(config_name='default'):
|
||||
app = Flask(__name__)
|
||||
app.config.from_object(config[config_name])
|
||||
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
CORS(app) # 允许跨域
|
||||
CORS(app) # 允许跨域
|
||||
|
||||
# 注册 Blueprints
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.knowledge_base import knowledge_base_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.schedule_admin import schedule_admin_bp
|
||||
from app.api.workspace_schedule import workspace_schedule_bp
|
||||
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp
|
||||
from app.api.speech import speech_bp
|
||||
|
||||
# 聊天相关接口
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
@@ -32,7 +66,156 @@ def create_app(config_name='default'):
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
# 普通用户可见的 Agent 列表接口
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
# 当前用户相关接口(首页、常用问题等)
|
||||
# 当前用户相关接口(首页、常见问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
# 知识库数据清洗模块接口
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
# 知识库外部集成接口(供外部系统按 Dify 映射反查源文件)
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
# window between worker boot and the first ``before_request`` would still
|
||||
# serve the defaults baked into config.py / the image).
|
||||
with app.app_context():
|
||||
_apply_persisted_settings(app)
|
||||
from app.services.schedule.scheduler_service import start_scheduler
|
||||
start_scheduler(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
_apply_persisted_settings(app)
|
||||
incoming_request_id = (request.headers.get('X-Request-Id') or '').strip()
|
||||
g.request_id = incoming_request_id or f"req_{uuid.uuid4().hex[:16]}"
|
||||
|
||||
@app.after_request
|
||||
def _wrap_success_response(resp):
|
||||
if not bool(app.config.get('ENABLE_API_ENVELOPE', False)):
|
||||
return resp
|
||||
if not request.path.startswith('/api/'):
|
||||
return resp
|
||||
if resp.is_streamed:
|
||||
return resp
|
||||
if resp.status_code < 200 or resp.status_code >= 300:
|
||||
return resp
|
||||
if not (resp.mimetype or '').startswith('application/json'):
|
||||
return resp
|
||||
try:
|
||||
payload = resp.get_json(silent=True)
|
||||
except Exception:
|
||||
payload = None
|
||||
if isinstance(payload, dict) and 'success' in payload:
|
||||
return resp
|
||||
wrapped = {
|
||||
'success': True,
|
||||
'data': payload,
|
||||
'request_id': getattr(g, 'request_id', None),
|
||||
'timestamp': utc_iso_now(),
|
||||
}
|
||||
wrapped_resp = jsonify(wrapped)
|
||||
wrapped_resp.status_code = resp.status_code
|
||||
for key, value in resp.headers.items():
|
||||
lower = key.lower()
|
||||
if lower in ('content-length', 'content-type'):
|
||||
continue
|
||||
wrapped_resp.headers[key] = value
|
||||
return wrapped_resp
|
||||
|
||||
def _should_return_json_error() -> bool:
|
||||
if request.path.startswith('/api/'):
|
||||
return True
|
||||
accepted = request.headers.get('Accept', '')
|
||||
return 'application/json' in accepted.lower()
|
||||
|
||||
def _log_api_error(
|
||||
*,
|
||||
code: str,
|
||||
message: str,
|
||||
status: int,
|
||||
details: dict | None = None,
|
||||
exc: Exception | None = None,
|
||||
) -> None:
|
||||
request_id = getattr(g, 'request_id', None)
|
||||
log_kwargs = {
|
||||
'method': request.method,
|
||||
'path': request.path,
|
||||
'status': status,
|
||||
'code': code,
|
||||
'message': message,
|
||||
'request_id': request_id,
|
||||
'details': details or {},
|
||||
}
|
||||
log_text = (
|
||||
'API error %(method)s %(path)s status=%(status)s code=%(code)s '
|
||||
'message=%(message)s request_id=%(request_id)s details=%(details)s'
|
||||
)
|
||||
if status >= 500:
|
||||
app.logger.error(log_text, log_kwargs, exc_info=exc)
|
||||
else:
|
||||
app.logger.warning(log_text, log_kwargs)
|
||||
|
||||
@app.errorhandler(HTTPException)
|
||||
def _handle_http_exception(exc: HTTPException):
|
||||
if not _should_return_json_error():
|
||||
return exc
|
||||
message = exc.description or exc.name or 'HTTP error'
|
||||
code_num = int(exc.code or 500)
|
||||
code_map = {
|
||||
400: 'VALIDATION.INVALID_PARAM',
|
||||
401: 'AUTH.UNAUTHORIZED',
|
||||
403: 'AUTH.FORBIDDEN',
|
||||
404: 'RESOURCE.NOT_FOUND',
|
||||
409: 'RESOURCE.CONFLICT',
|
||||
429: 'SYSTEM.RATE_LIMITED',
|
||||
}
|
||||
code = code_map.get(code_num, 'SYSTEM.HTTP_ERROR')
|
||||
_log_api_error(code=code, message=str(message), status=code_num, exc=exc)
|
||||
payload = error_payload(
|
||||
code=code,
|
||||
message=str(message),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
return jsonify(payload), code_num
|
||||
|
||||
@app.errorhandler(AppError)
|
||||
def _handle_app_error(exc: AppError):
|
||||
_log_api_error(
|
||||
code=exc.code,
|
||||
message=exc.message,
|
||||
status=exc.http_status,
|
||||
details=exc.details,
|
||||
exc=exc,
|
||||
)
|
||||
payload = error_payload(
|
||||
code=exc.code,
|
||||
message=exc.message,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
details=exc.details,
|
||||
retryable=exc.retryable,
|
||||
)
|
||||
return jsonify(payload), exc.http_status
|
||||
|
||||
@app.errorhandler(Exception)
|
||||
def _handle_unexpected_exception(exc: Exception):
|
||||
_log_api_error(
|
||||
code='SYSTEM.INTERNAL_ERROR',
|
||||
message='Internal server error',
|
||||
status=500,
|
||||
exc=exc,
|
||||
)
|
||||
if not _should_return_json_error():
|
||||
return '<h1><p>Internal Server Error</p></h1>', 500
|
||||
payload = error_payload(
|
||||
code='SYSTEM.INTERNAL_ERROR',
|
||||
message='Internal server error',
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
return jsonify(payload), 500
|
||||
|
||||
return app
|
||||
+722
-385
File diff suppressed because it is too large.
Load diff
+81
-16
@@ -4,14 +4,28 @@ backend/app/api/agents.py
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
||||
"""
|
||||
from flask import Blueprint, jsonify, g
|
||||
from app.models import Agent, User
|
||||
import os
|
||||
from flask import Blueprint, jsonify, send_from_directory
|
||||
|
||||
from app import db
|
||||
from app.decorators import _get_current_user # 内部工具函数
|
||||
from app.models import Agent, User, AgentGuide
|
||||
from app.services.minio_service import minio_service
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
|
||||
def _serialize_agent_row(row) -> dict:
|
||||
return {
|
||||
'id': row.id,
|
||||
'name': row.name,
|
||||
'description': row.description,
|
||||
'icon_url': row.icon_url,
|
||||
'dify_app_type': (row.extra_config or {}).get('dify_app_type') if hasattr(row, 'extra_config') else None,
|
||||
}
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
def list_user_agents():
|
||||
"""
|
||||
@@ -23,12 +37,63 @@ def list_user_agents():
|
||||
|
||||
# 管理员:返回所有激活的 Agent
|
||||
if user.role == 'admin':
|
||||
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
|
||||
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
|
||||
agents = [a for a in user.agents if a.is_active]
|
||||
agent_rows = [
|
||||
type('AgentRow', (), {
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url,
|
||||
'extra_config': a.extra_config,
|
||||
})()
|
||||
for a in user.agents
|
||||
if a.is_active
|
||||
]
|
||||
|
||||
# 序列化为前端所需字段
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
|
||||
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
|
||||
def list_agent_guides(agent_id):
|
||||
"""
|
||||
获取指定应用的新手指南列表 (需登录)
|
||||
用途:客户端 Chat 界面点击新手指南
|
||||
"""
|
||||
_get_current_user() # 确保已登录
|
||||
|
||||
if agent_id == 0:
|
||||
generic_agent = db.session.query(Agent).filter_by(name='通用入口').first()
|
||||
if generic_agent:
|
||||
agent_id = generic_agent.id
|
||||
else:
|
||||
return jsonify([])
|
||||
|
||||
guides = (
|
||||
db.session.query(AgentGuide)
|
||||
.filter_by(agent_id=agent_id, status=1)
|
||||
.order_by(AgentGuide.sort_order.asc(), AgentGuide.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
|
||||
result = []
|
||||
for g in guides:
|
||||
result.append({
|
||||
'id': g.id,
|
||||
'file_name': g.file_name,
|
||||
'file_type': g.file_type,
|
||||
'file_url': minio_service.get_public_url(g.file_path),
|
||||
'file_size': g.file_size,
|
||||
'remark': g.remark,
|
||||
'updated_at': g.updated_at.isoformat()
|
||||
})
|
||||
return jsonify(result)
|
||||
|
||||
@agents_bp.route('/public', methods=['GET'])
|
||||
def list_public_agents():
|
||||
@@ -37,17 +102,17 @@ def list_public_agents():
|
||||
用途:登录页面展示
|
||||
"""
|
||||
# 返回所有激活的 Agent,包含基本信息
|
||||
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
|
||||
|
||||
data = [
|
||||
{
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url,
|
||||
}
|
||||
for a in agents
|
||||
]
|
||||
return jsonify(data)
|
||||
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()
|
||||
)
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
|
||||
# 为了兼容本地无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)
|
||||
|
||||
|
||||
+1649
-73
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,303 @@
|
||||
"""
|
||||
backend/app/api/integration.py
|
||||
文件用途:知识库外部集成查询接口
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from pathlib import Path
|
||||
from flask import Blueprint, abort, current_app, jsonify, request, send_file
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
|
||||
|
||||
def _integration_token_secret() -> str:
|
||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
return configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||
|
||||
|
||||
def _decode_integration_token(token: str | None) -> dict | None:
|
||||
normalized_token = str(token or '').strip()
|
||||
if not normalized_token:
|
||||
return None
|
||||
try:
|
||||
import jwt
|
||||
payload = jwt.decode(
|
||||
normalized_token,
|
||||
_integration_token_secret(),
|
||||
algorithms=['HS256'],
|
||||
)
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"Integration API token validation failed: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def _build_download_url(document_id: int, *, kind: str, version_id: int | None = None) -> str:
|
||||
base_url = _integration_base_url()
|
||||
url = f'{base_url}/api/integration/files/{document_id}/download?kind={kind}'
|
||||
if version_id is not None:
|
||||
url += f'&version_id={version_id}'
|
||||
return url
|
||||
|
||||
|
||||
def _version_query():
|
||||
return (
|
||||
db.session.query(KbDocumentVersion)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.filter(KbDocument.is_deleted.is_(False))
|
||||
)
|
||||
|
||||
|
||||
def _resolve_requested_version(file_id: int) -> tuple[KbDocumentVersion | None, KbDocument | None]:
|
||||
requested_version_id = request.args.get('version_id', type=int)
|
||||
token_payload = _decode_integration_token(request.args.get('token'))
|
||||
if isinstance(token_payload, dict):
|
||||
token_version_id = token_payload.get('version_id')
|
||||
if token_version_id is not None:
|
||||
try:
|
||||
requested_version_id = int(token_version_id)
|
||||
except (TypeError, ValueError):
|
||||
current_app.logger.warning(
|
||||
'Integration API token carried invalid version_id: %r',
|
||||
token_version_id,
|
||||
)
|
||||
dataset_id = str(token_payload.get('dataset_id') or '').strip()
|
||||
remote_document_id = str(token_payload.get('remote_document_id') or '').strip()
|
||||
if dataset_id and remote_document_id:
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document))
|
||||
.filter(
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbDocument.id == file_id,
|
||||
KbDifySyncRecord.dataset_id == dataset_id,
|
||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if record and record.document_version and record.document_version.document:
|
||||
return record.document_version, record.document_version.document
|
||||
|
||||
if requested_version_id is not None:
|
||||
version = (
|
||||
_version_query()
|
||||
.filter(
|
||||
KbDocumentVersion.id == requested_version_id,
|
||||
KbDocumentVersion.document_id == file_id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if version:
|
||||
return version, version.document
|
||||
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
if not document:
|
||||
return None, None
|
||||
return _current_version(document), document
|
||||
|
||||
def _require_integration_key():
|
||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
|
||||
if not configured:
|
||||
|
||||
raise ServiceUnavailableError('INTEGRATION_API_KEY is not configured')
|
||||
|
||||
if configured == incoming:
|
||||
return None
|
||||
|
||||
token = request.args.get('token')
|
||||
if token and _decode_integration_token(token):
|
||||
return None
|
||||
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
|
||||
def _integration_base_url() -> str:
|
||||
request_origin = IntegrationApiService._request_origin_url()
|
||||
if request_origin:
|
||||
return request_origin
|
||||
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||
if explicit:
|
||||
return explicit
|
||||
return request.host_url.rstrip('/')
|
||||
|
||||
def _kb_storage_root() -> Path:
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
def _resolve_storage_path(path_value: str | None) -> Path | None:
|
||||
if not path_value:
|
||||
return None
|
||||
raw_path = Path(str(path_value))
|
||||
candidate = (raw_path if raw_path.is_absolute() else (_kb_storage_root() / raw_path)).resolve()
|
||||
root = _kb_storage_root()
|
||||
try:
|
||||
candidate.relative_to(root)
|
||||
except ValueError:
|
||||
return None
|
||||
return candidate
|
||||
|
||||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
def _document_query():
|
||||
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
|
||||
|
||||
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
|
||||
version = version or _current_version(document)
|
||||
if not version:
|
||||
abort(404, description='No current version found.')
|
||||
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
|
||||
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||
markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None
|
||||
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
|
||||
|
||||
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
|
||||
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||
|
||||
def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: int | None=None, file_name: str | None=None) -> list[dict]:
|
||||
normalized_file_name = str(file_name or '').strip().lower()
|
||||
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||
if knowledge_base_id is not None:
|
||||
query = query.filter(KbDocument.group_id == knowledge_base_id)
|
||||
if department_id is not None:
|
||||
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
|
||||
documents = query.all()
|
||||
payload = []
|
||||
for document in documents:
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
continue
|
||||
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
|
||||
if normalized_file_name and normalized_file_name not in normalized_name and (normalized_file_name not in document.title.lower()):
|
||||
continue
|
||||
payload.append(_serialize_integration_document(document, version=version))
|
||||
return payload
|
||||
|
||||
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||||
if kind == 'source':
|
||||
path = _resolve_storage_path(version.source_file_path)
|
||||
if path is None:
|
||||
raise NotFoundError('File not found on disk.')
|
||||
filename = version.source_file_name or f'document-{version.document_id}'
|
||||
return (path, filename)
|
||||
preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path)
|
||||
if not preferred:
|
||||
abort(409, description='Markdown not ready.')
|
||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||
return (preferred, filename)
|
||||
|
||||
@integration_bp.before_request
|
||||
def _verify_integration_access():
|
||||
result = _require_integration_key()
|
||||
if result is not None:
|
||||
return result
|
||||
return None
|
||||
|
||||
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
|
||||
def get_file_detail(file_id: int):
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
if not document:
|
||||
raise NotFoundError('Document not found.')
|
||||
return jsonify(_serialize_integration_document(document))
|
||||
|
||||
@integration_bp.route('/knowledge-bases', methods=['GET'])
|
||||
def list_knowledge_bases():
|
||||
department_id = request.args.get('department_id', type=int)
|
||||
q = str(request.args.get('q') or '').strip()
|
||||
document_counts = db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count')).filter(KbDocument.is_deleted.is_(False)).group_by(KbDocument.group_id).subquery()
|
||||
query = db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count')).outerjoin(document_counts, document_counts.c.group_id == KbGroup.id).filter(KbGroup.is_active.is_(True)).order_by(KbGroup.name.asc())
|
||||
if department_id is not None:
|
||||
query = query.filter(KbGroup.department_id == department_id)
|
||||
if q:
|
||||
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
|
||||
rows = query.all()
|
||||
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
|
||||
|
||||
@integration_bp.route('/files', methods=['GET'])
|
||||
def list_files():
|
||||
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
|
||||
department_id = request.args.get('department_id', type=int)
|
||||
file_name = request.args.get('file_name')
|
||||
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, department_id=department_id, file_name=file_name)})
|
||||
|
||||
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
|
||||
def list_files_for_knowledge_base(knowledge_base_id: int):
|
||||
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, file_name=request.args.get('file_name'))})
|
||||
|
||||
@integration_bp.route('/dify-file', methods=['GET'])
|
||||
def get_file_detail_by_dify():
|
||||
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
|
||||
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
|
||||
if not remote_document_id:
|
||||
raise ValidationError('remote_document_id is required')
|
||||
record_query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id == remote_document_id).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
if dataset_id:
|
||||
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
|
||||
record = record_query.first()
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
if not document:
|
||||
raise NotFoundError('No local file mapping found for the given Dify document.')
|
||||
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
|
||||
|
||||
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
||||
def resolve_files_by_dify():
|
||||
data = request.get_json(silent=True) or {}
|
||||
items = data.get('items') if isinstance(data.get('items'), list) else []
|
||||
if not items:
|
||||
return jsonify({'data': []})
|
||||
remote_ids = sorted({str(item.get('remote_document_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()})
|
||||
dataset_ids = sorted({str(item.get('dataset_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()})
|
||||
if not remote_ids:
|
||||
return jsonify({'data': []})
|
||||
query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id.in_(remote_ids)).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
if dataset_ids:
|
||||
query = query.filter(KbDifySyncRecord.dataset_id.in_(dataset_ids) | KbDifySyncRecord.dataset_id.is_(None))
|
||||
records = query.all()
|
||||
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
|
||||
records_by_remote: dict[str, KbDifySyncRecord] = {}
|
||||
for record in records:
|
||||
key = (record.dataset_id, record.remote_document_id)
|
||||
records_by_key.setdefault(key, record)
|
||||
records_by_remote.setdefault(record.remote_document_id, record)
|
||||
payload = []
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
requested_dataset_id = str(item.get('dataset_id') or '').strip() or None
|
||||
requested_remote_document_id = str(item.get('remote_document_id') or '').strip()
|
||||
if not requested_remote_document_id:
|
||||
continue
|
||||
record = records_by_key.get((requested_dataset_id, requested_remote_document_id))
|
||||
if record is None and requested_dataset_id is None:
|
||||
record = records_by_remote.get(requested_remote_document_id)
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
payload.append({'request': {'dataset_id': requested_dataset_id, 'remote_document_id': requested_remote_document_id}, 'found': bool(document), 'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None})
|
||||
return jsonify({'data': payload})
|
||||
|
||||
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
||||
def download_file(file_id: int):
|
||||
kind = str(request.args.get('kind') or 'md').strip().lower()
|
||||
version, document = _resolve_requested_version(file_id)
|
||||
if not document:
|
||||
raise NotFoundError('Document not found.')
|
||||
if not version:
|
||||
raise NotFoundError('No version found.')
|
||||
path, filename = _resolve_download_path(version, kind)
|
||||
if not path.exists():
|
||||
raise NotFoundError('File not found on disk.')
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
@@ -0,0 +1,56 @@
|
||||
from __future__ import annotations
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, jsonify, request
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule import _run_generic_check_job
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
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 {}
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
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))
|
||||
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}'")
|
||||
run = None
|
||||
if run_no:
|
||||
run = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||
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')
|
||||
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'
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.finished_at = datetime.utcnow()
|
||||
if run.started_at and run.finished_at:
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
db.session.commit()
|
||||
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})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,477 @@
|
||||
from __future__ import annotations
|
||||
import threading
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from flask import Response
|
||||
from io import BytesIO
|
||||
import json
|
||||
from app.decorators import require_admin
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
|
||||
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no, _notify_schedule_run_wecom
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
|
||||
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)
|
||||
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:
|
||||
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
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
db.session.commit()
|
||||
import decimal, datetime as dt
|
||||
|
||||
def _safe(v):
|
||||
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})
|
||||
except Exception as e:
|
||||
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, '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')}
|
||||
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, 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']
|
||||
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(), 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.platform_api_path = f'/{task.id}'
|
||||
db.session.commit()
|
||||
db.session.refresh(task)
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
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')
|
||||
task.enabled = True
|
||||
if task.cron_expr:
|
||||
try:
|
||||
from croniter import croniter
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@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
|
||||
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)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb)
|
||||
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,143 @@
|
||||
"""
|
||||
货代发货通知 Tool API — 供 Dify Chatflow Agent 调用
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
|
||||
|
||||
def _tool_api_base_url() -> str:
|
||||
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
|
||||
return resolve_tool_api_base_url()
|
||||
|
||||
|
||||
def _dify_openapi_spec() -> dict:
|
||||
return build_dify_openapi_spec(_tool_api_base_url())
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/checkpoint-catalog", methods=["GET"])
|
||||
def checkpoint_catalog():
|
||||
"""Checkpoint ids, human_options, action_buttons — developer/docs reference (Dify approach B: do not embed)."""
|
||||
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
|
||||
|
||||
return jsonify(build_checkpoint_catalog())
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
def openapi_dify_yaml():
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
|
||||
def tool_create_task():
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
|
||||
def tool_parse_notice():
|
||||
return jsonify(shipping_tools.parse_notice(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"])
|
||||
def tool_parse_inventory():
|
||||
return jsonify(shipping_tools.parse_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
|
||||
def tool_upload_inventory_file():
|
||||
"""Multipart upload — parse server-side without sending Excel through LLM."""
|
||||
task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip()
|
||||
upload = request.files.get("file")
|
||||
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
|
||||
def tool_get_inventory_schema_preview():
|
||||
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"])
|
||||
def tool_apply_inventory_mapping():
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
|
||||
def tool_ensure_inventory():
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
|
||||
def tool_auto_progress():
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
|
||||
def tool_match_inventory():
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"])
|
||||
def tool_submit_decision():
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"])
|
||||
def tool_generate_shipment_excel():
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
|
||||
def tool_upload_to_freight():
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
|
||||
def tool_get_task_status():
|
||||
return jsonify(shipping_tools.get_task_status(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
|
||||
def rpa_inventory_ready():
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"])
|
||||
def rpa_upload_complete():
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
|
||||
def download_task_export(task_no: str):
|
||||
from app.services.shipping_notice.tools import _get_task
|
||||
|
||||
task = _get_task(task_no)
|
||||
if not task or not task.export_file_path:
|
||||
return jsonify({"error": "export file not found"}), 404
|
||||
path = Path(task.export_file_path)
|
||||
if not path.is_file():
|
||||
return jsonify({"error": "export file missing on disk"}), 404
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=task.export_file_name or path.name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
Speech transcription API — forwards audio to SiliconFlow ASR.
|
||||
"""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||
from app.services.speech_asr import SpeechAsrService
|
||||
|
||||
speech_bp = Blueprint('speech', __name__)
|
||||
|
||||
|
||||
@speech_bp.route('/transcribe', methods=['POST'])
|
||||
def transcribe_audio():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
uploaded = request.files.get('audio') or request.files.get('file')
|
||||
if not uploaded or not uploaded.filename:
|
||||
raise ValidationError('audio file is required')
|
||||
|
||||
audio_bytes = uploaded.read()
|
||||
filename = uploaded.filename or 'recording.webm'
|
||||
content_type = uploaded.content_type or ''
|
||||
|
||||
try:
|
||||
SpeechAsrService.validate_upload(filename, len(audio_bytes))
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc)) from exc
|
||||
|
||||
try:
|
||||
text, model = SpeechAsrService.transcribe(audio_bytes, filename, content_type)
|
||||
except RuntimeError as exc:
|
||||
raise ServiceUnavailableError(str(exc)) from exc
|
||||
|
||||
return jsonify({
|
||||
'text': text,
|
||||
'model': model,
|
||||
})
|
||||
+1356
-385
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,49 @@
|
||||
from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
workspace_schedule_bp = Blueprint('workspace_schedule', __name__)
|
||||
|
||||
def _require_user():
|
||||
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) if started_after_str else None
|
||||
started_before = datetime.fromisoformat(started_before_str) 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')
|
||||
@@ -0,0 +1,323 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_for_user,
|
||||
list_tasks_for_user,
|
||||
serialize_task_detail,
|
||||
)
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return None, (jsonify({"error": "Unauthorized"}), 401)
|
||||
return user, None
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
|
||||
def workspace_shipping_tasks():
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
process_status = str(request.args.get("process_status") or "").strip() or None
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(list_tasks_for_user(user.id, process_status=process_status, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
|
||||
def workspace_create_shipping_task():
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {"user_id": user.id}
|
||||
source_type = str(data.get("source_type") or "").strip()
|
||||
if source_type:
|
||||
payload["source_type"] = source_type
|
||||
conversation_id = str(data.get("conversation_id") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
raw_content = str(data.get("raw_content") or "").strip()
|
||||
if raw_content:
|
||||
payload["raw_content"] = raw_content
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.create_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
|
||||
upload = request.files.get("file")
|
||||
if not upload:
|
||||
return jsonify({"error": "file is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
extract_notice_text,
|
||||
guess_source_type,
|
||||
max_notice_chars,
|
||||
save_task_notice_upload,
|
||||
)
|
||||
|
||||
source_type = guess_source_type(upload.filename or "")
|
||||
created = shipping_tools.create_task({"user_id": user.id, "source_type": source_type})
|
||||
task_id = str(created.get("task_id") or "").strip()
|
||||
if not task_id:
|
||||
return jsonify({"error": "failed to create task"}), 500
|
||||
|
||||
raw = upload.read() or b""
|
||||
saved_path = save_task_notice_upload(task_id, upload.filename or "notice", raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
if not text:
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"status": "needs_human",
|
||||
"task_id": task_id,
|
||||
"message": "未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。",
|
||||
"data": {"notice_upload": {"filename": upload.filename or "", **meta}},
|
||||
"human_options": ["reparse", "reject"],
|
||||
"checkpoint": CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
"action_buttons": action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED),
|
||||
}
|
||||
)
|
||||
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
meta.setdefault("warnings", []).append(f"notice_text_truncated:{limit}")
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = text
|
||||
db.session.commit()
|
||||
|
||||
payload = {"task_id": task_id}
|
||||
parsed = shipping_tools.parse_notice(payload)
|
||||
data = parsed.get("data") if isinstance(parsed, dict) else None
|
||||
if isinstance(data, dict):
|
||||
data["notice_upload"] = {"filename": upload.filename or "", **meta}
|
||||
parsed["message"] = f"已上传发货通知文件并创建任务 {task_id}。{parsed.get('message') or ''}".strip()
|
||||
return jsonify(parsed)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>", methods=["GET"])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(serialize_task_detail(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/chat-actions", methods=["GET"])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/upload-inventory", methods=["POST"])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""Hxops chat UI: upload inventory Excel with user auth (not Tool Key)."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
upload = request.files.get("file")
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/apply-inventory-mapping", methods=["POST"])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
map_json = data.get(MAP_JSON)
|
||||
if not isinstance(map_json, dict) or not map_json:
|
||||
return jsonify({"error": f"{MAP_JSON} is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/submit-decision", methods=["POST"])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""Hxops chat UI: submit shipping decision with user auth (bypass Dify tool routing)."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get("decision") or "").strip()
|
||||
if not decision:
|
||||
return jsonify({"error": "decision is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "decision": decision, AUTO_CHAIN_FALLBACK: True}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.submit_decision(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/auto-progress", methods=["POST"])
|
||||
def workspace_auto_progress_shipping_task(task_no: str):
|
||||
"""Hxops chat fallback: same as Dify auto_progress tool."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
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):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
human_options_for_checkpoint,
|
||||
)
|
||||
|
||||
matched = shipping_tools.match_inventory({"task_id": task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
data = matched.get("data")
|
||||
if isinstance(data, dict) and data.get("export_file_path"):
|
||||
matched = {
|
||||
**matched,
|
||||
"data": {**data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"},
|
||||
}
|
||||
checkpoint = matched.get("checkpoint") or CP_EXPORT_GENERATED
|
||||
if matched.get("status") == "ok" and data and data.get("export_file_path"):
|
||||
matched["checkpoint"] = checkpoint
|
||||
if "human_options" not in matched:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
if options is not None:
|
||||
matched["human_options"] = options
|
||||
if "action_buttons" not in matched:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched["action_buttons"] = buttons
|
||||
return jsonify(matched)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""Hxops chat: mark freight manual upload complete (no ref no required)."""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(
|
||||
shipping_tools.upload_to_freight({"task_id": task.task_no, "mode": "manual_confirm"})
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
result = shipping_tools.generate_excel({"task_id": task.task_no})
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
data = result.get("data")
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result["data"] = data
|
||||
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task or not task.export_file_path:
|
||||
return jsonify({"error": "export file not found"}), 404
|
||||
path = Path(task.export_file_path)
|
||||
if not path.is_file():
|
||||
return jsonify({"error": "export file missing on disk"}), 404
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=task.export_file_name or path.name,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -0,0 +1,287 @@
|
||||
import time
|
||||
import json
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
|
||||
import jwt
|
||||
import requests
|
||||
from flask import current_app, g, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
|
||||
_JWKS_CACHE: dict[str, Any] = {
|
||||
'url': None,
|
||||
'keys': None,
|
||||
'expires_at': 0.0,
|
||||
}
|
||||
|
||||
def _token_brief(token: Optional[str]) -> str:
|
||||
if not token:
|
||||
return 'empty'
|
||||
text = str(token)
|
||||
if len(text) <= 16:
|
||||
return f'len={len(text)}:{text}'
|
||||
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||||
|
||||
|
||||
def _extract_bearer_token() -> Optional[str]:
|
||||
# Only trust standard Bearer token; reject all non-Bearer auth schemes.
|
||||
auth = request.headers.get('Authorization', '')
|
||||
if not auth:
|
||||
return None
|
||||
parts = auth.split(' ', 1)
|
||||
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||
return None
|
||||
token = parts[1].strip()
|
||||
return token or None
|
||||
|
||||
|
||||
def _get_jwks_keys(jwks_url: str) -> dict:
|
||||
# Keep a short in-memory JWKS cache to avoid hitting Casdoor for every request.
|
||||
now = time.time()
|
||||
if (
|
||||
_JWKS_CACHE.get('url') == jwks_url
|
||||
and isinstance(_JWKS_CACHE.get('keys'), dict)
|
||||
and now < float(_JWKS_CACHE.get('expires_at') or 0.0)
|
||||
):
|
||||
return _JWKS_CACHE['keys']
|
||||
|
||||
resp = requests.get(jwks_url, timeout=5)
|
||||
resp.raise_for_status()
|
||||
data = resp.json() or {}
|
||||
keys = {}
|
||||
for item in data.get('keys', []):
|
||||
kid = item.get('kid')
|
||||
if kid:
|
||||
keys[kid] = item
|
||||
if not keys:
|
||||
raise ValueError('No JWKS keys found')
|
||||
|
||||
_JWKS_CACHE['url'] = jwks_url
|
||||
_JWKS_CACHE['keys'] = keys
|
||||
_JWKS_CACHE['expires_at'] = now + 300
|
||||
return keys
|
||||
|
||||
|
||||
def _decode_jwt(token: str) -> dict:
|
||||
# Strictly validate iss/aud/exp/iat against Casdoor metadata-derived settings.
|
||||
issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
jwks_url = (current_app.config.get('AUTH_JWT_JWKS_URL') or '').strip()
|
||||
if not issuer or not audience or not jwks_url:
|
||||
raise ValueError('JWT auth is not fully configured')
|
||||
|
||||
header = jwt.get_unverified_header(token)
|
||||
kid = header.get('kid')
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode start kid=%s alg=%s token=%s',
|
||||
kid,
|
||||
header.get('alg'),
|
||||
_token_brief(token),
|
||||
)
|
||||
if not kid:
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
|
||||
raise ValueError('JWT header missing kid')
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
if not secret:
|
||||
raise ValueError('Local JWT secret is missing')
|
||||
local_issuer = (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend').strip()
|
||||
local_audience = (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend').strip()
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=secret,
|
||||
algorithms=['HS256'],
|
||||
audience=local_audience,
|
||||
issuer=local_issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
# stale cache fallback
|
||||
_JWKS_CACHE['expires_at'] = 0.0
|
||||
keys = _get_jwks_keys(jwks_url)
|
||||
jwk = keys.get(kid)
|
||||
if not jwk:
|
||||
raise ValueError('No matching JWKS key for token')
|
||||
|
||||
# Different jwt packages/versions expose JWK->public-key helpers differently.
|
||||
# Try multiple compatible paths to avoid hard dependency on one symbol name.
|
||||
public_key = None
|
||||
pyjwk = getattr(jwt, 'PyJWK', None)
|
||||
if pyjwk and hasattr(pyjwk, 'from_dict'):
|
||||
public_key = pyjwk.from_dict(jwk).key
|
||||
if public_key is None:
|
||||
rsa_alg = getattr(getattr(jwt, 'algorithms', None), 'RSAAlgorithm', None)
|
||||
if rsa_alg and hasattr(rsa_alg, 'from_jwk'):
|
||||
public_key = rsa_alg.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
get_algs = getattr(getattr(jwt, 'algorithms', None), 'get_default_algorithms', None)
|
||||
if callable(get_algs):
|
||||
rs256 = (get_algs() or {}).get('RS256')
|
||||
if rs256 and hasattr(rs256, 'from_jwk'):
|
||||
public_key = rs256.from_jwk(json.dumps(jwk))
|
||||
if public_key is None:
|
||||
raise ValueError('Cannot build RSA public key from JWK; check installed jwt package')
|
||||
|
||||
return jwt.decode(
|
||||
token,
|
||||
key=public_key,
|
||||
algorithms=['RS256', 'RS384', 'RS512'],
|
||||
audience=audience,
|
||||
issuer=issuer,
|
||||
options={'require': ['exp', 'iat']},
|
||||
)
|
||||
|
||||
|
||||
def _extract_unverified_claims(token: str) -> dict:
|
||||
"""Best-effort decode without signature verification for troubleshooting logs."""
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
options={
|
||||
'verify_signature': False,
|
||||
'verify_exp': False,
|
||||
'verify_iat': False,
|
||||
'verify_nbf': False,
|
||||
'verify_aud': False,
|
||||
'verify_iss': False,
|
||||
},
|
||||
) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||
# Resolution order keeps compatibility with different token claim conventions.
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = claims.get('user_id') or claims.get('id')
|
||||
if user_id is not None:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||
if username:
|
||||
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||
if user:
|
||||
return user
|
||||
|
||||
email = claims.get('email')
|
||||
if email:
|
||||
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||
if user:
|
||||
return user
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _legacy_header_user() -> Optional[User]:
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if user_id:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = request.headers.get('X-Username')
|
||||
if username:
|
||||
return db.session.query(User).filter_by(username=username).first()
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def get_current_user() -> Optional[User]:
|
||||
cached = getattr(g, 'current_user', None)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
token = _extract_bearer_token()
|
||||
if token:
|
||||
try:
|
||||
claims = _decode_jwt(token)
|
||||
user = _resolve_user_from_claims(claims)
|
||||
current_app.logger.info(
|
||||
'[auth_jwt] decode ok sub=%s username=%s resolved_user=%s',
|
||||
claims.get('sub'),
|
||||
claims.get('preferred_username') or claims.get('username') or claims.get('name'),
|
||||
getattr(user, 'username', None),
|
||||
)
|
||||
except Exception:
|
||||
# Any decode/lookup failure should behave as unauthenticated.
|
||||
unverified = _extract_unverified_claims(token)
|
||||
expected_issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||
expected_audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||
current_app.logger.error(
|
||||
'[auth_jwt] decode context token_iss=%s token_aud=%s expected_iss=%s expected_aud=%s',
|
||||
unverified.get('iss'),
|
||||
unverified.get('aud'),
|
||||
expected_issuer,
|
||||
expected_audience,
|
||||
)
|
||||
current_app.logger.exception('[auth_jwt] decode failed token=%s path=%s', _token_brief(token), request.path)
|
||||
user = None
|
||||
claims = None
|
||||
if user:
|
||||
g.jwt_claims = claims
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||
user = _legacy_header_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def issue_local_access_token(user: User) -> str:
|
||||
"""Issue local HS256 JWT for password-login flow compatibility."""
|
||||
now = datetime.now(timezone.utc)
|
||||
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
|
||||
payload = {
|
||||
'sub': str(user.id),
|
||||
'id': user.id,
|
||||
'user_id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'email': user.email,
|
||||
'iat': int(now.timestamp()),
|
||||
'exp': int((now + timedelta(hours=max(1, exp_hours))).timestamp()),
|
||||
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
|
||||
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
|
||||
}
|
||||
secret = current_app.config.get('SECRET_KEY')
|
||||
return jwt.encode(payload, secret, algorithm='HS256')
|
||||
+229
-20
@@ -1,32 +1,167 @@
|
||||
|
||||
"""
|
||||
backend/app/config.py
|
||||
配置类,区分开发/生产环境
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _load_environment_files() -> str:
|
||||
"""Load env files from project root with stable priority.
|
||||
|
||||
Priority (low -> high):
|
||||
1. .env.shared
|
||||
2. .env.<ENV_NAME>
|
||||
3. .env.local (only for dev)
|
||||
4. system environment variables (always highest, never overridden)
|
||||
"""
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
shared_file = _ROOT_DIR / '.env.shared'
|
||||
if shared_file.exists():
|
||||
load_dotenv(shared_file, override=False)
|
||||
|
||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||
if env_file.exists():
|
||||
load_dotenv(env_file, override=True)
|
||||
|
||||
if env_name == 'dev':
|
||||
local_file = _ROOT_DIR / '.env.local'
|
||||
if local_file.exists():
|
||||
load_dotenv(local_file, override=True)
|
||||
return env_name
|
||||
|
||||
|
||||
ACTIVE_ENV_NAME = _load_environment_files()
|
||||
|
||||
|
||||
def _data_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath("data", *parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
def _backend_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath(*parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key')
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
|
||||
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
'max_overflow': 10,
|
||||
'pool_recycle': 3600,
|
||||
'pool_pre_ping': True
|
||||
'pool_pre_ping': True,
|
||||
}
|
||||
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE', 'https://api.dify.ai/v1')
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL', 'redis://:difyai123456@localhost:6379/0')
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv(
|
||||
'HR_WORKFLOW_IFRAME_URL',
|
||||
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'
|
||||
)
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE', 'http://127.0.0.1:5001/v1')
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||
'OA_WORKFLOW_WSDL_URL',
|
||||
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
# OpenAPI servers.url 基地址(Dify 调 Tool 时访问 hxops,不是 Dify 的 8882)
|
||||
SHIPPING_NOTICE_TOOL_API_BASE = os.getenv('SHIPPING_NOTICE_TOOL_API_BASE')
|
||||
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'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
|
||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||
'shipment_{task_no}_{ts}.xlsx',
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path("FREIGHT_INVENTORY_DROP_DIR", "freight_rpa", "inventory_drop")
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "freight_rpa", "inventory_triggers"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path("FREIGHT_UPLOAD_QUEUE_DIR", "freight_rpa", "upload_queue")
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "freight_rpa", "upload_triggers"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
)
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||
@@ -34,30 +169,104 @@ class Config:
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
AUTH_JWT_REQUIRED = os.getenv('AUTH_JWT_REQUIRED', 'true').lower() == 'true'
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN = os.getenv('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', 'true').lower() == 'true'
|
||||
# Login mode switch: "casdoor" (default) or "password".
|
||||
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
|
||||
# password: keep legacy local username/password login.
|
||||
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
|
||||
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
|
||||
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
|
||||
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
|
||||
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE')
|
||||
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL')
|
||||
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
|
||||
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
|
||||
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
|
||||
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
|
||||
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
|
||||
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||
# Casdoor organization (userOwner) for set-password and other management APIs.
|
||||
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
|
||||
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
|
||||
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||
SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '')
|
||||
SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '')
|
||||
SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server')
|
||||
SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no')
|
||||
SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes')
|
||||
SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15'))
|
||||
SMTP_HOST = os.getenv('SMTP_HOST', '')
|
||||
SMTP_PORT = int(os.getenv('SMTP_PORT', '25'))
|
||||
SMTP_USER = os.getenv('SMTP_USER', '')
|
||||
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||
|
||||
# MinIO 配置
|
||||
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
|
||||
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
|
||||
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
|
||||
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
# 本地 MacBook PostgreSQL 配置(数据库: hxops_db,用户: postgres, 密码: difyai123456)
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||
'DATABASE_URL',
|
||||
'postgresql://postgres:difyai123456@localhost:5432/hxops_db'
|
||||
)
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
# 服务器 Ubuntu PostgreSQL 配置
|
||||
# 注意:在服务器上通过环境变量覆盖,但此处保留默认模板
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'postgresql://postgres:difyai123456@localhost:5432/hxops_prod')
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
|
||||
|
||||
config = {
|
||||
'dev': DevelopmentConfig,
|
||||
'development': DevelopmentConfig,
|
||||
'testing': TestingConfig,
|
||||
'test': TestingConfig,
|
||||
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
||||
'prod': ProductionConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
+18
-84
@@ -1,4 +1,3 @@
|
||||
|
||||
"""
|
||||
backend/app/decorators.py
|
||||
文件用途:权限控制装饰器集合
|
||||
@@ -6,67 +5,18 @@ backend/app/decorators.py
|
||||
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
||||
"""
|
||||
from functools import wraps
|
||||
from flask import request, jsonify, g
|
||||
from app import db
|
||||
from flask import request, jsonify, g, current_app
|
||||
from app.models import Agent, User
|
||||
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""
|
||||
内部工具函数:获取当前登录用户
|
||||
支持从请求头识别用户并创建用户,读取 X-User-Id / X-Username / X-Role。
|
||||
"""
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
username = request.headers.get('X-Username')
|
||||
role = request.headers.get('X-Role', 'user')
|
||||
|
||||
user = None
|
||||
if user_id:
|
||||
try:
|
||||
user = User.query.get(int(user_id))
|
||||
except ValueError:
|
||||
user = None
|
||||
if user is None and username:
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if not user:
|
||||
if user_id:
|
||||
safe_id = int(user_id)
|
||||
user = User(
|
||||
id=safe_id,
|
||||
username=username or f'user_{safe_id}',
|
||||
email=f'{username or f"user_{safe_id}"}@example.com',
|
||||
department='IT',
|
||||
role=role,
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
elif username:
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
department='IT',
|
||||
role=role,
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
else:
|
||||
# Check if guest user exists
|
||||
user = User.query.filter_by(username='guest').first()
|
||||
if not user:
|
||||
user = User(
|
||||
username='guest',
|
||||
email='guest@example.com',
|
||||
department='',
|
||||
role='guest',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
g.current_user = user
|
||||
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
|
||||
user = _auth_current_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
||||
@@ -83,40 +33,24 @@ def require_agent_permission(f):
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# 从 JSON 请求体中解析数据
|
||||
data = request.get_json(silent=True) or {}
|
||||
# 获取 agent_id (优先从 Body,其次从 Query)
|
||||
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
||||
|
||||
# 如果未提供 agent_id,则返回 400 错误
|
||||
if not agent_id:
|
||||
return jsonify({'error': 'agent_id is required'}), 400
|
||||
|
||||
# 获取当前用户(此处固定为 admin 用户,用于演示)
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
|
||||
# 查询目标 Agent 是否存在
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
return jsonify({'error': 'Agent not found'}), 404
|
||||
|
||||
# 将 agent 对象挂在 g 上,方便下游使用
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
|
||||
# 如果用户是管理员,跳过权限检查直接放行
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
|
||||
# 非管理员:检查多对多关联表中是否存在权限
|
||||
if agent not in user.agents:
|
||||
return jsonify({'error': 'Permission denied for this agent'}), 403
|
||||
|
||||
# 鉴权通过,调用原始视图函数
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制只有管理员角色才能访问的接口
|
||||
@@ -127,12 +61,12 @@ def require_admin(f):
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# 获取当前用户(自动创建 admin)
|
||||
user = _get_current_user()
|
||||
# 如果不是管理员,则返回 403
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||
raise UnauthorizedError('JWT token is required')
|
||||
if user.role != 'admin':
|
||||
return jsonify({'error': 'Admin privilege required'}), 403
|
||||
# 是管理员则放行
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated_function
|
||||
return decorated_function
|
||||
@@ -0,0 +1,254 @@
|
||||
"""Persistent storage for runtime-editable application settings.
|
||||
|
||||
Settings managed from the admin console (e.g. WeCom configuration) need to
|
||||
survive process restarts AND container/image rebuilds in production. Writing
|
||||
only to ``backend/.env`` is not enough on Docker deployments because the
|
||||
container's writable layer is discarded on every ``docker compose up --build``.
|
||||
|
||||
Storage strategy:
|
||||
|
||||
1. Database (``app_settings`` table) - canonical, always authoritative.
|
||||
2. ``.env.local`` (dev only) - best-effort secondary write so local/dev
|
||||
workflows that restart without DB access still see updates.
|
||||
3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay
|
||||
in sync within the running process.
|
||||
|
||||
On read we merge env files (lowest priority) over DB (highest priority); the DB
|
||||
value wins whenever it exists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from dotenv import dotenv_values, set_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
# Backward-compatible alias for tests and older callers that still patch/read
|
||||
# the historical backend/.env location directly.
|
||||
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not ROOT_ENV_LOCAL_PATH.exists():
|
||||
ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_env_value(key: str, value: object) -> object:
|
||||
if value is None:
|
||||
return None
|
||||
if key in WECOM_BOOL_KEYS:
|
||||
return str(value).strip().lower() == 'true'
|
||||
return str(value)
|
||||
|
||||
|
||||
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
"""Write key/value pairs into the ``app_settings`` table.
|
||||
|
||||
Returns True if every value was committed, False otherwise. The function
|
||||
is defensive: it must not raise, because settings persistence is also
|
||||
written to ``.env`` and we don't want to fail the API request.
|
||||
"""
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
return False
|
||||
|
||||
try:
|
||||
for key, value in values.items():
|
||||
existing = db.session.get(AppSetting, key)
|
||||
if existing is None:
|
||||
db.session.add(AppSetting(key=key, value=value))
|
||||
else:
|
||||
existing.value = value
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
logger.debug('app_settings table not readable yet: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
if row.key and _matches_prefixes(row.key, prefixes):
|
||||
result[row.key] = row.value if row.value is not None else ''
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env read/write (secondary store, best-effort)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
if env_name != 'dev':
|
||||
return True
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
return False
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
merged: dict[str, str] = {}
|
||||
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
if not env_path.exists():
|
||||
continue
|
||||
try:
|
||||
loaded = dotenv_values(env_path)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', env_path, exc)
|
||||
continue
|
||||
for key, value in loaded.items():
|
||||
if key and _matches_prefixes(key, prefixes):
|
||||
merged[key] = value if value is not None else ''
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
|
||||
persisted: dict[str, str] = {}
|
||||
for key, value in values.items():
|
||||
env_value = _to_env_string(value)
|
||||
os.environ[key] = env_value
|
||||
persisted[key] = env_value
|
||||
|
||||
db_ok = _persist_to_db(persisted)
|
||||
file_ok = _persist_to_env_file(persisted)
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env.local mirror. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
backend/app/errors.py
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
说明:
|
||||
1. AppError 作为基础异常,包含 code/message/http_status/details/retryable。
|
||||
2. 各子类用于表达常见语义(参数错误、未授权、无权限、资源不存在)。
|
||||
3. 业务层可直接 raise 这些异常,避免到处手写 jsonify(error)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class AppError(Exception):
|
||||
code: str
|
||||
message: str
|
||||
http_status: int = 400
|
||||
details: dict[str, Any] = field(default_factory=dict)
|
||||
retryable: bool = False
|
||||
|
||||
|
||||
class ValidationError(AppError):
|
||||
def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None):
|
||||
super().__init__(
|
||||
code="VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=400,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class UnauthorizedError(AppError):
|
||||
def __init__(self, message: str = "Unauthorized"):
|
||||
super().__init__(code="AUTH.UNAUTHORIZED", message=message, http_status=401, retryable=False)
|
||||
|
||||
|
||||
class ForbiddenError(AppError):
|
||||
def __init__(self, message: str = "Forbidden"):
|
||||
super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False)
|
||||
|
||||
|
||||
class NotFoundError(AppError):
|
||||
def __init__(self, message: str = "Resource not found"):
|
||||
super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False)
|
||||
|
||||
|
||||
class ConflictError(AppError):
|
||||
def __init__(
|
||||
self,
|
||||
message: str = "Resource conflict",
|
||||
*,
|
||||
code: str = "RESOURCE.CONFLICT",
|
||||
details: dict[str, Any] | None = None,
|
||||
):
|
||||
super().__init__(
|
||||
code=code,
|
||||
message=message,
|
||||
http_status=409,
|
||||
details=details or {},
|
||||
retryable=False,
|
||||
)
|
||||
|
||||
|
||||
class ServiceUnavailableError(AppError):
|
||||
def __init__(self, message: str = "Service unavailable", *, code: str = "SYSTEM.SERVICE_UNAVAILABLE"):
|
||||
super().__init__(code=code, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
def raise_for_status(message: str, status: int, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
|
||||
if status == 401:
|
||||
raise UnauthorizedError(message)
|
||||
if status == 403:
|
||||
raise ForbiddenError(message)
|
||||
if status == 404:
|
||||
raise NotFoundError(message)
|
||||
if status == 409:
|
||||
raise ConflictError(message, code=code or "RESOURCE.CONFLICT", details=details)
|
||||
if status == 503:
|
||||
raise ServiceUnavailableError(message, code=code or "SYSTEM.SERVICE_UNAVAILABLE")
|
||||
if status >= 500:
|
||||
raise AppError(
|
||||
code=code or "SYSTEM.INTERNAL_ERROR",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
raise AppError(
|
||||
code=code or "VALIDATION.INVALID_PARAM",
|
||||
message=message,
|
||||
http_status=status,
|
||||
details=details or {},
|
||||
)
|
||||
+506
-2
@@ -1,7 +1,6 @@
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
|
||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, Float, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app import db
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
@@ -179,6 +178,27 @@ class Agent(Base):
|
||||
back_populates="agents"
|
||||
)
|
||||
|
||||
class ChatSession(Base):
|
||||
"""
|
||||
聊天会话表
|
||||
用途:独立持久化会话元数据,使生成中会话也能立即出现在历史记录中
|
||||
"""
|
||||
__tablename__ = 'chat_sessions'
|
||||
__table_args__ = (
|
||||
Index('ix_chat_sessions_user_agent_last_active', 'user_id', 'agent_id', 'last_active_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
session_id: Mapped[str] = mapped_column(String(100), unique=True, index=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255), default='')
|
||||
status: Mapped[str] = mapped_column(String(20), default='running')
|
||||
external_conversation_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
last_active_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
class ChatLog(Base):
|
||||
"""
|
||||
对话日志表
|
||||
@@ -193,7 +213,13 @@ class ChatLog(Base):
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
latency: Mapped[int] = mapped_column(default=0)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
session_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||
# Persist citation/source metadata so history messages can still show sources.
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
attribution_parts: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
# 关联 Feedback
|
||||
@@ -214,6 +240,23 @@ class Feedback(Base):
|
||||
|
||||
chat_log: Mapped["ChatLog"] = relationship(back_populates="feedback")
|
||||
|
||||
class GeneralFeedback(Base):
|
||||
"""
|
||||
通用意见反馈表
|
||||
用于存储 Workspace/Chat 页面提交的通用意见反馈
|
||||
"""
|
||||
__tablename__ = 'general_feedbacks'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
chat_log_id: Mapped[Optional[int]] = mapped_column(ForeignKey('chat_logs.id'), nullable=True, index=True)
|
||||
username: Mapped[str] = mapped_column(String(50), nullable=False)
|
||||
feedback_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
feedback_module: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
source_page: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
class PermissionRequest(Base):
|
||||
"""
|
||||
权限申请表
|
||||
@@ -271,7 +314,468 @@ class LoginAudit(Base):
|
||||
source: Mapped[str] = mapped_column(String(20), default='password') # password / wecom
|
||||
status: Mapped[str] = mapped_column(String(20), default='success') # success / failed
|
||||
reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
match_rules: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
match_operator: Mapped[Optional[str]] = mapped_column(String(8), nullable=True)
|
||||
match_result: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ip: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
user_agent: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class WecomNotifyAudit(Base):
|
||||
"""
|
||||
企业微信触达审计表
|
||||
用途:记录企微消息发送结果与回流点击数据
|
||||
"""
|
||||
__tablename__ = 'wecom_notify_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
status: Mapped[str] = mapped_column(String(20), default='sent', index=True) # sent / failed
|
||||
trace_id: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
|
||||
username: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
wecom_userid: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
title: Mapped[Optional[str]] = mapped_column(String(120), nullable=True)
|
||||
content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
jump_url: Mapped[Optional[str]] = mapped_column(String(512), nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
opened_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True, index=True)
|
||||
|
||||
|
||||
class AppSetting(Base):
|
||||
"""
|
||||
应用运行时配置表(Key/Value)
|
||||
用途:将企业微信等管理员可编辑的配置长效保存到数据库,
|
||||
避免容器/部署重建后写入 backend/.env 的修改丢失。
|
||||
"""
|
||||
__tablename__ = 'app_settings'
|
||||
|
||||
key: Mapped[str] = mapped_column(String(128), primary_key=True)
|
||||
value: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
|
||||
)
|
||||
|
||||
|
||||
class KbGroup(Base):
|
||||
"""
|
||||
知识库分组
|
||||
用途:承载数据清洗/知识库管理模块中的分组/知识库
|
||||
"""
|
||||
__tablename__ = 'kb_groups'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('department_id', 'name', name='uq_kb_groups_department_name'),
|
||||
Index('ix_kb_groups_department_active', 'department_id', 'is_active'),
|
||||
Index('ix_kb_groups_dify_dataset_id', 'dify_dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
department_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
dify_dataset_id: Mapped[Optional[str]] = mapped_column(String(128))
|
||||
dify_dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
|
||||
documents: Mapped[List["KbDocument"]] = relationship(
|
||||
"KbDocument",
|
||||
back_populates="group",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
|
||||
class KbDocument(Base):
|
||||
"""
|
||||
知识库逻辑文档
|
||||
用途:表示一个文档条目,不直接等同于某一次上传文件
|
||||
"""
|
||||
__tablename__ = 'kb_documents'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('group_id', 'title', name='uq_kb_documents_group_title'),
|
||||
Index('ix_kb_documents_group_status', 'group_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[int] = mapped_column(ForeignKey('kb_groups.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(32), default='draft', index=True)
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
group: Mapped["KbGroup"] = relationship("KbGroup", back_populates="documents")
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
|
||||
versions: Mapped[List["KbDocumentVersion"]] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="document",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="desc(KbDocumentVersion.version_no)",
|
||||
)
|
||||
|
||||
|
||||
class KbDocumentVersion(Base):
|
||||
"""
|
||||
知识库文档版本
|
||||
用途:记录每次上传、清洗、同步产生的版本信息
|
||||
"""
|
||||
__tablename__ = 'kb_document_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('document_id', 'version_no', name='uq_kb_document_versions_doc_version'),
|
||||
Index('ix_kb_document_versions_doc_status', 'document_id', 'status'),
|
||||
Index('ix_kb_document_versions_sha256', 'sha256'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('kb_documents.id'), index=True)
|
||||
version_no: Mapped[int] = mapped_column(Integer)
|
||||
status: Mapped[str] = mapped_column(String(32), default='uploaded', index=True)
|
||||
is_current: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
source_file_name: Mapped[str] = mapped_column(String(255))
|
||||
source_file_path: Mapped[str] = mapped_column(Text)
|
||||
source_file_ext: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
source_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
cleaned_file_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
cleaned_preview_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
sha256: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
word_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
warnings_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
uploaded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
converted_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
document: Mapped["KbDocument"] = relationship("KbDocument", back_populates="versions")
|
||||
uploaded_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[uploaded_by_id])
|
||||
jobs: Mapped[List["KbJob"]] = relationship(
|
||||
"KbJob",
|
||||
back_populates="document_version",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
sync_records: Mapped[List["KbDifySyncRecord"]] = relationship(
|
||||
"KbDifySyncRecord",
|
||||
back_populates="document_version",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="desc(KbDifySyncRecord.updated_at)",
|
||||
)
|
||||
|
||||
|
||||
class KbJob(Base):
|
||||
"""
|
||||
知识库后台任务
|
||||
用途:记录上传、清洗、同步等后台任务执行情况
|
||||
"""
|
||||
__tablename__ = 'kb_jobs'
|
||||
__table_args__ = (
|
||||
Index('ix_kb_jobs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
job_type: Mapped[str] = mapped_column(String(32), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
queue_job_id: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
progress: Mapped[int] = mapped_column(Integer, default=0)
|
||||
message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
payload_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
result_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
document_version: Mapped[Optional["KbDocumentVersion"]] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="jobs",
|
||||
)
|
||||
|
||||
|
||||
class KbDifySyncRecord(Base):
|
||||
"""
|
||||
知识库 Dify 同步记录
|
||||
用途:记录本地文档版本与 Dify 远端文档之间的同步映射
|
||||
"""
|
||||
__tablename__ = 'kb_dify_sync_records'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'document_version_id',
|
||||
'remote_document_id',
|
||||
name='uq_kb_dify_sync_records_version_remote'
|
||||
),
|
||||
Index('ix_kb_dify_sync_records_dataset_id', 'dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[int] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
dataset_id: Mapped[str] = mapped_column(String(128))
|
||||
dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
remote_document_id: Mapped[str] = mapped_column(String(128))
|
||||
remote_document_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
status: Mapped[str] = mapped_column(String(32), default='pending', index=True)
|
||||
sync_hash: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
synced_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
synced_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
document_version: Mapped["KbDocumentVersion"] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="sync_records",
|
||||
)
|
||||
synced_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[synced_by_id])
|
||||
|
||||
|
||||
class WecomCallbackAudit(Base):
|
||||
"""
|
||||
企业微信回调审计表
|
||||
用途:记录消息与事件回调(安全模式解密后的内容摘要)
|
||||
"""
|
||||
__tablename__ = 'wecom_callback_audits'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
msg_signature: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
timestamp: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
nonce: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
encrypt_raw: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
decrypted_xml: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
msg_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
event: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
from_user: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
|
||||
agent_id: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
msg_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class ScheduleTask(Base):
|
||||
__tablename__ = 'schedule_tasks'
|
||||
__table_args__ = (
|
||||
Index('ix_schedule_tasks_enabled_next_run', 'enabled', 'next_run_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
||||
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
|
||||
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||
cron_expr: Mapped[str] = mapped_column(String(64))
|
||||
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')
|
||||
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
notify_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
next_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
last_run_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
owner: Mapped[Optional["User"]] = relationship("User", foreign_keys=[owner_user_id])
|
||||
dify_agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[dify_agent_id])
|
||||
config: Mapped[Optional["ScheduleTaskConfig"]] = relationship("ScheduleTaskConfig", back_populates="task", uselist=False, cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class ScheduleTaskConfig(Base):
|
||||
__tablename__ = 'schedule_task_configs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schedule_task_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
|
||||
|
||||
row_id_key: Mapped[str] = mapped_column(String(64), default='id')
|
||||
log_prefix: Mapped[str] = mapped_column(String(128), default='')
|
||||
|
||||
base_fetch_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_where_conditions: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
fetch_order_by: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
writeback_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
detail_sql: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
detail_alias_order: Mapped[Optional[list]] = mapped_column(JSON, default=[])
|
||||
header_labels: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
|
||||
ds_db_type: Mapped[str] = mapped_column(String(32), default='sqlserver')
|
||||
ds_host: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_port: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
ds_database: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_username: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_password: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
ds_driver: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
ds_encrypt: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
ds_trust_cert: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
|
||||
|
||||
api_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
api_method: Mapped[str] = mapped_column(String(16), default='POST')
|
||||
api_headers: Mapped[Optional[dict]] = mapped_column(JSON, default={})
|
||||
api_body_template: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
dify_system_prompt: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", back_populates="config")
|
||||
|
||||
|
||||
class ScheduleRun(Base):
|
||||
__tablename__ = 'schedule_runs'
|
||||
__table_args__ = (
|
||||
Index('ix_schedule_runs_task_created', 'schedule_task_id', 'created_at'),
|
||||
Index('ix_schedule_runs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
schedule_task_id: Mapped[int] = mapped_column(ForeignKey('schedule_tasks.id'), index=True)
|
||||
trigger_type: Mapped[str] = mapped_column(String(16), default='cron')
|
||||
triggered_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, index=True)
|
||||
duration_ms: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
total_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
success_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
failed_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
skipped_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
api_request_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
api_response_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
response_summary_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
step_logs: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
dify_execution_snapshot: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary)
|
||||
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
excel_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
wecom_notified: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
|
||||
wecom_notified_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
wecom_notify_error: Mapped[Optional[str]] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
|
||||
|
||||
|
||||
class ShippingTask(Base):
|
||||
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
|
||||
__tablename__ = 'shipping_tasks'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
|
||||
Index('ix_shipping_tasks_conversation', 'conversation_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
source_type: Mapped[str] = mapped_column(String(32), default='manual')
|
||||
|
||||
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
|
||||
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
|
||||
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
|
||||
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
|
||||
export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
||||
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
events: Mapped[List["ShippingTaskEvent"]] = relationship(
|
||||
"ShippingTaskEvent",
|
||||
back_populates="task",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
|
||||
class ShippingTaskEvent(Base):
|
||||
"""发货 task 审计事件"""
|
||||
__tablename__ = 'shipping_task_events'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), index=True)
|
||||
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
task: Mapped["ShippingTask"] = relationship("ShippingTask", back_populates="events")
|
||||
|
||||
|
||||
class ShippingInventoryMapping(Base):
|
||||
__tablename__ = 'shipping_inventory_mappings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'),
|
||||
Index('ix_shipping_inventory_mappings_customer_code', 'customer_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
customer_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
header_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
headers_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
field_mapping_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, index=True)
|
||||
|
||||
class AgentGuide(Base):
|
||||
"""
|
||||
平台应用新手指南表
|
||||
用途:存储 Agent 的新手指南文件信息 (如视频、PDF)
|
||||
"""
|
||||
__tablename__ = 'agent_guides'
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
file_type: Mapped[str] = mapped_column(String(50), nullable=False) # video, pdf, image
|
||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_size: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, default=0)
|
||||
status: Mapped[int] = mapped_column(Integer, default=1) # 1: 启用, 0: 禁用
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
agent: Mapped[Optional["Agent"]] = relationship("Agent", foreign_keys=[agent_id])
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Resolve paths relative to the backend package root (not process cwd)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def backend_dir() -> Path:
|
||||
return _BACKEND_DIR
|
||||
|
||||
|
||||
def resolve_backend_relative_path(raw: str | None, default: Path | None = None) -> str:
|
||||
"""Resolve env paths like ``data/foo`` or legacy ``backend/data/foo``."""
|
||||
value = (raw or "").strip()
|
||||
if not value:
|
||||
if default is None:
|
||||
raise ValueError("path is required when no default is provided")
|
||||
return str(default.resolve())
|
||||
|
||||
path = Path(value)
|
||||
if path.is_absolute():
|
||||
return str(path.resolve())
|
||||
|
||||
normalized = value.replace("\\", "/")
|
||||
if normalized.startswith("backend/"):
|
||||
return str((_BACKEND_DIR / normalized[len("backend/") :]).resolve())
|
||||
return str((_BACKEND_DIR / value).resolve())
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
backend/app/response_utils.py
|
||||
用途:提供统一响应结构的工具函数(成功与失败)。
|
||||
说明:
|
||||
1. ok:构造 success=true 的响应体,数据统一放在 data 字段。
|
||||
2. error_payload:构造 success=false 的响应体,包含错误码、文案和可选详情。
|
||||
3. utc_iso_now:统一生成 UTC 时间戳,便于前后端与日志对齐。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from flask import jsonify
|
||||
|
||||
|
||||
def utc_iso_now() -> str:
|
||||
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def ok(data: Any, *, request_id: str | None = None, status: int = 200):
|
||||
payload: dict[str, Any] = {
|
||||
"success": True,
|
||||
"data": data,
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return jsonify(payload), status
|
||||
|
||||
|
||||
def error_payload(
|
||||
*,
|
||||
code: str,
|
||||
message: str,
|
||||
request_id: str | None = None,
|
||||
details: dict[str, Any] | None = None,
|
||||
retryable: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
payload: dict[str, Any] = {
|
||||
"success": False,
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"details": details or {},
|
||||
"retryable": retryable,
|
||||
},
|
||||
"timestamp": utc_iso_now(),
|
||||
}
|
||||
if request_id:
|
||||
payload["request_id"] = request_id
|
||||
return payload
|
||||
+1017
-98
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,352 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from flask import current_app
|
||||
|
||||
|
||||
class HRLeaveSQLServerService:
|
||||
_LEAVE_KEYWORDS = ("年假", "育儿假", "假期", "休假", "请假")
|
||||
_PROCESS_KEYWORDS = (
|
||||
"流程",
|
||||
"如何",
|
||||
"怎么办",
|
||||
"怎么",
|
||||
"申请",
|
||||
"审批",
|
||||
"制度",
|
||||
"规则",
|
||||
"办法",
|
||||
"政策",
|
||||
"指引",
|
||||
"规范",
|
||||
"是什么",
|
||||
)
|
||||
_SELF_KEYWORDS = ("我", "我的", "本人", "自己")
|
||||
_BALANCE_KEYWORDS = (
|
||||
"还剩",
|
||||
"还有",
|
||||
"剩余",
|
||||
"多少",
|
||||
"余额",
|
||||
"可休",
|
||||
"未休",
|
||||
"已休",
|
||||
"总时数",
|
||||
"情况",
|
||||
"记录",
|
||||
"明细",
|
||||
"查询",
|
||||
)
|
||||
_STRONG_BALANCE_PATTERNS = (
|
||||
r"(?:假期|年假|育儿假|休假).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少)",
|
||||
r"(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:假期|年假|育儿假|休假)",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def supports(query: str) -> bool:
|
||||
text = (query or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
if not any(keyword in text for keyword in HRLeaveSQLServerService._LEAVE_KEYWORDS):
|
||||
return False
|
||||
if any(keyword in text for keyword in HRLeaveSQLServerService._PROCESS_KEYWORDS):
|
||||
return False
|
||||
if any(re.search(pattern, text) for pattern in HRLeaveSQLServerService._STRONG_BALANCE_PATTERNS):
|
||||
return True
|
||||
if not any(keyword in text for keyword in HRLeaveSQLServerService._SELF_KEYWORDS):
|
||||
return False
|
||||
if any(keyword in text for keyword in HRLeaveSQLServerService._BALANCE_KEYWORDS):
|
||||
return True
|
||||
return bool(re.search(r"(20\d{2}|今年|去年|本年)", text))
|
||||
|
||||
@staticmethod
|
||||
def _detect_leave_type(query: str) -> str:
|
||||
text = (query or "").strip()
|
||||
if "育儿假" in text:
|
||||
return "childcare"
|
||||
if "年假" in text:
|
||||
return "annual"
|
||||
return "all"
|
||||
|
||||
@staticmethod
|
||||
def _extract_year(query: str) -> int | None:
|
||||
text = (query or "").strip()
|
||||
now_year = datetime.now().year
|
||||
explicit = re.search(r"(20\d{2})", text)
|
||||
if explicit:
|
||||
return int(explicit.group(1))
|
||||
if "今年" in text or "本年" in text:
|
||||
return now_year
|
||||
if "去年" in text:
|
||||
return now_year - 1
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _get_employee_code(user) -> str:
|
||||
employee_code = str(
|
||||
getattr(user, "employee_id", None)
|
||||
or getattr(user, "username", None)
|
||||
or ""
|
||||
).strip()
|
||||
if not employee_code:
|
||||
raise RuntimeError("当前登录用户缺少工号,无法查询 HR 假期数据")
|
||||
return employee_code
|
||||
|
||||
@staticmethod
|
||||
def _pick_driver(pyodbc) -> str:
|
||||
drivers = pyodbc.drivers()
|
||||
preferred = [
|
||||
"ODBC Driver 18 for SQL Server",
|
||||
"ODBC Driver 17 for SQL Server",
|
||||
"SQL Server",
|
||||
]
|
||||
for name in preferred:
|
||||
if name in drivers:
|
||||
return name
|
||||
if not drivers:
|
||||
raise RuntimeError("未找到可用的 SQL Server ODBC 驱动")
|
||||
return drivers[-1]
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
try:
|
||||
import pyodbc
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("pyodbc 未安装,无法连接 HR SQL Server") from exc
|
||||
|
||||
driver = os.getenv("HR_SQLSERVER_DRIVER", "").strip() or cls._pick_driver(pyodbc)
|
||||
available_drivers = pyodbc.drivers()
|
||||
if driver not in available_drivers:
|
||||
driver = cls._pick_driver(pyodbc)
|
||||
server = os.getenv("HR_SQLSERVER_HOST", "192.168.100.191").strip()
|
||||
port = os.getenv("HR_SQLSERVER_PORT", "1433").strip()
|
||||
database = os.getenv("HR_SQLSERVER_DATABASE", "NH_N8_HEXIN").strip()
|
||||
username = os.getenv("HR_SQLSERVER_USERNAME", "AI_Knowledge_Base_Hr").strip()
|
||||
password = os.getenv("HR_SQLSERVER_PASSWORD", "hoo-thai@123_AI_HR").strip()
|
||||
encrypt = os.getenv("HR_SQLSERVER_ENCRYPT", "no").strip().lower()
|
||||
trust_cert = os.getenv("HR_SQLSERVER_TRUST_CERT", "yes").strip().lower()
|
||||
timeout = int(os.getenv("HR_SQLSERVER_TIMEOUT", "10"))
|
||||
|
||||
conn_str = (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={server},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
)
|
||||
if driver != "SQL Server":
|
||||
conn_str += (
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
return pyodbc.connect(conn_str, timeout=timeout)
|
||||
|
||||
@staticmethod
|
||||
def _build_query(view_name: str, year_column: str, total_column: str, used_column: str, remaining_column: str, year: int | None):
|
||||
base_sql = f"""
|
||||
SELECT TOP 1
|
||||
c001001 AS department_code,
|
||||
c001002 AS department_name,
|
||||
a008003 AS parent_department_name,
|
||||
c002001 AS employee_id,
|
||||
c002002 AS employee_name,
|
||||
{year_column} AS leave_year,
|
||||
{total_column} AS total_hours,
|
||||
{used_column} AS used_hours,
|
||||
{remaining_column} AS remaining_hours
|
||||
FROM {view_name}
|
||||
WHERE c002001 = ?
|
||||
"""
|
||||
params = []
|
||||
if year is not None:
|
||||
base_sql += f" AND {year_column} = ?\n"
|
||||
params.append(year)
|
||||
base_sql += f"ORDER BY {year_column} DESC"
|
||||
return base_sql.strip(), params
|
||||
|
||||
@classmethod
|
||||
def _query_one(cls, view_name: str, year_column: str, total_column: str, used_column: str, remaining_column: str, employee_code: str, year: int | None):
|
||||
sql, extra_params = cls._build_query(view_name, year_column, total_column, used_column, remaining_column, year)
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
params = [employee_code] + extra_params
|
||||
cursor.execute(sql, params)
|
||||
columns = [col[0] for col in cursor.description] if cursor.description else []
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return sql, None
|
||||
return sql, {columns[idx]: row[idx] for idx in range(len(columns))}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@staticmethod
|
||||
def _format_number(value):
|
||||
if value is None:
|
||||
return "暂无数据"
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _format_quota(cls, value, unit: str = "天") -> str:
|
||||
formatted = cls._format_number(value)
|
||||
if formatted == "暂无数据":
|
||||
return formatted
|
||||
return f"{formatted}{unit}"
|
||||
|
||||
@staticmethod
|
||||
def _resolve_response_year(record: dict | None, requested_year: int | None) -> str:
|
||||
if record and record.get("leave_year") is not None:
|
||||
return str(record["leave_year"])
|
||||
if requested_year is not None:
|
||||
return str(requested_year)
|
||||
return str(datetime.now().year)
|
||||
|
||||
@classmethod
|
||||
def _render_table_row(cls, index: int, title: str, record: dict | None, requested_year: int | None, quota_unit: str = "天") -> str:
|
||||
response_year = cls._resolve_response_year(record, requested_year)
|
||||
if not record:
|
||||
return f"| {index} | {title} | {response_year} | 暂无数据 | 暂无数据 | 暂无数据 |"
|
||||
total = cls._format_quota(record.get('total_hours'), quota_unit)
|
||||
used = cls._format_quota(record.get('used_hours'), quota_unit)
|
||||
remaining = cls._format_quota(record.get('remaining_hours'), "小时")
|
||||
return f"| {index} | {title} | {response_year} | {total} | {used} | {remaining} |"
|
||||
|
||||
@classmethod
|
||||
def _build_result_text(cls, leave_type: str, requested_year: int | None, annual_result, childcare_result):
|
||||
_, annual_record = annual_result
|
||||
_, childcare_record = childcare_result
|
||||
displayed_records = []
|
||||
if leave_type in ("annual", "all"):
|
||||
displayed_records.append(annual_record)
|
||||
if leave_type in ("childcare", "all"):
|
||||
displayed_records.append(childcare_record)
|
||||
|
||||
intro_year = next(
|
||||
(
|
||||
cls._resolve_response_year(record, requested_year)
|
||||
for record in displayed_records
|
||||
if record
|
||||
),
|
||||
str(requested_year or datetime.now().year),
|
||||
)
|
||||
sections = [
|
||||
f"您好,已为您查询到 {intro_year} 年度假期情况:",
|
||||
"",
|
||||
"| 序号 | 假别 | 年度 | 可休 | 已休 | 当前剩余 |",
|
||||
"| :---: | :---: | :---: | :---: | :---: | :---: |",
|
||||
]
|
||||
|
||||
index = 1
|
||||
if leave_type in ("annual", "all"):
|
||||
sections.append(cls._render_table_row(index, "年假", annual_record, requested_year))
|
||||
index += 1
|
||||
if leave_type in ("childcare", "all"):
|
||||
sections.append(cls._render_table_row(index, "育儿假", childcare_record, requested_year, "小时"))
|
||||
index += 1
|
||||
|
||||
sections.extend(
|
||||
[
|
||||
"",
|
||||
"如需继续查询其他假期明细或历史休假记录,请告诉我,我继续帮您核对。",
|
||||
"",
|
||||
'如需发起请假,可点击 <a href="#" class="leave-action-trigger" data-leave-action="start-leave-flow">【点我请假】</a> 或输入 <span class="leave-intent-highlight">“我要请假”</span>。',
|
||||
]
|
||||
)
|
||||
return "\n".join(sections)
|
||||
|
||||
@classmethod
|
||||
def stream_chat(cls, query: str, user, agent, conversation_id: str = None, session_id: str | None = None):
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"hr_{int(time.time())}"
|
||||
try:
|
||||
employee_code = cls._get_employee_code(user)
|
||||
leave_type = cls._detect_leave_type(query)
|
||||
year = cls._extract_year(query)
|
||||
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '已识别为假期查询,正在为您核对假期明细,请稍候...\n'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
annual_result = ("-- 未执行年假查询", None)
|
||||
childcare_result = ("-- 未执行育儿假查询", None)
|
||||
|
||||
if leave_type in ("annual", "all"):
|
||||
annual_result = cls._query_one(
|
||||
view_name="VIEW_D044",
|
||||
year_column="D044001",
|
||||
total_column="D044005",
|
||||
used_column="D044006",
|
||||
remaining_column="D044007",
|
||||
employee_code=employee_code,
|
||||
year=year,
|
||||
)
|
||||
|
||||
if leave_type in ("childcare", "all"):
|
||||
childcare_result = cls._query_one(
|
||||
view_name="VIEW_D072",
|
||||
year_column="d072001",
|
||||
total_column="d072002",
|
||||
used_column="d072003",
|
||||
remaining_column="d072004",
|
||||
employee_code=employee_code,
|
||||
year=year,
|
||||
)
|
||||
|
||||
result_text = cls._build_result_text(leave_type, year, annual_result, childcare_result)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[hr-leave] query done user_id=%s employee_code=%s leave_type=%s year=%s latency_ms=%s",
|
||||
getattr(user, "id", None),
|
||||
employee_code,
|
||||
leave_type,
|
||||
year,
|
||||
latency,
|
||||
)
|
||||
|
||||
from app.models import ChatLog, db
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=final_conversation_id,
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
answer=result_text,
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.error("Failed to log hr leave chat: %s", exc)
|
||||
db.session.rollback()
|
||||
|
||||
end_data = {
|
||||
"event": "message_end",
|
||||
"answer": result_text,
|
||||
"replace_answer": True,
|
||||
"chat_log_id": chat_log_id,
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception("[hr-leave] stream_chat failed query=%s", query)
|
||||
error_data = {
|
||||
"event": "error",
|
||||
"message": str(exc) or "HR 假期查询失败",
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
@@ -0,0 +1,470 @@
|
||||
"""
|
||||
Integration API client for resolving original source-file download links.
|
||||
"""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
from flask import current_app, has_app_context, has_request_context, request
|
||||
|
||||
from app.config import Config
|
||||
|
||||
|
||||
class IntegrationApiService:
|
||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _request_origin_url() -> str:
|
||||
if not has_request_context():
|
||||
return ""
|
||||
|
||||
forwarded_proto = (request.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip()
|
||||
forwarded_host = (request.headers.get("X-Forwarded-Host") or "").split(",")[0].strip()
|
||||
if forwarded_proto and forwarded_host:
|
||||
return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
|
||||
|
||||
origin = str(request.headers.get("Origin") or "").strip().rstrip("/")
|
||||
if origin:
|
||||
return origin
|
||||
|
||||
referer = str(request.headers.get("Referer") or "").strip()
|
||||
if referer:
|
||||
parsed = urlparse(referer)
|
||||
if parsed.scheme and parsed.netloc:
|
||||
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
|
||||
|
||||
return request.host_url.rstrip("/")
|
||||
|
||||
@staticmethod
|
||||
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
|
||||
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
|
||||
"""
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
try:
|
||||
service = KbDifySyncService()
|
||||
if not service.base_url or not service.api_key:
|
||||
return None
|
||||
|
||||
document_payload = service.get_document(
|
||||
dataset_id=str(dataset_id),
|
||||
document_id=str(remote_document_id),
|
||||
)
|
||||
if not isinstance(document_payload, dict):
|
||||
return None
|
||||
|
||||
download_resp = requests.get(
|
||||
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
|
||||
headers=service._headers(),
|
||||
timeout=(5, 15),
|
||||
)
|
||||
if download_resp.status_code != 200:
|
||||
if has_app_context():
|
||||
current_app.logger.info(
|
||||
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
download_resp.status_code,
|
||||
)
|
||||
return None
|
||||
|
||||
download_payload = download_resp.json() if download_resp.content else {}
|
||||
source_url = str((download_payload or {}).get("url") or "").strip()
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
upload_info = (
|
||||
((document_payload.get("data_source_info") or {}).get("upload_file"))
|
||||
if isinstance(document_payload.get("data_source_info"), dict)
|
||||
else {}
|
||||
) or {}
|
||||
source_filename = str(
|
||||
upload_info.get("name")
|
||||
or document_payload.get("name")
|
||||
or ""
|
||||
).strip() or None
|
||||
source_ext = str(
|
||||
upload_info.get("extension")
|
||||
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
|
||||
).strip().lower() or None
|
||||
|
||||
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
|
||||
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
|
||||
|
||||
return {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": source_filename,
|
||||
"source_ext": source_ext,
|
||||
"download_url_expires_at": expires_at,
|
||||
"version_id": None,
|
||||
"document_id": remote_document_id,
|
||||
}
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(
|
||||
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
e,
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
|
||||
if not isinstance(row, dict):
|
||||
return None
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id or not row.get("found"):
|
||||
return None
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
return None
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
return key, normalized
|
||||
|
||||
@staticmethod
|
||||
def _is_loopback_url(url: str) -> bool:
|
||||
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
|
||||
return host in {"127.0.0.1", "localhost", "::1"}
|
||||
|
||||
@staticmethod
|
||||
def get_api_key() -> str:
|
||||
if has_app_context():
|
||||
return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
return str(Config.INTEGRATION_API_KEY or "").strip()
|
||||
|
||||
@staticmethod
|
||||
def get_base_url() -> str:
|
||||
mode = "local"
|
||||
if has_app_context():
|
||||
mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower()
|
||||
configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/")
|
||||
public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/")
|
||||
else:
|
||||
mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower()
|
||||
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
|
||||
public_base = ""
|
||||
|
||||
# For server-side lookups, always prefer the explicitly configured
|
||||
# integration service endpoint when present. Falling back to the current
|
||||
# request host would incorrectly call this backend itself.
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
if mode != "external":
|
||||
request_origin = IntegrationApiService._request_origin_url()
|
||||
if request_origin:
|
||||
return request_origin
|
||||
if public_base:
|
||||
return public_base
|
||||
if has_request_context():
|
||||
return request.host_url.rstrip("/")
|
||||
|
||||
return configured
|
||||
|
||||
@staticmethod
|
||||
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
|
||||
return (str(dataset_id), str(remote_document_id))
|
||||
|
||||
@staticmethod
|
||||
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
||||
exp_str = payload.get("download_url_expires_at")
|
||||
if exp_str:
|
||||
try:
|
||||
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
|
||||
source_url = payload.get("source_download_url") or ""
|
||||
if "token=" in source_url:
|
||||
try:
|
||||
import base64
|
||||
import json
|
||||
from urllib.parse import urlparse, parse_qs
|
||||
import time
|
||||
qs = parse_qs(urlparse(source_url).query)
|
||||
if 'token' in qs:
|
||||
token = qs['token'][0]
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
exp = payload_data.get('exp', 0)
|
||||
if exp and exp < time.time() + 300:
|
||||
return False # 已过期或即将过期
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
if not has_app_context():
|
||||
return None
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
|
||||
|
||||
normalized_dataset_id = str(dataset_id or '').strip()
|
||||
normalized_remote_document_id = str(remote_document_id or '').strip()
|
||||
if not normalized_dataset_id or not normalized_remote_document_id:
|
||||
return None
|
||||
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.filter(
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbDifySyncRecord.dataset_id == normalized_dataset_id,
|
||||
KbDifySyncRecord.remote_document_id == normalized_remote_document_id,
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if not record or not record.document_version or not record.document_version.document:
|
||||
return None
|
||||
|
||||
version = record.document_version
|
||||
document = version.document
|
||||
|
||||
base_url = IntegrationApiService._request_origin_url()
|
||||
if not base_url:
|
||||
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||
if explicit:
|
||||
base_url = explicit
|
||||
elif has_request_context():
|
||||
base_url = request.host_url.rstrip('/')
|
||||
else:
|
||||
base_url = ''
|
||||
|
||||
import time
|
||||
import jwt
|
||||
|
||||
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
if not secret:
|
||||
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
|
||||
payload = {
|
||||
'dataset_id': normalized_dataset_id,
|
||||
'remote_document_id': normalized_remote_document_id,
|
||||
'version_id': version.id,
|
||||
'exp': exp
|
||||
}
|
||||
token = jwt.encode(payload, secret, algorithm='HS256')
|
||||
|
||||
source_download_url = (
|
||||
f'{base_url}/api/integration/files/{document.id}/download'
|
||||
f'?kind=source&version_id={version.id}&token={token}'
|
||||
)
|
||||
|
||||
return {
|
||||
"source_download_url": source_download_url,
|
||||
"source_filename": version.source_file_name,
|
||||
"source_ext": version.source_file_ext,
|
||||
"download_url_expires_at": None,
|
||||
"version_id": version.id,
|
||||
"document_id": document.id,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
|
||||
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
cached = IntegrationApiService._cache.get(cache_key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
return cached
|
||||
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
|
||||
url = f"{base_url}/api/integration/dify-file"
|
||||
headers = {"X-Integration-Key": api_key}
|
||||
params = {
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
if isinstance(payload, dict):
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
elif has_app_context():
|
||||
current_app.logger.info(
|
||||
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
resp.status_code,
|
||||
)
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API lookup failed: {e}")
|
||||
|
||||
batch_url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
batch_headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
batch_body = {
|
||||
"items": [
|
||||
{
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
]
|
||||
}
|
||||
try:
|
||||
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
|
||||
if resp.status_code == 200:
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if isinstance(data, list):
|
||||
for row in data:
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
if key == cache_key:
|
||||
return normalized
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
|
||||
|
||||
# Fallback to local database if remote integration API fails or misses
|
||||
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if local_result:
|
||||
IntegrationApiService._cache[cache_key] = local_result
|
||||
return local_result
|
||||
|
||||
# Last fallback: query Dify document API directly and request a signed download URL.
|
||||
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
|
||||
if dify_result:
|
||||
IntegrationApiService._cache[cache_key] = dify_result
|
||||
return dify_result
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
|
||||
"""
|
||||
Batch resolve source files by (dataset_id, remote_document_id).
|
||||
Returns a mapping keyed by (dataset_id, remote_document_id).
|
||||
"""
|
||||
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
if not items:
|
||||
return results
|
||||
|
||||
unresolved: List[Dict[str, str]] = []
|
||||
seen = set()
|
||||
|
||||
for item in items:
|
||||
dataset_id = str(item.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(item.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
cached = IntegrationApiService._cache.get(key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
results[key] = cached
|
||||
else:
|
||||
unresolved.append({
|
||||
"dataset_id": dataset_id,
|
||||
"remote_document_id": remote_document_id,
|
||||
})
|
||||
|
||||
if not unresolved:
|
||||
return results
|
||||
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return results
|
||||
|
||||
url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
body = {"items": unresolved}
|
||||
|
||||
try:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
|
||||
if resp.status_code != 200:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(
|
||||
"Integration API batch lookup failed: status=%s", resp.status_code
|
||||
)
|
||||
else:
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if isinstance(data, list):
|
||||
for row in data:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||
if not normalized_row:
|
||||
continue
|
||||
key, normalized = normalized_row
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
results[key] = normalized
|
||||
except Exception as e:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
|
||||
|
||||
# Fallback to single lookup or local DB for unresolved items
|
||||
for item in unresolved:
|
||||
dataset_id = item["dataset_id"]
|
||||
remote_document_id = item["remote_document_id"]
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in results:
|
||||
continue
|
||||
|
||||
# Check if single lookup was not called already (if it was, it might be cached)
|
||||
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
|
||||
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||
if local_result:
|
||||
IntegrationApiService._cache[key] = local_result
|
||||
results[key] = local_result
|
||||
continue
|
||||
|
||||
# As a last resort, try remote single lookup if batch missed it
|
||||
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if payload:
|
||||
results[key] = payload
|
||||
|
||||
return results
|
||||
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
知识库清洗服务包
|
||||
"""
|
||||
@@ -0,0 +1,316 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/dify_sync_service.py
|
||||
文件用途:知识库文档版本到 Dify 的最小同步服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
|
||||
|
||||
|
||||
class KbDifySyncError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class KbDifySyncService:
|
||||
def __init__(self) -> None:
|
||||
settings = get_kb_dify_settings()
|
||||
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
|
||||
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
|
||||
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
|
||||
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
|
||||
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
|
||||
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
|
||||
self.timeout = 60
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.base_url:
|
||||
raise KbDifySyncError('DIFY_API_BASE 未配置')
|
||||
if not self.api_key:
|
||||
raise KbDifySyncError('DIFY_API_KEY 未配置')
|
||||
return {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs):
|
||||
url = f'{self.base_url}{path}'
|
||||
try:
|
||||
response = requests.request(
|
||||
method,
|
||||
url,
|
||||
headers=self._headers(),
|
||||
timeout=self.timeout,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
|
||||
if response.status_code >= 400:
|
||||
raise KbDifySyncError(
|
||||
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
|
||||
)
|
||||
if response.status_code == 204:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
def list_datasets(self) -> list[dict]:
|
||||
payload = self._request('GET', '/datasets')
|
||||
return payload.get('data', []) if isinstance(payload, dict) else []
|
||||
|
||||
def create_dataset(self, *, name: str, description: str | None) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'description': description or '',
|
||||
'permission': self.permission,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'retrieval_model': {
|
||||
'search_method': self.search_method,
|
||||
'reranking_enable': False,
|
||||
'top_k': 3,
|
||||
'score_threshold_enabled': False,
|
||||
'score_threshold': None,
|
||||
},
|
||||
}
|
||||
return self._request('POST', '/datasets', json=payload)
|
||||
|
||||
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
|
||||
if group.dify_dataset_id:
|
||||
return group.dify_dataset_id, group.dify_dataset_name or group.name
|
||||
|
||||
dataset_name = group.dify_dataset_name or group.name
|
||||
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
|
||||
if existing:
|
||||
group.dify_dataset_id = existing.get('id')
|
||||
group.dify_dataset_name = existing.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
created = self.create_dataset(name=dataset_name, description=group.description)
|
||||
group.dify_dataset_id = created.get('id')
|
||||
group.dify_dataset_name = created.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
|
||||
|
||||
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request(
|
||||
'POST',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
|
||||
json=payload,
|
||||
)
|
||||
|
||||
def get_document(self, *, dataset_id: str, document_id: str) -> dict:
|
||||
return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}')
|
||||
|
||||
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
|
||||
self._request(
|
||||
'DELETE',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}',
|
||||
)
|
||||
|
||||
|
||||
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
|
||||
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
|
||||
for value in candidate_paths:
|
||||
if not value:
|
||||
continue
|
||||
path = Path(value)
|
||||
if not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8', errors='ignore').strip()
|
||||
if text:
|
||||
return text, str(path)
|
||||
raise KbDifySyncError('没有可用于同步的文本结果')
|
||||
|
||||
|
||||
def _is_remote_document_missing(error_text: str) -> bool:
|
||||
return (
|
||||
'404' in error_text
|
||||
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
|
||||
)
|
||||
|
||||
|
||||
def _resolve_upload_name(version: KbDocumentVersion) -> str:
|
||||
document_title = str(getattr(version.document, 'title', '') or '').strip()
|
||||
if document_title:
|
||||
return document_title
|
||||
source_file_name = str(version.source_file_name or '').strip()
|
||||
if source_file_name:
|
||||
return source_file_name
|
||||
return f'文档-{version.document_id}'
|
||||
|
||||
|
||||
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
|
||||
version = db.session.get(KbDocumentVersion, document_version_id)
|
||||
if not version or not version.document or not version.document.group:
|
||||
raise KbDifySyncError('文档版本或关联分组不存在')
|
||||
|
||||
group = version.document.group
|
||||
document = version.document
|
||||
text, source_path = _load_sync_text(version)
|
||||
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
service = KbDifySyncService()
|
||||
dataset_id, dataset_name = service.ensure_dataset(group)
|
||||
|
||||
existing_record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document.id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
upload_name = _resolve_upload_name(version)
|
||||
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
|
||||
try:
|
||||
payload = service.get_document(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
)
|
||||
remote_document_id = payload.get('id') or existing_record.remote_document_id
|
||||
remote_document_name = payload.get('name') or existing_record.remote_document_name or upload_name
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=upload_name,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or upload_name
|
||||
elif existing_record and existing_record.dataset_id == dataset_id:
|
||||
try:
|
||||
payload = service.update_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
name=upload_name,
|
||||
text=text,
|
||||
)
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=upload_name,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
|
||||
remote_document_name = payload.get('document', {}).get('name') or upload_name
|
||||
else:
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=upload_name,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or upload_name
|
||||
|
||||
if not remote_document_id:
|
||||
raise KbDifySyncError('Dify 未返回远端文档 ID')
|
||||
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_version_id == version.id,
|
||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not record:
|
||||
record = KbDifySyncRecord(
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
dataset_id=dataset_id,
|
||||
dataset_name=dataset_name,
|
||||
remote_document_id=remote_document_id,
|
||||
remote_document_name=remote_document_name,
|
||||
status='synced',
|
||||
sync_hash=sync_hash,
|
||||
synced_by_id=synced_by_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
else:
|
||||
record.dataset_id = dataset_id
|
||||
record.dataset_name = dataset_name
|
||||
record.remote_document_name = remote_document_name
|
||||
record.status = 'synced'
|
||||
record.sync_hash = sync_hash
|
||||
record.error_message = None
|
||||
record.synced_by_id = synced_by_id
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
'remote_document_id': remote_document_id,
|
||||
'remote_document_name': remote_document_name,
|
||||
'sync_hash': sync_hash,
|
||||
'source_path': source_path,
|
||||
}
|
||||
|
||||
|
||||
def delete_document_from_dify(document_id: int) -> dict:
|
||||
records = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document_id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
KbDifySyncRecord.dataset_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.all()
|
||||
)
|
||||
if not records:
|
||||
return {'deleted': True, 'remote_document_count': 0}
|
||||
|
||||
service = KbDifySyncService()
|
||||
deleted_count = 0
|
||||
visited: set[tuple[str, str]] = set()
|
||||
|
||||
for record in records:
|
||||
key = (str(record.dataset_id), str(record.remote_document_id))
|
||||
if key in visited:
|
||||
continue
|
||||
visited.add(key)
|
||||
try:
|
||||
service.delete_document(dataset_id=key[0], document_id=key[1])
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
raise
|
||||
record.status = 'deleted'
|
||||
record.error_message = None
|
||||
record.synced_at = datetime.utcnow()
|
||||
deleted_count += 1
|
||||
|
||||
db.session.commit()
|
||||
return {'deleted': True, 'remote_document_count': deleted_count}
|
||||
@@ -0,0 +1,242 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/dify_sync_service.py
|
||||
文件用途:知识库文档版本到 Dify 的最小同步服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
|
||||
|
||||
|
||||
class KbDifySyncError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class KbDifySyncService:
|
||||
def __init__(self) -> None:
|
||||
settings = get_kb_dify_settings()
|
||||
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
|
||||
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
|
||||
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
|
||||
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
|
||||
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
|
||||
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
|
||||
self.timeout = 60
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.base_url:
|
||||
raise KbDifySyncError('DIFY_API_BASE 未配置')
|
||||
if not self.api_key:
|
||||
raise KbDifySyncError('DIFY_API_KEY 未配置')
|
||||
return {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs):
|
||||
url = f'{self.base_url}{path}'
|
||||
try:
|
||||
response = requests.request(
|
||||
method,
|
||||
url,
|
||||
headers=self._headers(),
|
||||
timeout=self.timeout,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
|
||||
if response.status_code >= 400:
|
||||
raise KbDifySyncError(
|
||||
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
|
||||
)
|
||||
if response.status_code == 204:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
def list_datasets(self) -> list[dict]:
|
||||
payload = self._request('GET', '/datasets')
|
||||
return payload.get('data', []) if isinstance(payload, dict) else []
|
||||
|
||||
def create_dataset(self, *, name: str, description: str | None) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'description': description or '',
|
||||
'permission': self.permission,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'retrieval_model': {
|
||||
'search_method': self.search_method,
|
||||
'reranking_enable': False,
|
||||
'top_k': 3,
|
||||
'score_threshold_enabled': False,
|
||||
'score_threshold': None,
|
||||
},
|
||||
}
|
||||
return self._request('POST', '/datasets', json=payload)
|
||||
|
||||
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
|
||||
if group.dify_dataset_id:
|
||||
return group.dify_dataset_id, group.dify_dataset_name or group.name
|
||||
|
||||
dataset_name = group.dify_dataset_name or group.name
|
||||
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
|
||||
if existing:
|
||||
group.dify_dataset_id = existing.get('id')
|
||||
group.dify_dataset_name = existing.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
created = self.create_dataset(name=dataset_name, description=group.description)
|
||||
group.dify_dataset_id = created.get('id')
|
||||
group.dify_dataset_name = created.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
|
||||
|
||||
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request(
|
||||
'POST',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
|
||||
json=payload,
|
||||
)
|
||||
|
||||
|
||||
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
|
||||
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
|
||||
for value in candidate_paths:
|
||||
if not value:
|
||||
continue
|
||||
path = Path(value)
|
||||
if not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8', errors='ignore').strip()
|
||||
if text:
|
||||
return text, str(path)
|
||||
raise KbDifySyncError('没有可用于同步的文本结果')
|
||||
|
||||
|
||||
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
|
||||
version = db.session.get(KbDocumentVersion, document_version_id)
|
||||
if not version or not version.document or not version.document.group:
|
||||
raise KbDifySyncError('文档版本或关联分组不存在')
|
||||
|
||||
group = version.document.group
|
||||
document = version.document
|
||||
text, source_path = _load_sync_text(version)
|
||||
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
service = KbDifySyncService()
|
||||
dataset_id, dataset_name = service.ensure_dataset(group)
|
||||
|
||||
existing_record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document.id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
if existing_record and existing_record.sync_hash == sync_hash:
|
||||
remote_document_id = existing_record.remote_document_id
|
||||
remote_document_name = existing_record.remote_document_name
|
||||
elif existing_record and existing_record.dataset_id == dataset_id:
|
||||
try:
|
||||
payload = service.update_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
except KbDifySyncError as exc:
|
||||
error_text = str(exc)
|
||||
remote_missing = (
|
||||
'404' in error_text
|
||||
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
|
||||
)
|
||||
if not remote_missing:
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
else:
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
|
||||
if not remote_document_id:
|
||||
raise KbDifySyncError('Dify 未返回远端文档 ID')
|
||||
|
||||
record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_version_id == version.id,
|
||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not record:
|
||||
record = KbDifySyncRecord(
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
dataset_id=dataset_id,
|
||||
dataset_name=dataset_name,
|
||||
remote_document_id=remote_document_id,
|
||||
remote_document_name=remote_document_name,
|
||||
status='synced',
|
||||
sync_hash=sync_hash,
|
||||
synced_by_id=synced_by_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
else:
|
||||
record.dataset_id = dataset_id
|
||||
record.dataset_name = dataset_name
|
||||
record.remote_document_name = remote_document_name
|
||||
record.status = 'synced'
|
||||
record.sync_hash = sync_hash
|
||||
record.error_message = None
|
||||
record.synced_by_id = synced_by_id
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
'remote_document_id': remote_document_id,
|
||||
'remote_document_name': remote_document_name,
|
||||
'sync_hash': sync_hash,
|
||||
'source_path': source_path,
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/edkb_adapter.py
|
||||
文件用途:edkb_system 轻量适配层
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
TEXT_EXTS = {'.txt', '.md'}
|
||||
|
||||
|
||||
def _temporary_env(**overrides: str):
|
||||
saved: dict[str, str | None] = {}
|
||||
|
||||
class _EnvGuard:
|
||||
def __enter__(self):
|
||||
for key, value in overrides.items():
|
||||
saved[key] = os.environ.get(key)
|
||||
os.environ[key] = value
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
for key, old_value in saved.items():
|
||||
if old_value is None:
|
||||
os.environ.pop(key, None)
|
||||
else:
|
||||
os.environ[key] = old_value
|
||||
return False
|
||||
|
||||
return _EnvGuard()
|
||||
|
||||
|
||||
def _find_generated_markdown(output_root: Path) -> Path:
|
||||
# Look for md files directly inside output_root or inside any of its subdirectories
|
||||
# Note that edkb_system puts output inside a directory matching the parent dir name, which might be tmp_dir
|
||||
candidates = [path for path in output_root.rglob('*.md') if not path.name.startswith('_')]
|
||||
if not candidates:
|
||||
raise RuntimeError('No markdown output produced by edkb_system.')
|
||||
candidates.sort(key=lambda item: len(item.parts))
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def _find_generated_preview_markdown(output_root: Path) -> Path | None:
|
||||
candidates = [path for path in output_root.rglob('03_clean_view.md') if path.is_file()]
|
||||
if not candidates:
|
||||
return None
|
||||
candidates.sort(key=lambda item: len(item.parts))
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def _rewrite_preview_markdown_if_needed(preview_path: Path, target_dir: Path) -> None:
|
||||
content = preview_path.read_text(encoding='utf-8', errors='ignore')
|
||||
if 'data:image/' not in content:
|
||||
return
|
||||
|
||||
from edkb_system.skills.export import _LocalPreviewImageRewriter
|
||||
|
||||
images_dir = target_dir / 'images_view'
|
||||
if images_dir.exists():
|
||||
shutil.rmtree(images_dir)
|
||||
rewriter = _LocalPreviewImageRewriter(images_dir=images_dir)
|
||||
preview_path.write_text(rewriter.replace_text(content), encoding='utf-8')
|
||||
|
||||
|
||||
def _write_text_result(source_path: Path, target_dir: Path) -> dict:
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
cleaned_path = target_dir / 'document.md'
|
||||
content = source_path.read_text(encoding='utf-8', errors='ignore')
|
||||
cleaned_path.write_text(content, encoding='utf-8')
|
||||
return {
|
||||
'mode': 'plain_text',
|
||||
'cleaned_file_path': str(cleaned_path),
|
||||
'cleaned_preview_path': str(cleaned_path),
|
||||
'word_count': len(content.split()),
|
||||
}
|
||||
|
||||
|
||||
def build_clean_result(source_path: Path, target_dir: Path) -> dict:
|
||||
"""
|
||||
优先产出真实文本结果:
|
||||
- txt/md:直接抽取文本;
|
||||
- 其它格式:尝试走 edkb_system;
|
||||
- 失败时由调用方决定是否回退。
|
||||
"""
|
||||
suffix = source_path.suffix.lower()
|
||||
if suffix in TEXT_EXTS:
|
||||
return _write_text_result(source_path, target_dir)
|
||||
|
||||
from edkb_system.config import SystemConfig
|
||||
from edkb_system.controller import build_knowledge
|
||||
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='edkb_', dir=str(target_dir.parent)) as tmp_dir:
|
||||
tmp_root = Path(tmp_dir)
|
||||
output_dir = tmp_root / 'output'
|
||||
cache_dir = tmp_root / 'cache'
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# IMPORTANT: copy the source file into tmp_root so that its parent directory is predictable
|
||||
# edkb_system seems to output to output_dir / <parent_dir_name> / <filename>.md
|
||||
# ALSO IMPORTANT: ensure the file has its original suffix, otherwise edkb_system might fail or output nothing
|
||||
original_name = getattr(source_path, "original_filename", None)
|
||||
if not original_name:
|
||||
original_name = source_path.name
|
||||
if "." not in original_name and hasattr(source_path, "suffix_hint"):
|
||||
original_name += source_path.suffix_hint
|
||||
|
||||
tmp_source_path = tmp_root / original_name
|
||||
shutil.copy2(source_path, tmp_source_path)
|
||||
|
||||
config = SystemConfig.load(None)
|
||||
# Align with the xx system: do not spend clean-time uploading images to MinIO.
|
||||
# Keep embedded-image fallback so Markdown can still be produced locally.
|
||||
with _temporary_env(
|
||||
MINIO_UPLOAD_ENABLED='false',
|
||||
MINIO_ALLOW_EMBED_FALLBACK='true',
|
||||
):
|
||||
result = build_knowledge(tmp_source_path, output_dir, config, cache_dir)
|
||||
failures = [item for item in result if item.get('status') == 'failed']
|
||||
if failures:
|
||||
raise RuntimeError(failures[0].get('error') or 'edkb_system failed.')
|
||||
|
||||
markdown_source = _find_generated_markdown(output_dir)
|
||||
preview_source = _find_generated_preview_markdown(output_dir)
|
||||
cleaned_path = target_dir / 'document.md'
|
||||
shutil.copy2(markdown_source, cleaned_path)
|
||||
preview_path = cleaned_path
|
||||
if preview_source and preview_source.exists():
|
||||
preview_path = target_dir / 'document_preview.md'
|
||||
shutil.copy2(preview_source, preview_path)
|
||||
preview_images_dir = preview_source.parent / 'images_view'
|
||||
target_preview_images_dir = target_dir / 'images_view'
|
||||
if target_preview_images_dir.exists():
|
||||
shutil.rmtree(target_preview_images_dir)
|
||||
if preview_images_dir.exists():
|
||||
shutil.copytree(preview_images_dir, target_preview_images_dir)
|
||||
_rewrite_preview_markdown_if_needed(preview_path, target_dir)
|
||||
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
|
||||
|
||||
return {
|
||||
'mode': 'edkb_system',
|
||||
'cleaned_file_path': str(cleaned_path),
|
||||
'cleaned_preview_path': str(preview_path),
|
||||
'word_count': len(content.split()),
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/queue_service.py
|
||||
文件用途:知识库任务调度最小实现
|
||||
|
||||
补充能力(2026-05):
|
||||
- recover_stale_running_jobs:回收超时仍处于 running 的后台任务,防止单条卡死阻塞 worker;
|
||||
- process_next_kb_job 在取 queued 任务前会先执行一次超时回收。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app import db
|
||||
from app.models import KbDocumentVersion, KbJob
|
||||
|
||||
logger = logging.getLogger('kb-worker')
|
||||
_WORD_EXTENSIONS = {'doc', 'docx'}
|
||||
|
||||
|
||||
def _normalize_source_ext(value: str | None) -> str:
|
||||
return str(value or '').strip().lower().lstrip('.')
|
||||
|
||||
|
||||
def _is_word_clean_job(job: KbJob | None) -> bool:
|
||||
if not job or job.job_type != 'clean' or not job.document_version:
|
||||
return False
|
||||
return _normalize_source_ext(job.document_version.source_file_ext) in _WORD_EXTENSIONS
|
||||
|
||||
|
||||
def _has_running_word_clean_job() -> bool:
|
||||
running_jobs = (
|
||||
db.session.query(KbJob)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbJob.document_version_id)
|
||||
.filter(
|
||||
KbJob.job_type == 'clean',
|
||||
KbJob.status == 'running',
|
||||
KbDocumentVersion.source_file_ext.isnot(None),
|
||||
)
|
||||
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
|
||||
.all()
|
||||
)
|
||||
return any(_is_word_clean_job(job) for job in running_jobs)
|
||||
|
||||
|
||||
def recover_stale_running_jobs() -> tuple[int, str]:
|
||||
"""
|
||||
回收长时间停留在 running 的任务,避免单条卡死阻塞 worker 队列。
|
||||
|
||||
阈值读取 KB_JOB_RUNNING_TIMEOUT_SECONDS(默认 300 秒),
|
||||
应大于单次清洗的预期耗时(含多次 soffice 转换)。
|
||||
"""
|
||||
timeout_sec = float(current_app.config.get('KB_JOB_RUNNING_TIMEOUT_SECONDS', 300))
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_sec)
|
||||
|
||||
stale_jobs = (
|
||||
db.session.query(KbJob)
|
||||
.filter(
|
||||
KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')),
|
||||
KbJob.status == 'running',
|
||||
KbJob.started_at.isnot(None),
|
||||
KbJob.started_at < cutoff,
|
||||
)
|
||||
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
|
||||
.all()
|
||||
)
|
||||
if not stale_jobs:
|
||||
return 0, 'no_stale_jobs'
|
||||
|
||||
now = datetime.utcnow()
|
||||
message = f'任务执行超时(超过 {int(timeout_sec)}s),已自动回收'
|
||||
for job in stale_jobs:
|
||||
job.status = 'failed'
|
||||
job.error_message = message
|
||||
job.message = message
|
||||
job.finished_at = now
|
||||
job.progress = 100
|
||||
|
||||
if not job.document_version_id:
|
||||
continue
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id)
|
||||
if not version:
|
||||
continue
|
||||
|
||||
if job.job_type == 'clean' and version.status in ('processing', 'uploaded'):
|
||||
version.status = 'failed'
|
||||
version.error_message = message
|
||||
elif job.job_type == 'sync_dify' and version.status == 'syncing':
|
||||
version.status = 'ready'
|
||||
version.error_message = message
|
||||
|
||||
db.session.commit()
|
||||
logger.warning('recovered %s stale running kb job(s)', len(stale_jobs))
|
||||
return len(stale_jobs), f'recovered_{len(stale_jobs)}'
|
||||
|
||||
|
||||
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
|
||||
"""
|
||||
最小任务调度器:
|
||||
- sync: 上传后立即在请求内执行;
|
||||
- worker: 仅保留 queued,等待独立 worker 轮询;
|
||||
- manual: 保留 queued,等待管理台手动执行。
|
||||
"""
|
||||
mode = str(
|
||||
current_app.config.get('KB_TASK_EXECUTION_MODE')
|
||||
or current_app.config.get('TASK_EXECUTION_MODE', 'worker')
|
||||
).strip().lower()
|
||||
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, 'job_not_found'
|
||||
|
||||
if mode == 'sync':
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job, run_sync_job
|
||||
|
||||
if job.job_type == 'clean':
|
||||
return run_clean_job(job_id)
|
||||
if job.job_type == 'path_upload':
|
||||
return run_path_upload_job(job_id)
|
||||
if job.job_type == 'sync_dify':
|
||||
return run_sync_job(job_id)
|
||||
return False, f'unsupported_sync_job:{job.job_type}'
|
||||
|
||||
if mode in ('worker', 'rq'):
|
||||
return True, 'queued_for_worker'
|
||||
|
||||
return True, 'queued_manual'
|
||||
|
||||
|
||||
def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
return enqueue_kb_job(job_id)
|
||||
|
||||
|
||||
def claim_next_kb_job() -> KbJob | None:
|
||||
"""
|
||||
原子领取下一条 queued 任务,避免并发 worker 重复消费同一条记录。
|
||||
|
||||
当前运行在 PostgreSQL,可安全使用 FOR UPDATE SKIP LOCKED。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
has_running_word_job = _has_running_word_clean_job()
|
||||
candidates = (
|
||||
db.session.query(KbJob)
|
||||
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
|
||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
logger.exception('failed to claim next kb job')
|
||||
return None
|
||||
|
||||
job = next(
|
||||
(
|
||||
item for item in candidates
|
||||
if not (has_running_word_job and _is_word_clean_job(item))
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
if not job:
|
||||
db.session.rollback()
|
||||
return None
|
||||
|
||||
job.status = 'running'
|
||||
job.started_at = job.started_at or now
|
||||
job.progress = max(int(job.progress or 0), 1)
|
||||
if job.job_type == 'clean':
|
||||
job.message = 'worker 已领取 Word 串行清洗任务' if _is_word_clean_job(job) else 'worker 已领取清洗任务'
|
||||
elif job.job_type == 'sync_dify':
|
||||
job.message = 'worker 已领取同步任务'
|
||||
else:
|
||||
job.message = 'worker 已领取路径上传任务'
|
||||
db.session.commit()
|
||||
return job
|
||||
|
||||
|
||||
def process_next_kb_job() -> tuple[bool, str]:
|
||||
# 先回收历史卡死的 running 任务,再领取下一条 queued 任务
|
||||
recover_stale_running_jobs()
|
||||
|
||||
job = claim_next_kb_job()
|
||||
if not job:
|
||||
return False, 'no_job'
|
||||
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job, run_sync_job
|
||||
|
||||
if job.job_type == 'path_upload':
|
||||
return run_path_upload_job(job.id)
|
||||
if job.job_type == 'sync_dify':
|
||||
return run_sync_job(job.id)
|
||||
return run_clean_job(job.id)
|
||||
|
||||
|
||||
def process_next_clean_job() -> tuple[bool, str]:
|
||||
return process_next_kb_job()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/settings_service.py
|
||||
文件用途:知识库 Dify 设置读写服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.env_persistence import persist_env_settings
|
||||
from app.models import AppSetting, KbDifySyncRecord, KbGroup, KbJob, KbDocumentVersion
|
||||
|
||||
|
||||
SETTING_DEFAULTS = {
|
||||
'DIFY_API_BASE': '',
|
||||
'DIFY_API_KEY': '',
|
||||
'KB_DIFY_PERMISSION': 'only_me',
|
||||
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
||||
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
|
||||
'KB_DIFY_DOC_FORM': 'text_model',
|
||||
}
|
||||
|
||||
|
||||
def _get_setting_value(key: str) -> str:
|
||||
row = db.session.get(AppSetting, key)
|
||||
if row and row.value is not None:
|
||||
return row.value
|
||||
config_value = current_app.config.get(key)
|
||||
if config_value is not None:
|
||||
return str(config_value)
|
||||
return str(os.getenv(key, SETTING_DEFAULTS.get(key, '')))
|
||||
|
||||
|
||||
def get_kb_dify_settings() -> dict:
|
||||
payload = {key: _get_setting_value(key) for key in SETTING_DEFAULTS}
|
||||
payload['dify_api_configured'] = bool(payload.get('DIFY_API_KEY'))
|
||||
return payload
|
||||
|
||||
|
||||
def save_kb_dify_settings(values: dict[str, object]) -> dict:
|
||||
allowed = {key: values[key] for key in SETTING_DEFAULTS if key in values}
|
||||
persisted = persist_env_settings(allowed)
|
||||
return {
|
||||
**get_kb_dify_settings(),
|
||||
**persisted,
|
||||
'dify_api_configured': bool((persisted.get('DIFY_API_KEY') or _get_setting_value('DIFY_API_KEY')).strip()),
|
||||
}
|
||||
|
||||
|
||||
def get_kb_dify_health_payload() -> dict:
|
||||
settings = get_kb_dify_settings()
|
||||
base_url = settings.get('DIFY_API_BASE') or ''
|
||||
api_key = settings.get('DIFY_API_KEY') or ''
|
||||
|
||||
payload = {
|
||||
'dify_base_url': base_url,
|
||||
'dify_api_configured': bool(api_key),
|
||||
'api': {
|
||||
'configured': bool(api_key),
|
||||
'reachable': False,
|
||||
'dataset_count': None,
|
||||
'error': None,
|
||||
},
|
||||
'local_sync_health': {
|
||||
'dataset_bound_groups': db.session.query(KbGroup).filter(KbGroup.dify_dataset_id.isnot(None)).count(),
|
||||
'sync_records': db.session.query(KbDifySyncRecord).count(),
|
||||
'syncing_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'syncing').count(),
|
||||
'synced_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'synced').count(),
|
||||
'failed_sync_records': db.session.query(KbDifySyncRecord).filter(KbDifySyncRecord.status == 'failed').count(),
|
||||
'pending_sync_jobs': db.session.query(KbJob).filter(KbJob.job_type == 'sync_dify', KbJob.status == 'queued').count(),
|
||||
},
|
||||
}
|
||||
return payload
|
||||
@@ -0,0 +1,574 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/tasks.py
|
||||
文件用途:知识库任务执行第一版
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import zipfile
|
||||
|
||||
from flask import current_app
|
||||
from app import db
|
||||
from app.models import KbDocument, KbDocumentVersion, KbJob
|
||||
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
|
||||
from app.services.knowledge_cleaning.dify_sync_service import (
|
||||
KbDifySyncError,
|
||||
sync_document_version_to_dify,
|
||||
)
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
def _infer_missing_extension(source_path: Path) -> str:
|
||||
if zipfile.is_zipfile(source_path):
|
||||
try:
|
||||
with zipfile.ZipFile(source_path) as archive:
|
||||
names = archive.namelist()
|
||||
except Exception:
|
||||
names = []
|
||||
if any(name.startswith('xl/') for name in names):
|
||||
return '.xlsx'
|
||||
if any(name.startswith('word/') for name in names):
|
||||
return '.docx'
|
||||
if any(name.startswith('ppt/') for name in names):
|
||||
return '.pptx'
|
||||
return '.zip'
|
||||
|
||||
try:
|
||||
header = source_path.read_bytes()[:8]
|
||||
except Exception:
|
||||
return ''
|
||||
if header.startswith(b'\xd0\xcf\x11\xe0'):
|
||||
return '.xls'
|
||||
return ''
|
||||
|
||||
|
||||
def _normalized_source_filename(version: KbDocumentVersion, source_path: Path) -> str:
|
||||
raw_name = Path(version.source_file_name or source_path.name).name
|
||||
if Path(raw_name).suffix:
|
||||
return raw_name
|
||||
|
||||
ext = version.source_file_ext
|
||||
if ext:
|
||||
normalized_ext = ext if str(ext).startswith('.') else f'.{ext}'
|
||||
else:
|
||||
normalized_ext = _infer_missing_extension(source_path)
|
||||
|
||||
return f'{raw_name}{normalized_ext}' if normalized_ext else raw_name
|
||||
|
||||
|
||||
def _hash_file(source_path: Path) -> tuple[str, int]:
|
||||
sha = hashlib.sha256()
|
||||
size = 0
|
||||
with source_path.open('rb') as handle:
|
||||
while True:
|
||||
chunk = handle.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
sha.update(chunk)
|
||||
size += len(chunk)
|
||||
return sha.hexdigest(), size
|
||||
|
||||
|
||||
def _safe_storage_filename(filename: str) -> str:
|
||||
candidate = Path(filename or '').name.strip()
|
||||
if not candidate:
|
||||
return 'uploaded_file'
|
||||
safe_stem = secure_filename(Path(candidate).stem) or 'uploaded_file'
|
||||
suffix = Path(candidate).suffix.lower()
|
||||
return f'{safe_stem}{suffix}'
|
||||
|
||||
|
||||
def _safe_display_filename(filename: str) -> str:
|
||||
candidate = Path(filename or '').name.strip()
|
||||
if not candidate:
|
||||
return 'uploaded_file'
|
||||
invalid_chars = '\\/:*?"<>|'
|
||||
sanitized = ''.join('_' if ch in invalid_chars else ch for ch in candidate).strip()
|
||||
return sanitized or 'uploaded_file'
|
||||
|
||||
|
||||
def _kb_storage_root() -> Path:
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def _resolve_path_upload_display_name(relative_path: str, original_name: str) -> str:
|
||||
relative_name = Path(str(relative_path or '').replace('\\', '/')).name.strip()
|
||||
if relative_name:
|
||||
return relative_name
|
||||
original_leaf = Path(original_name or '').name.strip()
|
||||
if original_leaf:
|
||||
return original_leaf
|
||||
return 'uploaded_file'
|
||||
|
||||
|
||||
def _resolve_clean_display_filename(version: KbDocumentVersion, source_path: Path) -> str:
|
||||
document_title = _safe_display_filename(str(getattr(version.document, 'title', '') or ''))
|
||||
if document_title:
|
||||
title_path = Path(document_title)
|
||||
if title_path.suffix:
|
||||
return document_title
|
||||
normalized_source_name = _normalized_source_filename(version, source_path)
|
||||
source_suffix = Path(normalized_source_name).suffix
|
||||
return f'{document_title}{source_suffix}' if source_suffix else document_title
|
||||
return _safe_display_filename(_normalized_source_filename(version, source_path))
|
||||
|
||||
|
||||
def _normalize_markdown_title_candidate(value: str) -> str:
|
||||
text = str(value or '').strip()
|
||||
if not text:
|
||||
return ''
|
||||
if text.startswith('#'):
|
||||
text = text.lstrip('#').strip()
|
||||
return text
|
||||
|
||||
|
||||
def _rewrite_markdown_title(cleaned_file_path: str | None, *, preferred_title: str, fallback_source_name: str) -> None:
|
||||
if not cleaned_file_path:
|
||||
return
|
||||
cleaned_path = Path(cleaned_file_path)
|
||||
if cleaned_path.suffix.lower() != '.md' or not cleaned_path.exists():
|
||||
return
|
||||
|
||||
preferred_stem = Path(preferred_title or '').stem.strip()
|
||||
if not preferred_stem:
|
||||
return
|
||||
|
||||
fallback_candidates = {
|
||||
Path(fallback_source_name or '').stem.strip(),
|
||||
Path(cleaned_path.stem or '').stem.strip(),
|
||||
}
|
||||
fallback_candidates = {item for item in fallback_candidates if item}
|
||||
if not fallback_candidates:
|
||||
return
|
||||
|
||||
lines = cleaned_path.read_text(encoding='utf-8', errors='ignore').splitlines()
|
||||
for index, raw_line in enumerate(lines):
|
||||
stripped_line = raw_line.strip()
|
||||
if not stripped_line:
|
||||
continue
|
||||
normalized_line = _normalize_markdown_title_candidate(stripped_line)
|
||||
if normalized_line not in fallback_candidates or normalized_line == preferred_stem:
|
||||
return
|
||||
if stripped_line.startswith('#'):
|
||||
prefix = raw_line[: len(raw_line) - len(raw_line.lstrip())]
|
||||
heading_prefix = raw_line[len(prefix):].split(normalized_line, 1)[0]
|
||||
lines[index] = f'{prefix}{heading_prefix}{preferred_stem}'
|
||||
else:
|
||||
prefix = raw_line[: len(raw_line) - len(raw_line.lstrip())]
|
||||
lines[index] = f'{prefix}{preferred_stem}'
|
||||
cleaned_path.write_text('\n'.join(lines) + ('\n' if lines else ''), encoding='utf-8')
|
||||
return
|
||||
return
|
||||
|
||||
|
||||
def _get_or_create_document(*, group_id: int, title: str, description: str | None, user_id: int | None) -> KbDocument:
|
||||
document = (
|
||||
db.session.query(KbDocument)
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.title == title)
|
||||
.first()
|
||||
)
|
||||
if document and document.is_deleted:
|
||||
document.is_deleted = False
|
||||
if document:
|
||||
document.description = description
|
||||
document.updated_by_id = user_id
|
||||
return document
|
||||
|
||||
document = KbDocument(
|
||||
group_id=group_id,
|
||||
title=title,
|
||||
description=description,
|
||||
status='draft',
|
||||
source_type='upload',
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
return document
|
||||
|
||||
|
||||
def _find_existing_active_document(*, group_id: int, title: str) -> KbDocument | None:
|
||||
return (
|
||||
db.session.query(KbDocument)
|
||||
.filter(
|
||||
KbDocument.group_id == group_id,
|
||||
KbDocument.title == title,
|
||||
KbDocument.is_deleted.is_(False),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _next_version_no(document: KbDocument) -> int:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return 1
|
||||
return max(item.version_no for item in versions) + 1
|
||||
|
||||
|
||||
def _register_document_version_from_staged_file(
|
||||
*,
|
||||
group_id: int,
|
||||
relative_path: str,
|
||||
staged_path: Path,
|
||||
original_name: str,
|
||||
user_id: int | None,
|
||||
) -> tuple[KbDocument, KbDocumentVersion, KbJob]:
|
||||
display_name = _resolve_path_upload_display_name(relative_path, original_name)
|
||||
if _find_existing_active_document(group_id=group_id, title=display_name):
|
||||
raise FileExistsError('上传失败,文件已存在')
|
||||
document = _get_or_create_document(
|
||||
group_id=group_id,
|
||||
title=display_name,
|
||||
description=display_name,
|
||||
user_id=user_id,
|
||||
)
|
||||
version_no = _next_version_no(document)
|
||||
source_file_name = display_name
|
||||
stored_file_name = _safe_display_filename(display_name)
|
||||
ext = Path(source_file_name).suffix.lower().lstrip('.') or None
|
||||
version_dir = _kb_storage_root() / f'group_{group_id:04d}' / f'document_{document.id:06d}' / f'v{version_no:03d}'
|
||||
version_dir.mkdir(parents=True, exist_ok=True)
|
||||
target_path = version_dir / stored_file_name
|
||||
shutil.copy2(staged_path, target_path)
|
||||
sha256, file_size = _hash_file(target_path)
|
||||
|
||||
for existing in document.versions:
|
||||
if existing.is_current:
|
||||
existing.is_current = False
|
||||
|
||||
version = KbDocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=version_no,
|
||||
status='uploaded',
|
||||
is_current=True,
|
||||
source_file_name=source_file_name,
|
||||
source_file_path=str(target_path),
|
||||
source_file_ext=ext,
|
||||
source_file_size=file_size,
|
||||
sha256=sha256,
|
||||
uploaded_by_id=user_id,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
|
||||
document.source_type = 'upload'
|
||||
document.status = 'uploaded'
|
||||
document.updated_by_id = user_id
|
||||
|
||||
upload_job = KbJob(
|
||||
job_type='upload',
|
||||
status='success',
|
||||
group_id=group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=100,
|
||||
message=f'已通过上传路径导入文件:{relative_path}',
|
||||
payload_json={
|
||||
'source_file_name': source_file_name,
|
||||
'relative_path': relative_path,
|
||||
'source_file_size': file_size,
|
||||
},
|
||||
result_json={
|
||||
'sha256': sha256,
|
||||
'stored_path': str(target_path),
|
||||
},
|
||||
created_by_id=user_id,
|
||||
started_at=version.created_at,
|
||||
finished_at=version.created_at,
|
||||
)
|
||||
clean_job = KbJob(
|
||||
job_type='clean',
|
||||
status='queued',
|
||||
group_id=group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
message='等待清洗任务执行',
|
||||
payload_json={
|
||||
'document_version_id': version.id,
|
||||
'source_file_name': source_file_name,
|
||||
'relative_path': relative_path,
|
||||
},
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.session.add(upload_job)
|
||||
db.session.add(clean_job)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job
|
||||
|
||||
enqueue_clean_job(clean_job.id)
|
||||
return document, version, clean_job
|
||||
|
||||
|
||||
def run_path_upload_job(job_id: int) -> tuple[bool, str]:
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, '任务不存在'
|
||||
if job.job_type != 'path_upload':
|
||||
return False, '当前任务不是 path_upload 类型'
|
||||
|
||||
payload = dict(job.payload_json or {})
|
||||
items = list(payload.get('files') or [])
|
||||
total = max(int(payload.get('total_files') or len(items) or 0), 1)
|
||||
result = dict(job.result_json or {})
|
||||
result.setdefault('total', total)
|
||||
result.setdefault('success', 0)
|
||||
result.setdefault('failed', 0)
|
||||
result.setdefault('staged', len(items))
|
||||
|
||||
job.status = 'running'
|
||||
job.progress = min(job.progress or 0, 5)
|
||||
job.message = '后台开始批量导入上传路径文件'
|
||||
job.started_at = job.started_at or _utc_now()
|
||||
db.session.commit()
|
||||
|
||||
success_count = 0
|
||||
fail_count = 0
|
||||
processed = 0
|
||||
|
||||
for item in items:
|
||||
if item.get('status') in ('success', 'failed'):
|
||||
processed += 1
|
||||
if item.get('status') == 'success':
|
||||
success_count += 1
|
||||
else:
|
||||
fail_count += 1
|
||||
continue
|
||||
|
||||
staged_path = Path(str(item.get('staged_path') or ''))
|
||||
item['status'] = 'uploading'
|
||||
item['error'] = None
|
||||
payload['current_file'] = item.get('relative_path') or item.get('original_name')
|
||||
job.payload_json = payload
|
||||
job.message = f'正在导入:{payload["current_file"]}'
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
if not staged_path.exists():
|
||||
raise FileNotFoundError('暂存文件不存在')
|
||||
|
||||
document, version, _clean_job = _register_document_version_from_staged_file(
|
||||
group_id=job.group_id,
|
||||
relative_path=str(item.get('relative_path') or item.get('original_name') or staged_path.name),
|
||||
staged_path=staged_path,
|
||||
original_name=str(item.get('original_name') or staged_path.name),
|
||||
user_id=job.created_by_id,
|
||||
)
|
||||
item['status'] = 'success'
|
||||
item['document_id'] = document.id
|
||||
item['version_id'] = version.id
|
||||
item['error'] = None
|
||||
success_count += 1
|
||||
except Exception as exc:
|
||||
item['status'] = 'failed'
|
||||
item['error'] = str(exc)
|
||||
fail_count += 1
|
||||
|
||||
processed += 1
|
||||
result['success'] = success_count
|
||||
result['failed'] = fail_count
|
||||
result['processed'] = processed
|
||||
result['items'] = items
|
||||
job.payload_json = payload
|
||||
job.result_json = result
|
||||
job.progress = min(int(processed * 100 / total), 100)
|
||||
db.session.commit()
|
||||
|
||||
payload['current_file'] = ''
|
||||
job.payload_json = payload
|
||||
job.result_json = result
|
||||
job.progress = 100
|
||||
job.finished_at = _utc_now()
|
||||
if fail_count > 0:
|
||||
job.status = 'failed'
|
||||
job.message = f'路径上传完成,成功 {success_count} 条,失败 {fail_count} 条'
|
||||
job.error_message = f'部分文件上传失败:{fail_count} 条'
|
||||
db.session.commit()
|
||||
return False, 'partial_failed'
|
||||
|
||||
job.status = 'success'
|
||||
job.message = f'路径上传完成,成功 {success_count} 条'
|
||||
job.error_message = None
|
||||
db.session.commit()
|
||||
return True, 'ok'
|
||||
|
||||
|
||||
def _is_clean_timeout_error(exc: Exception) -> bool:
|
||||
"""判断清洗异常是否由 soffice / 子进程超时引起(与 soffice_util 错误文案对齐)。"""
|
||||
message = str(exc).lower()
|
||||
return 'timed out' in message or 'timeout' in message
|
||||
|
||||
|
||||
def run_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
"""
|
||||
第一版最小清洗任务执行器。
|
||||
当前先不接 edkb_system,只做以下动作:
|
||||
1. 把 queued 的 clean 任务改为 running/success;
|
||||
2. 为版本生成 cleaned_preview_path;
|
||||
3. 更新版本状态为 cleaned;
|
||||
4. 为下一步接真实清洗链路预留结构。
|
||||
"""
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, '任务不存在'
|
||||
if job.job_type != 'clean':
|
||||
return False, '当前任务不是 clean 类型'
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id)
|
||||
if not version:
|
||||
job.status = 'failed'
|
||||
job.error_message = '关联文档版本不存在'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, '关联文档版本不存在'
|
||||
|
||||
source_path = Path(version.source_file_path)
|
||||
if not source_path.exists():
|
||||
job.status = 'failed'
|
||||
job.error_message = '原始文件不存在,无法执行 clean'
|
||||
version.status = 'failed'
|
||||
version.error_message = '原始文件不存在,无法执行 clean'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, '原始文件不存在'
|
||||
|
||||
job.status = 'running'
|
||||
job.progress = 20
|
||||
job.message = '开始执行最小清洗任务'
|
||||
job.started_at = _utc_now()
|
||||
version.status = 'processing'
|
||||
db.session.commit()
|
||||
|
||||
target_dir = source_path.parent
|
||||
warnings = []
|
||||
|
||||
try:
|
||||
normalized_name = _resolve_clean_display_filename(version, source_path)
|
||||
staged_source = target_dir / normalized_name
|
||||
if staged_source != source_path:
|
||||
shutil.copy2(source_path, staged_source)
|
||||
source_path = staged_source
|
||||
|
||||
result = build_clean_result(source_path, target_dir)
|
||||
_rewrite_markdown_title(
|
||||
result.get('cleaned_file_path'),
|
||||
preferred_title=str(getattr(version.document, 'title', '') or ''),
|
||||
fallback_source_name=str(version.source_file_name or source_path.name),
|
||||
)
|
||||
job_message = '真实清洗结果已生成'
|
||||
except Exception as exc:
|
||||
# soffice 超时等不可恢复错误:直接失败,避免回退占位结果掩盖问题
|
||||
if _is_clean_timeout_error(exc):
|
||||
job.status = 'failed'
|
||||
job.progress = 100
|
||||
job.message = '清洗超时'
|
||||
job.error_message = str(exc)
|
||||
job.finished_at = _utc_now()
|
||||
version.status = 'failed'
|
||||
version.error_message = str(exc)
|
||||
db.session.commit()
|
||||
return False, 'timeout'
|
||||
|
||||
preview_path = target_dir / f'{_normalized_source_filename(version, source_path)}.preview.txt'
|
||||
preview_path.write_text(
|
||||
'\n'.join([
|
||||
f'source_file={source_path.name}',
|
||||
f'source_size={version.source_file_size or 0}',
|
||||
'clean_status=placeholder_success',
|
||||
f'fallback_reason={str(exc)}',
|
||||
]),
|
||||
encoding='utf-8',
|
||||
)
|
||||
result = {
|
||||
'mode': 'placeholder_clean',
|
||||
'cleaned_file_path': None,
|
||||
'cleaned_preview_path': str(preview_path),
|
||||
'word_count': 0,
|
||||
}
|
||||
warnings.append({'message': f'edkb_fallback={str(exc)}'})
|
||||
job_message = 'edkb_system 未就绪,已回退到占位清洗结果'
|
||||
|
||||
version.cleaned_file_path = result.get('cleaned_file_path')
|
||||
version.cleaned_preview_path = result.get('cleaned_preview_path')
|
||||
version.word_count = int(result.get('word_count') or 0)
|
||||
version.status = 'cleaned'
|
||||
version.converted_at = _utc_now()
|
||||
version.error_message = None
|
||||
version.warnings_json = warnings or None
|
||||
if version.document:
|
||||
version.document.status = 'ready'
|
||||
|
||||
job.status = 'success'
|
||||
job.progress = 100
|
||||
job.message = job_message
|
||||
job.error_message = None
|
||||
job.result_json = result
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
|
||||
return True, 'ok'
|
||||
|
||||
|
||||
def run_sync_job(job_id: int) -> tuple[bool, str]:
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, '任务不存在'
|
||||
if job.job_type != 'sync_dify':
|
||||
return False, '当前任务不是 sync_dify 类型'
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id)
|
||||
if not version:
|
||||
job.status = 'failed'
|
||||
job.error_message = '关联文档版本不存在'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, '关联文档版本不存在'
|
||||
|
||||
job.status = 'running'
|
||||
job.progress = 20
|
||||
job.message = '开始同步到 Dify'
|
||||
job.started_at = _utc_now()
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
result = sync_document_version_to_dify(version.id, synced_by_id=job.created_by_id)
|
||||
except KbDifySyncError as exc:
|
||||
version.status = 'ready'
|
||||
job.status = 'failed'
|
||||
job.progress = 100
|
||||
job.error_message = str(exc)
|
||||
job.message = '同步到 Dify 失败'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, str(exc)
|
||||
except Exception as exc:
|
||||
version.status = 'ready'
|
||||
job.status = 'failed'
|
||||
job.progress = 100
|
||||
job.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
|
||||
job.message = '同步到 Dify 失败'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, str(exc)
|
||||
|
||||
version.status = 'synced'
|
||||
job.status = 'success'
|
||||
job.progress = 100
|
||||
job.message = '已同步到 Dify'
|
||||
job.error_message = None
|
||||
job.result_json = result
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return True, 'ok'
|
||||
@@ -0,0 +1,97 @@
|
||||
import os
|
||||
import uuid
|
||||
from typing import BinaryIO
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
from werkzeug.utils import secure_filename
|
||||
from app.config import config, ACTIVE_ENV_NAME
|
||||
|
||||
cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
class MinioService:
|
||||
def __init__(self):
|
||||
self.client = Minio(
|
||||
cfg.MINIO_ENDPOINT,
|
||||
access_key=cfg.MINIO_ACCESS_KEY,
|
||||
secret_key=cfg.MINIO_SECRET_KEY,
|
||||
secure=cfg.MINIO_SECURE,
|
||||
)
|
||||
self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET
|
||||
self._ensure_bucket_exists()
|
||||
|
||||
def _ensure_bucket_exists(self):
|
||||
try:
|
||||
if not self.client.bucket_exists(self.bucket_name):
|
||||
self.client.make_bucket(self.bucket_name)
|
||||
# Set bucket policy to public read
|
||||
policy = {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Principal": {"AWS": ["*"]},
|
||||
"Action": ["s3:GetObject"],
|
||||
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
import json
|
||||
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
|
||||
except Exception as e:
|
||||
# log or print error
|
||||
print(f"MinIO bucket error (or not reachable): {e}")
|
||||
|
||||
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
|
||||
"""
|
||||
Uploads a file to MinIO and returns the generated object name.
|
||||
"""
|
||||
# If MinIO is not running, we could fallback to local storage or raise clear error
|
||||
try:
|
||||
self._ensure_bucket_exists()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ext = os.path.splitext(filename)[1]
|
||||
unique_filename = f"{uuid.uuid4().hex}{ext}"
|
||||
|
||||
try:
|
||||
self.client.put_object(
|
||||
bucket_name=self.bucket_name,
|
||||
object_name=unique_filename,
|
||||
data=file_stream,
|
||||
length=file_size,
|
||||
content_type=content_type
|
||||
)
|
||||
except Exception as e:
|
||||
# For development, if minio is down, let's mock it so UI can continue
|
||||
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
|
||||
|
||||
# fallback to local storage
|
||||
os.makedirs('data/agent-guides', exist_ok=True)
|
||||
local_path = os.path.join('data/agent-guides', unique_filename)
|
||||
file_stream.seek(0)
|
||||
with open(local_path, 'wb') as f:
|
||||
f.write(file_stream.read())
|
||||
|
||||
return unique_filename
|
||||
|
||||
def get_public_url(self, object_name: str) -> str:
|
||||
"""
|
||||
Returns the public URL for the given object name.
|
||||
"""
|
||||
if os.path.exists(os.path.join('data/agent-guides', object_name)):
|
||||
# It's a local fallback file
|
||||
# the backend needs a static route to serve this, we'll assume /api/agents/guides/files/<object_name>
|
||||
# but since we want it public without auth:
|
||||
return f"/api/agents/guides/files/{object_name}"
|
||||
|
||||
base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/')
|
||||
return f"{base_url}/{self.bucket_name}/{object_name}"
|
||||
|
||||
def delete_file(self, object_name: str):
|
||||
try:
|
||||
self.client.remove_object(self.bucket_name, object_name)
|
||||
except S3Error as e:
|
||||
print(f"Error deleting file from MinIO: {e}")
|
||||
|
||||
minio_service = MinioService()
|
||||
@@ -0,0 +1,456 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
import os
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
|
||||
SOAP_ENV_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
|
||||
SERVICE_NS = 'webservices.services.weaver.com.cn'
|
||||
WORKFLOW_NS = 'http://webservices.workflow.weaver'
|
||||
XSI_NS = 'http://www.w3.org/2001/XMLSchema-instance'
|
||||
|
||||
NS = {
|
||||
'soapenv': SOAP_ENV_NS,
|
||||
'svc': SERVICE_NS,
|
||||
'wf': WORKFLOW_NS,
|
||||
'xsi': XSI_NS,
|
||||
}
|
||||
|
||||
ET.register_namespace('soapenv', SOAP_ENV_NS)
|
||||
ET.register_namespace('svc', SERVICE_NS)
|
||||
ET.register_namespace('wf', WORKFLOW_NS)
|
||||
ET.register_namespace('xsi', XSI_NS)
|
||||
|
||||
|
||||
class OALeaveWorkflowError(RuntimeError):
|
||||
"""Raised when OA leave workflow submission fails."""
|
||||
|
||||
|
||||
class OALeaveWorkflowService:
|
||||
WORKFLOW_ID = '879'
|
||||
OA_USER_MAP = {
|
||||
'26030025': {'user_id': '21784', 'name': '梁春艳'},
|
||||
'26040006': {'user_id': '21823', 'name': '刘义亮'},
|
||||
}
|
||||
# Keep backend leave labels aligned with the chat form options so OA browser
|
||||
# fields always receive the expected showValue instead of a raw code.
|
||||
LEAVE_TYPE_LABELS = {
|
||||
'005': '事假(小时)',
|
||||
'006': '病假(小时)',
|
||||
'007': '丧假(天)',
|
||||
'010': '年假(天)',
|
||||
'021': '因公出差(小时)',
|
||||
'025': '调休假(小时)',
|
||||
'035': '其他假(小时)',
|
||||
'401': '产假(天)',
|
||||
'402': '陪产假(天)',
|
||||
'403': '婚假(天)',
|
||||
'405': '住院病假(小时)',
|
||||
'406': '工伤假(天)',
|
||||
'408': '育儿假(小时)',
|
||||
'ZZ01': '返乡假(小时)',
|
||||
'ZZ04': '事假(经理专用小时)',
|
||||
'ZZ05': '病假(经理专用小时)',
|
||||
'ZZ07': '丧假(经理专用天)',
|
||||
'ZZ08': '产假(经理专用天)',
|
||||
'ZZ09': '陪产假(经理专用天)',
|
||||
'ZZ10': '婚假(经理专用天)',
|
||||
}
|
||||
ERROR_MESSAGES = {
|
||||
'-1': '创建流程失败',
|
||||
'-2': '用户没有流程创建权限',
|
||||
'-3': '创建流程基本信息失败',
|
||||
'-4': '保存表单主表信息失败',
|
||||
'-5': '更新紧急程度失败',
|
||||
'-6': '流程操作者失败',
|
||||
'-7': '流转至下一节点失败',
|
||||
'-8': '节点附加操作失败',
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_wsdl_url(cls) -> str:
|
||||
return (
|
||||
current_app.config.get('OA_WORKFLOW_WSDL_URL')
|
||||
or os.getenv('OA_WORKFLOW_WSDL_URL')
|
||||
or 'http://oa.well-trust.com:8888/services/WorkflowService?wsdl'
|
||||
).strip()
|
||||
|
||||
@classmethod
|
||||
def _get_service_url(cls) -> str:
|
||||
wsdl_url = cls._get_wsdl_url()
|
||||
return wsdl_url[:-5] if wsdl_url.lower().endswith('?wsdl') else wsdl_url
|
||||
|
||||
@classmethod
|
||||
def _request_timeout(cls) -> tuple[int, int]:
|
||||
return (5, 25)
|
||||
|
||||
@classmethod
|
||||
def _post_soap(cls, action: str, body_el: ET.Element) -> ET.Element:
|
||||
envelope = ET.Element(f'{{{SOAP_ENV_NS}}}Envelope')
|
||||
ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Header')
|
||||
body = ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Body')
|
||||
body.append(body_el)
|
||||
payload = ET.tostring(envelope, encoding='utf-8', xml_declaration=True)
|
||||
headers = {
|
||||
'Content-Type': 'text/xml; charset=utf-8',
|
||||
'SOAPAction': action,
|
||||
}
|
||||
max_retries = 3
|
||||
last_exc = None
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
response = requests.post(
|
||||
cls._get_service_url(),
|
||||
data=payload,
|
||||
headers=headers,
|
||||
timeout=cls._request_timeout(),
|
||||
)
|
||||
response.raise_for_status()
|
||||
return ET.fromstring(response.text)
|
||||
except requests.RequestException as exc:
|
||||
last_exc = exc
|
||||
status_code = getattr(getattr(exc, 'response', None), 'status_code', None)
|
||||
retryable = status_code in (502, 503, 504) if status_code else True
|
||||
if retryable and attempt < max_retries:
|
||||
import time
|
||||
wait = attempt * 2
|
||||
current_app.logger.warning(
|
||||
'[oa-leave] SOAP request failed (attempt %d/%d, status=%s), retrying in %ds: %s',
|
||||
attempt, max_retries, status_code, wait, exc,
|
||||
)
|
||||
time.sleep(wait)
|
||||
continue
|
||||
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
|
||||
except ET.ParseError as exc:
|
||||
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
|
||||
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
|
||||
|
||||
@classmethod
|
||||
def resolve_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
employee_id = (employee_id or '').strip()
|
||||
if not employee_id:
|
||||
raise OALeaveWorkflowError('缺少员工工号,无法匹配 OA 用户。')
|
||||
matched = cls.OA_USER_MAP.get(employee_id)
|
||||
if not matched:
|
||||
raise OALeaveWorkflowError(f'工号 {employee_id} 暂未配置 OA userid 映射。')
|
||||
return {
|
||||
'employee_id': employee_id,
|
||||
'user_id': matched['user_id'],
|
||||
'name': (real_name or matched.get('name') or '').strip() or matched['name'],
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def resolve_creator_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='请假人')
|
||||
|
||||
@classmethod
|
||||
def resolve_agent_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='代理人')
|
||||
|
||||
@classmethod
|
||||
def _resolve_runtime_oa_user(
|
||||
cls,
|
||||
employee_id: str | None,
|
||||
real_name: str | None = None,
|
||||
*,
|
||||
role_label: str,
|
||||
) -> dict[str, str]:
|
||||
employee_id = (employee_id or '').strip()
|
||||
real_name = (real_name or '').strip()
|
||||
if not employee_id:
|
||||
raise OALeaveWorkflowError(f'缺少{role_label}工号,无法匹配 OA 用户。')
|
||||
if not real_name:
|
||||
raise OALeaveWorkflowError(f'缺少{role_label}姓名,无法匹配 OA 用户。')
|
||||
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
matched = OASQLServerService.get_employee_by_name_and_workcode(real_name, employee_id)
|
||||
except Exception as exc:
|
||||
raise OALeaveWorkflowError(f'查询{role_label} OA 用户失败:{exc}') from exc
|
||||
|
||||
if not matched:
|
||||
raise OALeaveWorkflowError(f'未找到{role_label} OA 用户:{real_name}({employee_id})。')
|
||||
|
||||
return {
|
||||
'employee_id': matched['employeeId'],
|
||||
'user_id': matched['uid'],
|
||||
'name': matched['name'],
|
||||
'jobtitle': matched.get('jobtitle', ''),
|
||||
'jobtitleName': matched.get('jobtitleName', ''),
|
||||
'departmentid': matched.get('departmentid', ''),
|
||||
'departmentName': matched.get('departmentName', ''),
|
||||
'subcompanyid1': matched.get('subcompanyid1', ''),
|
||||
'subcompanyName': matched.get('subcompanyName', ''),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _pick_browser_field_value(*values: Any) -> str:
|
||||
for value in values:
|
||||
text = ('' if value is None else str(value)).strip()
|
||||
if text:
|
||||
return text
|
||||
return ''
|
||||
|
||||
@classmethod
|
||||
def _build_get_template_body(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
|
||||
root = ET.Element(f'{{{SERVICE_NS}}}getCreateWorkflowRequestInfo')
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in0').text = str(workflow_id)
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _get_template_request_info(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
|
||||
action = 'urn:weaver.workflow.webservices.WorkflowService.getCreateWorkflowRequestInfo'
|
||||
root = cls._post_soap(action, cls._build_get_template_body(workflow_id, oa_user_id))
|
||||
out = root.find('.//svc:out', NS)
|
||||
if out is None or out.attrib.get(f'{{{XSI_NS}}}nil') == 'true' or len(list(out)) == 0:
|
||||
raise OALeaveWorkflowError('OA 未返回建单模板,请确认 workflowId 与 OA userid 是否正确。')
|
||||
return deepcopy(out)
|
||||
|
||||
@classmethod
|
||||
def _find_field(cls, request_info: ET.Element, field_name: str) -> ET.Element | None:
|
||||
for field in request_info.findall('.//wf:WorkflowRequestTableField', NS):
|
||||
if (field.findtext('wf:fieldName', default='', namespaces=NS) or '').strip() == field_name:
|
||||
return field
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _set_field(
|
||||
cls,
|
||||
request_info: ET.Element,
|
||||
field_name: str,
|
||||
*,
|
||||
value: str | None,
|
||||
show_value: str | None = None,
|
||||
) -> None:
|
||||
field = cls._find_field(request_info, field_name)
|
||||
if field is None:
|
||||
current_app.logger.warning('[oa-leave] field not found in template: %s', field_name)
|
||||
return
|
||||
value_node = field.find('wf:fieldValue', NS)
|
||||
if value_node is None:
|
||||
value_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldValue')
|
||||
value_node.text = '' if value is None else str(value)
|
||||
|
||||
if show_value is not None:
|
||||
show_node = field.find('wf:fieldShowValue', NS)
|
||||
if show_node is None:
|
||||
show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue')
|
||||
show_node.text = str(show_value)
|
||||
|
||||
field_html_type = (field.findtext('wf:fieldHtmlType', default='', namespaces=NS) or '').strip()
|
||||
if field_html_type == '3':
|
||||
filed_html_node = field.find('wf:filedHtmlShow', NS)
|
||||
if filed_html_node is not None:
|
||||
filed_html_node.text = str(show_value)
|
||||
|
||||
for tag in ['edit', 'view']:
|
||||
node = field.find(f'wf:{tag}', NS)
|
||||
if node is not None:
|
||||
node.text = 'true'
|
||||
else:
|
||||
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
|
||||
node.text = 'true'
|
||||
|
||||
@classmethod
|
||||
def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None:
|
||||
node = parent.find(xpath, NS)
|
||||
if node is not None:
|
||||
node.text = value
|
||||
|
||||
@classmethod
|
||||
def _parse_frontend_datetime(cls, raw: str, field_name: str) -> datetime:
|
||||
text = (raw or '').strip().replace('T', ' ')
|
||||
try:
|
||||
return datetime.strptime(text, '%Y-%m-%d %H:%M')
|
||||
except ValueError as exc:
|
||||
raise OALeaveWorkflowError(f'{field_name} 格式不正确,应为 YYYY-MM-DD HH:MM。') from exc
|
||||
|
||||
@classmethod
|
||||
def _build_request_name(cls, creator_name: str, start_dt: datetime) -> str:
|
||||
return f'请假申请单-{creator_name}-{start_dt.strftime("%Y-%m-%d")}'
|
||||
|
||||
@classmethod
|
||||
def _normalize_duration(cls, value: Any) -> str:
|
||||
try:
|
||||
hours = float(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise OALeaveWorkflowError('请假时长格式不正确。') from exc
|
||||
if hours <= 0:
|
||||
raise OALeaveWorkflowError('请假时长必须大于 0。')
|
||||
return f'{hours:.2f}'.rstrip('0').rstrip('.')
|
||||
|
||||
@classmethod
|
||||
def build_request_info(cls, form_data: dict[str, Any], current_user: Any) -> tuple[ET.Element, dict[str, str], dict[str, str], dict[str, str]]:
|
||||
filler_name = (
|
||||
form_data.get('fillerName')
|
||||
or getattr(current_user, 'real_name', None)
|
||||
or getattr(current_user, 'username', None)
|
||||
or '当前用户'
|
||||
)
|
||||
filler = cls._resolve_runtime_oa_user(
|
||||
getattr(current_user, 'employee_id', None),
|
||||
filler_name,
|
||||
role_label='填单人'
|
||||
)
|
||||
|
||||
applicant_name = (
|
||||
form_data.get('applicantName')
|
||||
or getattr(current_user, 'real_name', None)
|
||||
or getattr(current_user, 'username', None)
|
||||
or '当前用户'
|
||||
)
|
||||
applicant = cls.resolve_creator_oa_user(
|
||||
form_data.get('employeeId') or getattr(current_user, 'employee_id', None),
|
||||
applicant_name,
|
||||
)
|
||||
agent = cls.resolve_agent_oa_user(form_data.get('agentEmployeeId'), form_data.get('agentName'))
|
||||
|
||||
workflow_id = str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID)
|
||||
request_info = cls._get_template_request_info(workflow_id, filler['user_id'])
|
||||
|
||||
start_dt = cls._parse_frontend_datetime(form_data.get('startTime'), '开始时间')
|
||||
end_dt = cls._parse_frontend_datetime(form_data.get('endTime'), '结束时间')
|
||||
if end_dt <= start_dt:
|
||||
raise OALeaveWorkflowError('结束时间必须晚于开始时间。')
|
||||
|
||||
leave_type_code = (form_data.get('leaveType') or '').strip()
|
||||
if not leave_type_code:
|
||||
raise OALeaveWorkflowError('缺少假别编码。')
|
||||
leave_type_label = cls.LEAVE_TYPE_LABELS.get(leave_type_code, leave_type_code)
|
||||
request_name = cls._build_request_name(applicant['name'], start_dt)
|
||||
|
||||
cls._set_text(request_info, 'wf:creatorId', filler['user_id'])
|
||||
cls._set_text(request_info, 'wf:creatorName', filler['name'])
|
||||
cls._set_text(request_info, 'wf:requestLevel', '0')
|
||||
cls._set_text(request_info, 'wf:requestName', request_name)
|
||||
cls._set_text(request_info, './/wf:workflowBaseInfo/wf:workflowId', workflow_id)
|
||||
|
||||
cls._set_field(request_info, 'requestname', value=request_name, show_value=request_name)
|
||||
cls._set_field(request_info, 'tdrgh', value=filler['employee_id'])
|
||||
cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'])
|
||||
cls._set_field(request_info, 'tdrxm', value=filler['user_id'], show_value=filler['name'])
|
||||
cls._set_field(request_info, 'sqrxm', value=applicant['user_id'], show_value=applicant['name'])
|
||||
|
||||
filler_jobtitle = cls._pick_browser_field_value(filler.get('jobtitle'), form_data.get('fillerJobTitle'))
|
||||
filler_jobtitle_name = cls._pick_browser_field_value(filler.get('jobtitleName'))
|
||||
filler_department = cls._pick_browser_field_value(filler.get('departmentid'), form_data.get('fillerDepartmentId'))
|
||||
filler_department_name = cls._pick_browser_field_value(filler.get('departmentName'))
|
||||
filler_subcompany = cls._pick_browser_field_value(filler.get('subcompanyid1'), form_data.get('fillerSubCompanyId1'))
|
||||
filler_subcompany_name = cls._pick_browser_field_value(filler.get('subcompanyName'))
|
||||
applicant_jobtitle = cls._pick_browser_field_value(applicant.get('jobtitle'), form_data.get('applicantJobTitle'))
|
||||
applicant_jobtitle_name = cls._pick_browser_field_value(applicant.get('jobtitleName'))
|
||||
applicant_department = cls._pick_browser_field_value(applicant.get('departmentid'), form_data.get('applicantDepartmentId'))
|
||||
applicant_department_name = cls._pick_browser_field_value(applicant.get('departmentName'))
|
||||
applicant_subcompany = cls._pick_browser_field_value(applicant.get('subcompanyid1'), form_data.get('applicantSubCompanyId1'))
|
||||
applicant_subcompany_name = cls._pick_browser_field_value(applicant.get('subcompanyName'))
|
||||
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
if filler_jobtitle and not filler_jobtitle_name:
|
||||
filler_jobtitle_name = OASQLServerService.get_jobtitle_name(filler_jobtitle)
|
||||
if filler_department and not filler_department_name:
|
||||
filler_department_name = OASQLServerService.get_department_name(filler_department)
|
||||
if filler_subcompany and not filler_subcompany_name:
|
||||
filler_subcompany_name = OASQLServerService.get_subcompany_name(filler_subcompany)
|
||||
if applicant_jobtitle and not applicant_jobtitle_name:
|
||||
applicant_jobtitle_name = OASQLServerService.get_jobtitle_name(applicant_jobtitle)
|
||||
if applicant_department and not applicant_department_name:
|
||||
applicant_department_name = OASQLServerService.get_department_name(applicant_department)
|
||||
if applicant_subcompany and not applicant_subcompany_name:
|
||||
applicant_subcompany_name = OASQLServerService.get_subcompany_name(applicant_subcompany)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cls._set_field(request_info, 'tdrzw', value=filler_jobtitle, show_value=filler_jobtitle_name or filler_jobtitle or '暂无')
|
||||
cls._set_field(request_info, 'tdrbm', value=filler_department, show_value=filler_department_name or filler_department or '暂无')
|
||||
cls._set_field(request_info, 'tdrgs', value=filler_subcompany, show_value=filler_subcompany_name or filler_subcompany or '暂无')
|
||||
cls._set_field(request_info, 'sqrzw', value=applicant_jobtitle, show_value=applicant_jobtitle_name or applicant_jobtitle or '暂无')
|
||||
cls._set_field(request_info, 'sqrbm', value=applicant_department, show_value=applicant_department_name or applicant_department or '暂无')
|
||||
cls._set_field(request_info, 'sqrgs', value=applicant_subcompany, show_value=applicant_subcompany_name or applicant_subcompany or '暂无')
|
||||
|
||||
current_app.logger.info(
|
||||
'[oa-leave] field values: tdrzw=%s/%s tdrbm=%s/%s tdrgs=%s/%s sqrzw=%s/%s sqrbm=%s/%s sqrgs=%s/%s',
|
||||
filler_jobtitle, filler_jobtitle_name or filler_jobtitle or '暂无',
|
||||
filler_department, filler_department_name or filler_department or '暂无',
|
||||
filler_subcompany, filler_subcompany_name or filler_subcompany or '暂无',
|
||||
applicant_jobtitle, applicant_jobtitle_name or applicant_jobtitle or '暂无',
|
||||
applicant_department, applicant_department_name or applicant_department or '暂无',
|
||||
applicant_subcompany, applicant_subcompany_name or applicant_subcompany or '暂无',
|
||||
)
|
||||
|
||||
cls._set_field(request_info, 'dlrgh', value=agent['employee_id'])
|
||||
cls._set_field(request_info, 'dlrxm', value=agent['user_id'], show_value=agent['name'])
|
||||
cls._set_field(request_info, 'dlrlogid', value=agent['user_id'], show_value=agent['user_id'])
|
||||
cls._set_field(request_info, 'jb', value=leave_type_code, show_value=leave_type_label)
|
||||
cls._set_field(request_info, 'jbbh', value=leave_type_code, show_value=leave_type_code)
|
||||
cls._set_field(request_info, 'kssj', value=start_dt.strftime('%Y-%m-%d'), show_value=start_dt.strftime('%Y-%m-%d'))
|
||||
cls._set_field(request_info, 'kssk', value=start_dt.strftime('%H:%M'), show_value=start_dt.strftime('%H:%M'))
|
||||
cls._set_field(request_info, 'jssj', value=end_dt.strftime('%Y-%m-%d'), show_value=end_dt.strftime('%Y-%m-%d'))
|
||||
cls._set_field(request_info, 'jssk', value=end_dt.strftime('%H:%M'), show_value=end_dt.strftime('%H:%M'))
|
||||
cls._set_field(request_info, 'qjsc', value=cls._normalize_duration(form_data.get('durationHours')), show_value=cls._normalize_duration(form_data.get('durationHours')))
|
||||
cls._set_field(request_info, 'sfwgs', value=str(form_data.get('isWorkInjury')), show_value='是' if str(form_data.get('isWorkInjury')) == '0' else '否')
|
||||
cls._set_field(request_info, 'sfwc', value=str(form_data.get('isOutOfOffice')), show_value='是' if str(form_data.get('isOutOfOffice')) == '0' else '否')
|
||||
cls._set_field(request_info, 'bz', value=(form_data.get('remark') or '').strip(), show_value=(form_data.get('remark') or '').strip())
|
||||
|
||||
return request_info, filler, applicant, agent
|
||||
|
||||
@classmethod
|
||||
def _build_create_body(cls, request_info: ET.Element, oa_user_id: str) -> ET.Element:
|
||||
root = ET.Element(f'{{{SERVICE_NS}}}doCreateWorkflowRequest')
|
||||
in0 = deepcopy(request_info)
|
||||
in0.tag = f'{{{SERVICE_NS}}}in0'
|
||||
root.append(in0)
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _parse_create_response(cls, root: ET.Element) -> str:
|
||||
out = root.findtext('.//svc:out', default='', namespaces=NS)
|
||||
out = (out or '').strip()
|
||||
if not out:
|
||||
raise OALeaveWorkflowError('OA 未返回单据编号。')
|
||||
if out in cls.ERROR_MESSAGES:
|
||||
raise OALeaveWorkflowError(cls.ERROR_MESSAGES[out])
|
||||
if out.startswith('-'):
|
||||
raise OALeaveWorkflowError(f'OA 创建流程失败,返回码:{out}')
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def serialize_request_xml(cls, request_info: ET.Element) -> str:
|
||||
return ET.tostring(request_info, encoding='unicode')
|
||||
|
||||
@classmethod
|
||||
def submit_leave_request(cls, form_data: dict[str, Any], current_user: Any) -> dict[str, Any]:
|
||||
request_info, filler, applicant, agent = cls.build_request_info(form_data, current_user)
|
||||
|
||||
log_fields = ['tdrzw', 'tdrbm', 'tdrgs', 'sqrzw', 'sqrbm', 'sqrgs', 'qjsc', 'tdrgh', 'sqrgh']
|
||||
for fn in log_fields:
|
||||
f = cls._find_field(request_info, fn)
|
||||
if f is not None:
|
||||
fv = f.findtext('wf:fieldValue', default='', namespaces=NS)
|
||||
fsv = f.findtext('wf:fieldShowValue', default='', namespaces=NS)
|
||||
fe = f.findtext('wf:edit', default='(removed)', namespaces=NS)
|
||||
current_app.logger.info('[oa-leave] PUSH field %s: value=%s showValue=%s edit=%s', fn, fv, fsv, fe)
|
||||
|
||||
action = 'urn:weaver.workflow.webservices.WorkflowService.doCreateWorkflowRequest'
|
||||
root = cls._post_soap(action, cls._build_create_body(request_info, filler['user_id']))
|
||||
request_id = cls._parse_create_response(root)
|
||||
current_app.logger.info('[oa-leave] OA response request_id=%s', request_id)
|
||||
return {
|
||||
'ok': True,
|
||||
'request_id': request_id,
|
||||
'request_name': request_info.findtext('wf:requestName', default='', namespaces=NS),
|
||||
'submitted_at': datetime.now().strftime('%Y-%m-%d %H:%M'),
|
||||
'creator': applicant,
|
||||
'filler': filler,
|
||||
'agent': agent,
|
||||
'workflow_id': str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID),
|
||||
'request_xml': cls.serialize_request_xml(request_info),
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
import os
|
||||
import pyodbc
|
||||
from flask import current_app
|
||||
|
||||
class OASQLServerService:
|
||||
@staticmethod
|
||||
def _pick_driver():
|
||||
drivers = pyodbc.drivers()
|
||||
preferred = [
|
||||
"ODBC Driver 18 for SQL Server",
|
||||
"ODBC Driver 17 for SQL Server",
|
||||
"SQL Server",
|
||||
]
|
||||
for name in preferred:
|
||||
if name in drivers:
|
||||
return name
|
||||
if not drivers:
|
||||
raise RuntimeError("未找到可用的 SQL Server ODBC 驱动")
|
||||
return drivers[-1]
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
driver = os.getenv("OA_SQLSERVER_DRIVER", "").strip() or cls._pick_driver()
|
||||
available_drivers = pyodbc.drivers()
|
||||
if driver not in available_drivers:
|
||||
driver = cls._pick_driver()
|
||||
server = os.getenv("OA_SQLSERVER_HOST", "192.168.100.225").strip()
|
||||
port = os.getenv("OA_SQLSERVER_PORT", "1433").strip()
|
||||
database = os.getenv("OA_SQLSERVER_DATABASE", "ecology").strip()
|
||||
username = os.getenv("OA_SQLSERVER_USERNAME", "AI_Knowledge_Base_OA").strip()
|
||||
password = os.getenv("OA_SQLSERVER_PASSWORD", "hoo-thai@123_AI_OA").strip()
|
||||
encrypt = os.getenv("OA_SQLSERVER_ENCRYPT", "no").strip().lower()
|
||||
trust_cert = os.getenv("OA_SQLSERVER_TRUST_CERT", "yes").strip().lower()
|
||||
timeout = int(os.getenv("OA_SQLSERVER_TIMEOUT", "10"))
|
||||
|
||||
conn_str = (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={server},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
)
|
||||
if driver != "SQL Server":
|
||||
conn_str += (
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
return pyodbc.connect(conn_str, timeout=timeout)
|
||||
|
||||
@classmethod
|
||||
def search_employees(cls, keyword: str, page: int, page_size: int):
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
offset = (page - 1) * page_size
|
||||
params = []
|
||||
|
||||
# Count total
|
||||
count_sql = "SELECT COUNT(1) FROM userInfo_view WHERE 1=1"
|
||||
if keyword:
|
||||
count_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
||||
like_kw = f"%{keyword}%"
|
||||
params.extend([like_kw, like_kw])
|
||||
|
||||
cursor.execute(count_sql, params)
|
||||
total = cursor.fetchone()[0]
|
||||
|
||||
# Fetch page
|
||||
# Compatible with older SQL Server versions (2008/2012)
|
||||
query_sql = """
|
||||
SELECT id, workcode, lastname, jobtitle, departmentid, subcompanyid1,
|
||||
departmentname, subcompanyname, jobtitlename
|
||||
FROM (
|
||||
SELECT v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
|
||||
d.departmentname, s.subcompanyname, j.jobtitlename,
|
||||
ROW_NUMBER() OVER(ORDER BY v.id) as rn
|
||||
FROM userInfo_view v
|
||||
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
|
||||
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
|
||||
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
|
||||
WHERE 1=1
|
||||
"""
|
||||
if keyword:
|
||||
query_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
||||
|
||||
query_sql += """
|
||||
) as T
|
||||
WHERE rn > ? AND rn <= ?
|
||||
"""
|
||||
|
||||
page_params = params + [offset, offset + page_size]
|
||||
cursor.execute(query_sql, page_params)
|
||||
|
||||
items = []
|
||||
for row in cursor.fetchall():
|
||||
items.append({
|
||||
"uid": str(row.id) if row.id is not None else "",
|
||||
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
||||
"name": str(row.lastname) if row.lastname is not None else "",
|
||||
"jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
|
||||
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
||||
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
||||
"departmentName": str(row.departmentname).strip() if row.departmentname else "",
|
||||
"subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
|
||||
"jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
|
||||
})
|
||||
|
||||
return {
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_employee_by_name_and_workcode(cls, real_name: str, employee_id: str):
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
normalized_name = (real_name or "").strip()
|
||||
normalized_employee_id = (employee_id or "").strip()
|
||||
if not normalized_name or not normalized_employee_id:
|
||||
raise RuntimeError("缺少姓名或工号,无法查询 OA 用户")
|
||||
|
||||
query_sql = """
|
||||
SELECT TOP 1 v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
|
||||
d.departmentname, s.subcompanyname, j.jobtitlename
|
||||
FROM userInfo_view v
|
||||
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
|
||||
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
|
||||
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
|
||||
WHERE v.workcode = ? AND v.lastname = ?
|
||||
ORDER BY v.id
|
||||
"""
|
||||
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
return {
|
||||
"uid": str(row.id) if row.id is not None else "",
|
||||
"employeeId": str(row.workcode) if row.workcode is not None else "",
|
||||
"name": str(row.lastname) if row.lastname is not None else "",
|
||||
"jobtitle": str(row.jobtitle) if row.jobtitle is not None else "",
|
||||
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
|
||||
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
|
||||
"departmentName": str(row.departmentname).strip() if row.departmentname else "",
|
||||
"subcompanyName": str(row.subcompanyname).strip() if row.subcompanyname else "",
|
||||
"jobtitleName": str(row.jobtitlename).strip() if row.jobtitlename else "",
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_department_name(cls, department_id: str) -> str:
|
||||
if not department_id or not department_id.strip():
|
||||
return ""
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT TOP 1 departmentname FROM HrmDepartment WHERE id = ?",
|
||||
[department_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return str(row.departmentname).strip() if row and row.departmentname else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_subcompany_name(cls, subcompany_id: str) -> str:
|
||||
if not subcompany_id or not subcompany_id.strip():
|
||||
return ""
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT TOP 1 subcompanyname FROM HrmSubCompany WHERE id = ?",
|
||||
[subcompany_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return str(row.subcompanyname).strip() if row and row.subcompanyname else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_jobtitle_name(cls, jobtitle_id: str) -> str:
|
||||
if not jobtitle_id or not jobtitle_id.strip():
|
||||
return ""
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(
|
||||
"SELECT TOP 1 jobtitlename FROM HrmJobTitles WHERE id = ?",
|
||||
[jobtitle_id.strip()],
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
return str(row.jobtitlename).strip() if row and row.jobtitlename else ""
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
@@ -0,0 +1,378 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
from html import escape
|
||||
from urllib.parse import quote
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ChatLog, db
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
|
||||
class PLMOracleService:
|
||||
_ALLOWED_AGENT_NAMES = {"通用入口", "生产sop"}
|
||||
_MAX_RESULT_ROWS = 50
|
||||
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
|
||||
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
|
||||
_EXPLICIT_LABEL_PATTERN = re.compile(
|
||||
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_RELATIONAL_SQL = """
|
||||
select *
|
||||
from bi_file endb
|
||||
where endb.revisionguid in (
|
||||
select bb.revisionguid
|
||||
from (
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b
|
||||
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = cad.masterfk
|
||||
and cad.latestrevision like '%m%'
|
||||
and b.revisionguid = cad.guid
|
||||
union
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b
|
||||
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = cad.masterfk
|
||||
and cad.latestrevision like '%m%'
|
||||
and b.revisionguid = cad.guid
|
||||
union
|
||||
select v.end1, b.*
|
||||
from viewobject_0 v,
|
||||
StructureObject_0 str,
|
||||
document_0 doc,
|
||||
bi_file b
|
||||
where v.name in ('RelatedDoc')
|
||||
and str.viewfk = v.guid
|
||||
and str.end2$master = doc.masterfk
|
||||
and doc.latestrevision like '%m%'
|
||||
and b.revisionguid = doc.guid
|
||||
) bb,
|
||||
item_0 i
|
||||
where bb.end1 = i.guid
|
||||
and i.id = :item_id
|
||||
and i.latestrevision like '%m%'
|
||||
)
|
||||
and endb.lastaccesstime is not null
|
||||
"""
|
||||
_FILENAME_SQL = """
|
||||
select *
|
||||
from bi_file
|
||||
where upper(name) like :name_pattern
|
||||
and lastaccesstime is not null
|
||||
order by lastaccesstime desc nulls last
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def supports(cls, query: str, agent) -> bool:
|
||||
return bool(cls.extract_material_no(query) and cls._is_supported_agent(agent))
|
||||
|
||||
@classmethod
|
||||
def extract_material_no(cls, query: str) -> str | None:
|
||||
text = str(query or "").strip().upper()
|
||||
if not text:
|
||||
return None
|
||||
|
||||
explicit = cls._EXPLICIT_LABEL_PATTERN.search(text)
|
||||
if explicit:
|
||||
return explicit.group(1).strip().upper()
|
||||
|
||||
direct_match = cls._MATERIAL_PATTERN.fullmatch(text)
|
||||
if direct_match:
|
||||
return direct_match.group(0).upper()
|
||||
|
||||
for match in cls._MATERIAL_PATTERN.finditer(text):
|
||||
candidate = match.group(0).upper()
|
||||
if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate):
|
||||
return candidate
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _is_supported_agent(cls, agent) -> bool:
|
||||
name = str(getattr(agent, "name", "") or "").strip().lower().replace(" ", "")
|
||||
return name in cls._ALLOWED_AGENT_NAMES
|
||||
|
||||
@staticmethod
|
||||
def _get_connect_kwargs() -> dict:
|
||||
dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip()
|
||||
host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip()
|
||||
port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip())
|
||||
service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip()
|
||||
sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip()
|
||||
|
||||
kwargs = {
|
||||
"user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(),
|
||||
"password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(),
|
||||
}
|
||||
if dsn:
|
||||
kwargs["dsn"] = dsn
|
||||
return kwargs
|
||||
|
||||
import oracledb
|
||||
|
||||
if service_name:
|
||||
kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name)
|
||||
else:
|
||||
kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid)
|
||||
return kwargs
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc
|
||||
|
||||
oracle_client_dir = Text2SQLService._get_oracle_client_dir()
|
||||
Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir)
|
||||
Text2SQLService._init_oracle_client(oracledb)
|
||||
return oracledb.connect(**cls._get_connect_kwargs())
|
||||
|
||||
@classmethod
|
||||
def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]:
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(sql, params)
|
||||
columns = [col[0] for col in cursor.description] if cursor.description else []
|
||||
rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1)
|
||||
return columns, rows
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]:
|
||||
try:
|
||||
columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no)
|
||||
if rows:
|
||||
return columns, rows, "relational"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc)
|
||||
|
||||
columns, rows = cls._execute_query(
|
||||
cls._FILENAME_SQL,
|
||||
name_pattern=f"{material_no.upper()}%",
|
||||
)
|
||||
return columns, rows, "filename_fallback"
|
||||
|
||||
@staticmethod
|
||||
def _format_datetime(value) -> str:
|
||||
if value is None:
|
||||
return "-"
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return str(value)
|
||||
|
||||
@staticmethod
|
||||
def _format_size(value) -> str:
|
||||
if value in (None, ""):
|
||||
return "-"
|
||||
try:
|
||||
size = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return str(value)
|
||||
if size < 1024:
|
||||
return f"{size} B"
|
||||
if size < 1024 * 1024:
|
||||
return f"{size / 1024:.1f} KB"
|
||||
return f"{size / 1024 / 1024:.2f} MB"
|
||||
|
||||
@classmethod
|
||||
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
|
||||
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
|
||||
for value in (storage_id, file_path, file_id):
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
parts.append(text.replace("/", "\\").strip("\\"))
|
||||
return "\\".join(part for part in parts if part)
|
||||
|
||||
@classmethod
|
||||
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
|
||||
def raw(column_name: str):
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return None
|
||||
value = row[idx]
|
||||
return None if value in (None, "") else value
|
||||
|
||||
file_name = str(raw("NAME") or "").strip()
|
||||
if not file_name:
|
||||
return "-"
|
||||
|
||||
storage_id = raw("STORAGEID")
|
||||
file_path = raw("FILEPATH")
|
||||
file_id = str(raw("ID") or "").strip()
|
||||
if not storage_id or file_path is None or not file_id:
|
||||
return escape(file_name)
|
||||
|
||||
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
|
||||
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
|
||||
return f'<a href="{preview_href}">{escape(file_name)}</a>'
|
||||
|
||||
@staticmethod
|
||||
def _escape_markdown_cell(value: str) -> str:
|
||||
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@staticmethod
|
||||
def _escape_html_text(value) -> str:
|
||||
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
|
||||
|
||||
@classmethod
|
||||
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
|
||||
idx = index_map.get(column_name.upper())
|
||||
if idx is None or idx >= len(row):
|
||||
return "-"
|
||||
value = row[idx]
|
||||
if value in (None, ""):
|
||||
return "-"
|
||||
upper_name = column_name.upper()
|
||||
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
|
||||
return cls._format_datetime(value)
|
||||
if upper_name == "FILESIZE":
|
||||
return cls._format_size(value)
|
||||
if upper_name == "NAME":
|
||||
return cls._render_file_name(row, index_map)
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
|
||||
parts = [f"记录 {row_no}"]
|
||||
for column_name in cls._SUMMARY_COLUMNS:
|
||||
if column_name.upper() not in index_map:
|
||||
continue
|
||||
rendered = cls._render_column_value(row, column_name, index_map)
|
||||
label = {
|
||||
"NAME": "文件名",
|
||||
"EXTENTIONNAME": "扩展名",
|
||||
"FILETYPE": "文件类型",
|
||||
"FILESIZE": "文件大小",
|
||||
"RELATIVEPATH": "相对路径",
|
||||
"LASTACCESSTIME": "最后访问时间",
|
||||
}.get(column_name.upper(), column_name)
|
||||
if column_name.upper() == "NAME":
|
||||
parts.append(f"{label}: {rendered}")
|
||||
else:
|
||||
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
|
||||
return " | ".join(parts)
|
||||
|
||||
@classmethod
|
||||
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
|
||||
rows_html = []
|
||||
for column_name in columns:
|
||||
rendered_value = cls._render_column_value(row, column_name, index_map)
|
||||
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
|
||||
rows_html.append(
|
||||
"<tr>"
|
||||
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
|
||||
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
|
||||
"</tr>"
|
||||
)
|
||||
|
||||
summary_html = cls._build_record_summary(row, index_map, row_no)
|
||||
return (
|
||||
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
|
||||
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
|
||||
"<div style=\"margin-top:10px;overflow:auto;\">"
|
||||
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
|
||||
"<thead><tr>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
|
||||
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
|
||||
"</tr></thead>"
|
||||
f"<tbody>{''.join(rows_html)}</tbody>"
|
||||
"</table>"
|
||||
"</div>"
|
||||
"</details>"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
|
||||
if not rows:
|
||||
return f"已在 PLM 中查询料号 `{material_no}`,未找到符合条件的相关资料。"
|
||||
|
||||
overflow = len(rows) > cls._MAX_RESULT_ROWS
|
||||
visible_rows = rows[: cls._MAX_RESULT_ROWS]
|
||||
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
|
||||
|
||||
lines = [
|
||||
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
|
||||
+ ("(仅展示前 50 条)" if overflow else "。"),
|
||||
"",
|
||||
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
|
||||
]
|
||||
for idx, row in enumerate(visible_rows, start=1):
|
||||
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
|
||||
|
||||
if overflow:
|
||||
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
|
||||
return "\n".join(lines)
|
||||
|
||||
@classmethod
|
||||
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None):
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
|
||||
material_no = cls.extract_material_no(query)
|
||||
|
||||
try:
|
||||
if not material_no:
|
||||
raise RuntimeError("未识别到有效料号,请输入类似 F3-A12M290000019 的料号。")
|
||||
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': f'已识别料号 `{material_no}`,正在查询 PLM 资料,请稍候...\\n'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
columns, rows, query_mode = cls._query_files(material_no)
|
||||
answer = cls._build_answer(material_no, columns, rows)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=final_conversation_id,
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
answer=answer,
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
payload={
|
||||
"material_no": material_no,
|
||||
"row_count": min(len(rows), cls._MAX_RESULT_ROWS),
|
||||
"query_mode": query_mode,
|
||||
},
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.error("Failed to log PLM chat: %s", exc)
|
||||
db.session.rollback()
|
||||
|
||||
end_data = {
|
||||
"event": "message_end",
|
||||
"answer": answer,
|
||||
"replace_answer": True,
|
||||
"chat_log_id": chat_log_id,
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception("[plm-oracle] stream_chat failed query=%s", query)
|
||||
error_data = {
|
||||
"event": "error",
|
||||
"message": str(exc) or "PLM 查询失败",
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
@@ -0,0 +1,319 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import requests
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.sql_config import (
|
||||
get_schedule_sql_config,
|
||||
get_schedule_sql_config_by_task_id,
|
||||
get_all_schedule_sql_configs,
|
||||
upsert_schedule_task_config,
|
||||
ScheduleSqlConfig,
|
||||
)
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
|
||||
|
||||
|
||||
def normalize_platform_api_path(path: str | None) -> str:
|
||||
value = str(path or "").strip()
|
||||
if not value:
|
||||
return ""
|
||||
parsed = urlparse(value)
|
||||
if parsed.scheme in {"http", "https"}:
|
||||
return value
|
||||
if not value.startswith("/"):
|
||||
value = "/" + value
|
||||
return value
|
||||
|
||||
|
||||
def _build_srm_conn_str() -> str:
|
||||
host = str(current_app.config.get("SRM_SQLSERVER_HOST") or "").strip()
|
||||
if not host:
|
||||
raise RuntimeError("SRM_SQLSERVER_HOST is not configured")
|
||||
|
||||
port = str(current_app.config.get("SRM_SQLSERVER_PORT") or "1433").strip()
|
||||
database = str(current_app.config.get("SRM_SQLSERVER_DATABASE") or "").strip()
|
||||
username = str(current_app.config.get("SRM_SQLSERVER_USERNAME") or "").strip()
|
||||
password = str(current_app.config.get("SRM_SQLSERVER_PASSWORD") or "").strip()
|
||||
driver = str(current_app.config.get("SRM_SQLSERVER_DRIVER") or "SQL Server").strip()
|
||||
encrypt = str(current_app.config.get("SRM_SQLSERVER_ENCRYPT") or "no").strip().lower()
|
||||
trust_cert = str(current_app.config.get("SRM_SQLSERVER_TRUST_CERT") or "yes").strip().lower()
|
||||
|
||||
return (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={host},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
|
||||
|
||||
def _resolve_dify_agent(task: ScheduleTask):
|
||||
agent = db.session.get(Agent, task.dify_agent_id) if task.dify_agent_id else None
|
||||
if task.dify_agent_id and (not agent or not agent.dify_api_key):
|
||||
raise RuntimeError("dify_agent_id is invalid or key is missing")
|
||||
return agent
|
||||
|
||||
|
||||
def _resolve_schedule_user(task: ScheduleTask) -> str:
|
||||
return str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system")
|
||||
|
||||
|
||||
def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
endpoint = normalize_platform_api_path(task.platform_api_path)
|
||||
if not endpoint:
|
||||
raise RuntimeError("platform_api_path is missing")
|
||||
|
||||
base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/")
|
||||
if endpoint.startswith("http://") or endpoint.startswith("https://"):
|
||||
url = endpoint
|
||||
elif base:
|
||||
name = endpoint.lstrip("/")
|
||||
url = f"{base}/api/internal/jobs/{name}"
|
||||
else:
|
||||
url = endpoint
|
||||
|
||||
payload = {
|
||||
"run_no": run.run_no,
|
||||
"schedule_task_id": task.id,
|
||||
"schedule_name": task.name,
|
||||
"dify_agent_id": task.dify_agent_id,
|
||||
}
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
|
||||
run.api_request_json = payload
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
timeout = max(5, (task.wait_seconds or 120) + 30)
|
||||
resp = requests.post(url, json=payload, timeout=(5, timeout))
|
||||
resp.raise_for_status()
|
||||
data = resp.json() if resp.content else {}
|
||||
step_logs.append({
|
||||
"step": "call_internal_api",
|
||||
"status": "success",
|
||||
"detail": {"url": url, "status_code": resp.status_code},
|
||||
})
|
||||
except requests.RequestException as e:
|
||||
data = {}
|
||||
if e.response is not None:
|
||||
try:
|
||||
data = e.response.json()
|
||||
except Exception:
|
||||
data = {"error_text": e.response.text}
|
||||
else:
|
||||
data = {"error": str(e)}
|
||||
step_logs.append({
|
||||
"step": "call_internal_api",
|
||||
"status": "failed",
|
||||
"detail": {"url": url, "error": str(e)},
|
||||
})
|
||||
run.api_response_json = data
|
||||
db.session.commit()
|
||||
raise e
|
||||
|
||||
run.api_response_json = data
|
||||
db.session.commit()
|
||||
|
||||
summary = data.get("summary") if isinstance(data, dict) and isinstance(data.get("summary"), dict) else {}
|
||||
details = data.get("details") if isinstance(data, dict) and isinstance(data.get("details"), list) else []
|
||||
errors = data.get("errors") if isinstance(data, dict) and isinstance(data.get("errors"), list) else []
|
||||
remote_step_logs = data.get("step_logs") if isinstance(data, dict) and isinstance(data.get("step_logs"), list) else []
|
||||
|
||||
total = int(summary.get("total_count") if summary.get("total_count") is not None else (len(details) or 1))
|
||||
success = int(summary.get("success_count") if summary.get("success_count") is not None else total)
|
||||
failed = int(summary.get("failed_count") if summary.get("failed_count") is not None else max(0, total - success))
|
||||
skipped = int(summary.get("skipped_count") if summary.get("skipped_count") is not None else 0)
|
||||
|
||||
if remote_step_logs:
|
||||
step_logs.extend(remote_step_logs)
|
||||
|
||||
return total, success, failed, skipped, details, [str(e) for e in errors if str(e).strip()], step_logs
|
||||
|
||||
|
||||
def _run_external_api_job(task: ScheduleTask, run: ScheduleRun, cfg: ScheduleSqlConfig) -> ScheduleExecuteResult:
|
||||
import requests as http_requests
|
||||
|
||||
ext = cfg.external_api
|
||||
if not ext.url:
|
||||
return 0, 0, 0, 0, [], ["external_api url is empty"], []
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
step_logs.append({"step": "call_external_api", "status": "started", "url": ext.url, "method": ext.method})
|
||||
|
||||
try:
|
||||
headers = dict(ext.headers) if ext.headers else {}
|
||||
body = ext.body_template or "{}"
|
||||
resp = http_requests.request(
|
||||
method=ext.method,
|
||||
url=ext.url,
|
||||
headers=headers,
|
||||
data=body,
|
||||
timeout=120,
|
||||
)
|
||||
step_logs.append({"step": "call_external_api", "status": "completed", "status_code": resp.status_code})
|
||||
if not resp.ok:
|
||||
return 0, 0, 0, 1, [], [f"external API returned {resp.status_code}: {resp.text[:500]}"], step_logs
|
||||
try:
|
||||
result_data = resp.json()
|
||||
except Exception:
|
||||
result_data = {"raw": resp.text[:2000]}
|
||||
|
||||
total = 1
|
||||
details = [result_data] if isinstance(result_data, dict) else (result_data if isinstance(result_data, list) else [{"raw": str(result_data)}])
|
||||
step_logs.append({"step": "call_external_api", "status": "success", "total": total})
|
||||
return total, total, 0, 0, details, [], step_logs
|
||||
except Exception as e:
|
||||
step_logs.append({"step": "call_external_api", "status": "error", "error": str(e)})
|
||||
return 0, 0, 1, 0, [], [str(e)], step_logs
|
||||
|
||||
|
||||
def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
from app.services.schedule.srm_service import (
|
||||
_run_check_job_loop,
|
||||
_fetch_records,
|
||||
_execute_writeback,
|
||||
_build_record_text,
|
||||
)
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg:
|
||||
return 0, 0, 0, 0, [], [], []
|
||||
|
||||
if cfg.data_source_type == "external_api":
|
||||
return _run_external_api_job(task, run, cfg)
|
||||
|
||||
if not cfg.fetch_sql:
|
||||
return 0, 0, 0, 0, [], [], []
|
||||
|
||||
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)
|
||||
user = _resolve_schedule_user(task)
|
||||
has_detail = bool(cfg.detail_sql)
|
||||
|
||||
def fetch_fn(cs: str):
|
||||
return _fetch_records(cs, cfg.fetch_sql)
|
||||
|
||||
def writeback_fn(cs: str, *, row_id: str, run_no: str, dify_result: str, dify_message: str):
|
||||
_execute_writeback(cs, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
|
||||
pre_dify_fn = None
|
||||
build_record_fn = None
|
||||
|
||||
if has_detail:
|
||||
def _pre_dify(cs: str, item: dict[str, Any], row_id_value: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
detail_rows = _fetch_records(cs, 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_summary_lines: list[str] = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_summary_lines.append(", ".join(parts))
|
||||
item["detail_text"] = "; ".join(detail_summary_lines) if detail_summary_lines else ""
|
||||
item["_detail_rows"] = detail_rows
|
||||
return None
|
||||
pre_dify_fn = _pre_dify
|
||||
|
||||
def _build_with_detail(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
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")
|
||||
build_record_fn = _build_with_detail
|
||||
else:
|
||||
def _build_simple(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return text, item.get("attachment")
|
||||
build_record_fn = _build_simple
|
||||
|
||||
return _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run.run_no,
|
||||
agent=agent,
|
||||
user=user,
|
||||
wait_seconds=task.wait_seconds or 120,
|
||||
run_id=run.id,
|
||||
fetch_fn=fetch_fn,
|
||||
build_record_fn=build_record_fn,
|
||||
writeback_fn=writeback_fn,
|
||||
writeback_sql=cfg.writeback_sql,
|
||||
row_id_key=cfg.row_id_key,
|
||||
log_prefix=cfg.log_prefix,
|
||||
fetch_sql=cfg.fetch_sql,
|
||||
pre_dify_fn=pre_dify_fn,
|
||||
dify_system_prompt=cfg.dify_system_prompt,
|
||||
)
|
||||
|
||||
|
||||
def list_registered_api_paths() -> list[dict[str, str]]:
|
||||
from app.models import ScheduleTask
|
||||
results: list[dict[str, str]] = []
|
||||
tasks = ScheduleTask.query.filter(ScheduleTask.platform_api_path.isnot(None)).all()
|
||||
for t in tasks:
|
||||
results.append({"value": t.platform_api_path, "label": t.name or str(t.id)})
|
||||
return results
|
||||
|
||||
|
||||
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
|
||||
dst = getattr(task, "data_source_type", None) or "database"
|
||||
if dst in ("database", "external_api"):
|
||||
return _run_generic_check_job
|
||||
return _run_common_executor
|
||||
|
||||
|
||||
_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {}
|
||||
|
||||
|
||||
def register_schedule_header(name: str, header_order: list[str], header_labels: dict[str, str]) -> None:
|
||||
key = str(name or "").strip().lower()
|
||||
if not key:
|
||||
raise ValueError("header name is required")
|
||||
_SCHEDULE_HEADER_REGISTRY[key] = (header_order, header_labels)
|
||||
|
||||
|
||||
def resolve_schedule_header(platform_api_path: str | None) -> tuple[list[str] | None, dict[str, str] | None]:
|
||||
path = normalize_platform_api_path(platform_api_path)
|
||||
if path:
|
||||
key = path.lstrip("/").lower()
|
||||
if key in _SCHEDULE_HEADER_REGISTRY:
|
||||
return _SCHEDULE_HEADER_REGISTRY[key]
|
||||
return None, None
|
||||
|
||||
|
||||
def _register_headers_from_config() -> None:
|
||||
_SCHEDULE_HEADER_REGISTRY.clear()
|
||||
for name, cfg in get_all_schedule_sql_configs().items():
|
||||
if cfg.alias_order and cfg.header_labels:
|
||||
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
||||
|
||||
|
||||
def reload_config() -> dict[str, Any]:
|
||||
_register_headers_from_config()
|
||||
return {"reloaded": []}
|
||||
|
||||
|
||||
_HEADERS_LOADED = False
|
||||
|
||||
|
||||
def ensure_headers_loaded() -> None:
|
||||
global _HEADERS_LOADED
|
||||
if not _HEADERS_LOADED:
|
||||
_register_headers_from_config()
|
||||
_HEADERS_LOADED = True
|
||||
@@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
|
||||
def build_dify_execution_snapshot(task: ScheduleTask) -> dict[str, Any]:
|
||||
"""Capture Dify agent + system prompt used at execution time for audit."""
|
||||
captured_at = datetime.utcnow().isoformat() + "Z"
|
||||
if not task.dify_agent_id:
|
||||
return {
|
||||
"dify_enabled": False,
|
||||
"dify_agent_id": None,
|
||||
"dify_agent_name": None,
|
||||
"dify_app_id": None,
|
||||
"dify_system_prompt": "",
|
||||
"captured_at": captured_at,
|
||||
}
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
prompt = str(cfg.dify_system_prompt if cfg else "").strip()
|
||||
agent = db.session.get(Agent, task.dify_agent_id)
|
||||
return {
|
||||
"dify_enabled": True,
|
||||
"dify_agent_id": task.dify_agent_id,
|
||||
"dify_agent_name": getattr(agent, "name", None) if agent else None,
|
||||
"dify_app_id": getattr(agent, "dify_app_id", None) if agent else None,
|
||||
"dify_system_prompt": prompt,
|
||||
"captured_at": captured_at,
|
||||
}
|
||||
|
||||
|
||||
def capture_dify_execution_snapshot(run: ScheduleRun, task: ScheduleTask) -> dict[str, Any]:
|
||||
snapshot = build_dify_execution_snapshot(task)
|
||||
run.dify_execution_snapshot = snapshot
|
||||
return snapshot
|
||||
@@ -0,0 +1,139 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
|
||||
def _flatten_value(v: Any) -> Any:
|
||||
if isinstance(v, (dict, list)):
|
||||
return json.dumps(v, ensure_ascii=False)
|
||||
return v
|
||||
|
||||
|
||||
_EXPORT_SKIP_KEYS = {"dify_output", "json_output", "output", "_detail_rows", "detail_text"}
|
||||
|
||||
|
||||
def export_schedule_result_excel(
|
||||
*,
|
||||
run_no: str,
|
||||
summary: dict,
|
||||
details: list[dict],
|
||||
header_order: list[str] | None = None,
|
||||
header_labels: dict[str, str] | None = None,
|
||||
detail_alias_order: list[str] | None = None,
|
||||
) -> tuple[bytes | None, str | None, int]:
|
||||
if not details:
|
||||
return None, None, 0
|
||||
|
||||
header_order = header_order or []
|
||||
header_labels = header_labels or {}
|
||||
detail_alias_order = detail_alias_order or []
|
||||
|
||||
exec_result_order = ["dify_result", "dify_message", "writeback_srm", "writeback_err"]
|
||||
|
||||
sql_headers: list[str] = []
|
||||
detail_headers: list[str] = []
|
||||
exec_result_headers: list[str] = []
|
||||
|
||||
def _append_unique(target: list[str], key: str) -> None:
|
||||
if key not in target:
|
||||
target.append(key)
|
||||
|
||||
for row in details:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
for k in row.keys():
|
||||
key = str(k)
|
||||
if key in _EXPORT_SKIP_KEYS:
|
||||
continue
|
||||
if key in exec_result_order:
|
||||
_append_unique(exec_result_headers, key)
|
||||
else:
|
||||
_append_unique(sql_headers, key)
|
||||
detail_rows = row.get("_detail_rows")
|
||||
if isinstance(detail_rows, list):
|
||||
for dr in detail_rows:
|
||||
if isinstance(dr, dict):
|
||||
for dk in dr.keys():
|
||||
_append_unique(detail_headers, str(dk))
|
||||
|
||||
ordered_sql_headers = [k for k in header_order if k in sql_headers]
|
||||
other_sql_headers = [k for k in sql_headers if k not in header_order]
|
||||
ordered_detail_headers = [k for k in detail_alias_order if k in detail_headers]
|
||||
other_detail_headers = [k for k in detail_headers if k not in detail_alias_order]
|
||||
ordered_exec_headers = [k for k in exec_result_order if k in exec_result_headers]
|
||||
other_exec_headers = [k for k in exec_result_headers if k not in exec_result_order]
|
||||
|
||||
all_detail_headers = ordered_detail_headers + other_detail_headers
|
||||
|
||||
headers = (
|
||||
ordered_sql_headers
|
||||
+ other_sql_headers
|
||||
+ all_detail_headers
|
||||
+ ordered_exec_headers
|
||||
+ other_exec_headers
|
||||
)
|
||||
|
||||
if not headers:
|
||||
return None, None, 0
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "result"
|
||||
ws.append([header_labels.get(k, k) for k in headers])
|
||||
|
||||
detail_key_set = set(all_detail_headers)
|
||||
merge_keys = [k for k in headers if k not in detail_key_set]
|
||||
col_index_map = {k: idx + 1 for idx, k in enumerate(headers)}
|
||||
|
||||
current_excel_row = 2 # header is row 1
|
||||
for row in details:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
|
||||
base_row: dict[str, Any] = {}
|
||||
for k, v in row.items():
|
||||
key = str(k)
|
||||
if key in _EXPORT_SKIP_KEYS:
|
||||
continue
|
||||
if key in {"dify_output", "json_output", "output"}:
|
||||
if isinstance(v, dict):
|
||||
for json_key, json_val in v.items():
|
||||
base_row[str(json_key)] = _flatten_value(json_val)
|
||||
continue
|
||||
base_row[key] = _flatten_value(v)
|
||||
|
||||
detail_rows = row.get("_detail_rows")
|
||||
group_rows: list[dict[str, Any]] = []
|
||||
if all_detail_headers and isinstance(detail_rows, list) and detail_rows:
|
||||
for dr in detail_rows:
|
||||
flat = dict(base_row)
|
||||
if isinstance(dr, dict):
|
||||
for dk in all_detail_headers:
|
||||
flat[dk] = dr.get(dk, "")
|
||||
group_rows.append(flat)
|
||||
else:
|
||||
group_rows.append(base_row)
|
||||
|
||||
for out_row in group_rows:
|
||||
ws.append([out_row.get(k, "") for k in headers])
|
||||
|
||||
group_size = len(group_rows)
|
||||
if group_size > 1:
|
||||
start_row = current_excel_row
|
||||
end_row = current_excel_row + group_size - 1
|
||||
for key in merge_keys:
|
||||
col = col_index_map.get(key)
|
||||
if not col:
|
||||
continue
|
||||
ws.merge_cells(start_row=start_row, start_column=col, end_row=end_row, end_column=col)
|
||||
current_excel_row += group_size
|
||||
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
file_data = buf.getvalue()
|
||||
file_name = f"schedule_{run_no}.xlsx"
|
||||
return file_data, file_name, len(file_data)
|
||||
@@ -0,0 +1,132 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
|
||||
def serialize_task(task: ScheduleTask, *, last_status: str | None = None) -> dict:
|
||||
return {
|
||||
'id': task.id,
|
||||
'schedule_no': task.schedule_no,
|
||||
'name': task.name,
|
||||
'schedule_type': task.schedule_type,
|
||||
'owner_user_id': task.owner_user_id,
|
||||
'owner_username': task.owner.username if task.owner else None,
|
||||
'cron_expr': task.cron_expr,
|
||||
'wait_seconds': task.wait_seconds,
|
||||
'dify_agent_id': task.dify_agent_id,
|
||||
'platform_api_path': task.platform_api_path,
|
||||
'data_source_type': task.data_source_type,
|
||||
'notify_user_ids_json': task.notify_user_ids_json or [],
|
||||
'notify_enabled': bool(task.notify_enabled),
|
||||
'enabled': bool(task.enabled),
|
||||
'next_run_at': task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
'last_run_at': task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
'last_status': last_status,
|
||||
'created_at': task.created_at.isoformat() if task.created_at else None,
|
||||
'updated_at': task.updated_at.isoformat() if task.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def serialize_run(run: ScheduleRun) -> dict:
|
||||
return {
|
||||
'id': run.id,
|
||||
'run_no': run.run_no,
|
||||
'schedule_task_id': run.schedule_task_id,
|
||||
'schedule_name': run.task.name if run.task else None,
|
||||
'trigger_type': run.trigger_type,
|
||||
'triggered_by_user_id': run.triggered_by_user_id,
|
||||
'started_at': run.started_at.isoformat() if run.started_at else None,
|
||||
'finished_at': run.finished_at.isoformat() if run.finished_at else None,
|
||||
'duration_ms': run.duration_ms,
|
||||
'status': run.status,
|
||||
'total_count': run.total_count,
|
||||
'success_count': run.success_count,
|
||||
'failed_count': run.failed_count,
|
||||
'skipped_count': run.skipped_count,
|
||||
'api_request_json': run.api_request_json,
|
||||
'api_response_json': run.api_response_json,
|
||||
'response_summary_json': run.response_summary_json,
|
||||
'step_logs': run.step_logs,
|
||||
'dify_execution_snapshot': run.dify_execution_snapshot,
|
||||
'error_message': run.error_message,
|
||||
'excel_file_name': run.excel_file_name,
|
||||
'excel_file_size': run.excel_file_size,
|
||||
'wecom_notified': bool(run.wecom_notified),
|
||||
'wecom_notified_at': run.wecom_notified_at.isoformat() if run.wecom_notified_at else None,
|
||||
'wecom_notify_error': run.wecom_notify_error,
|
||||
'created_at': run.created_at.isoformat() if run.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_tasks() -> list[dict]:
|
||||
latest_run_subquery = (
|
||||
db.session.query(
|
||||
ScheduleRun.schedule_task_id.label('task_id'),
|
||||
func.max(ScheduleRun.id).label('last_run_id'),
|
||||
)
|
||||
.group_by(ScheduleRun.schedule_task_id)
|
||||
.subquery()
|
||||
)
|
||||
rows = (
|
||||
db.session.query(ScheduleTask, ScheduleRun.status.label('last_status'))
|
||||
.options(joinedload(ScheduleTask.owner))
|
||||
.outerjoin(latest_run_subquery, latest_run_subquery.c.task_id == ScheduleTask.id)
|
||||
.outerjoin(ScheduleRun, ScheduleRun.id == latest_run_subquery.c.last_run_id)
|
||||
.order_by(ScheduleTask.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
return [serialize_task(task, last_status=last_status) for task, last_status in rows]
|
||||
|
||||
|
||||
def list_runs(
|
||||
*,
|
||||
task_id: Optional[int] = None,
|
||||
owner_user_id: Optional[int] = None,
|
||||
notify_user_id: Optional[int] = None,
|
||||
schedule_name: Optional[str] = None,
|
||||
status: Optional[str] = None,
|
||||
started_after: Optional[datetime] = None,
|
||||
started_before: Optional[datetime] = None,
|
||||
limit: int = 100,
|
||||
) -> list[dict]:
|
||||
query = db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
if task_id is not None:
|
||||
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||
if schedule_name:
|
||||
query = query.filter(ScheduleTask.name.ilike(f'%{schedule_name}%'))
|
||||
if status:
|
||||
query = query.filter(ScheduleRun.status == status)
|
||||
if started_after is not None:
|
||||
query = query.filter(ScheduleRun.started_at >= started_after)
|
||||
if started_before is not None:
|
||||
query = query.filter(ScheduleRun.started_at < started_before)
|
||||
if owner_user_id is not None:
|
||||
query = query.filter(ScheduleTask.owner_user_id == owner_user_id)
|
||||
if notify_user_id is not None:
|
||||
query = query.filter(
|
||||
(ScheduleTask.owner_user_id == notify_user_id)
|
||||
| ScheduleTask.notify_user_ids_json.cast(db.String).ilike(f'%{notify_user_id}%')
|
||||
)
|
||||
runs = query.order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 500))).all()
|
||||
return [serialize_run(r) for r in runs]
|
||||
|
||||
|
||||
def get_run(run_id: int) -> ScheduleRun | None:
|
||||
return db.session.query(ScheduleRun).options(joinedload(ScheduleRun.task)).filter(ScheduleRun.id == run_id).first()
|
||||
|
||||
|
||||
def can_view_run(run: ScheduleRun, user_id: int) -> bool:
|
||||
task = run.task
|
||||
if not task:
|
||||
return False
|
||||
if task.owner_user_id == user_id:
|
||||
return True
|
||||
notify = task.notify_user_ids_json or []
|
||||
return int(user_id) in {int(x) for x in notify if str(x).isdigit()}
|
||||
@@ -0,0 +1,452 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from croniter import croniter
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
|
||||
_worker_started = False
|
||||
_worker_lock = threading.Lock()
|
||||
_cancelled_runs: set[int] = set()
|
||||
_cancel_lock = threading.Lock()
|
||||
|
||||
|
||||
def request_cancel_run(run_id: int) -> None:
|
||||
with _cancel_lock:
|
||||
_cancelled_runs.add(run_id)
|
||||
|
||||
|
||||
def is_run_cancelled(run_id: int) -> bool:
|
||||
with _cancel_lock:
|
||||
return run_id in _cancelled_runs
|
||||
|
||||
|
||||
def clear_cancelled_run(run_id: int) -> None:
|
||||
with _cancel_lock:
|
||||
_cancelled_runs.discard(run_id)
|
||||
|
||||
|
||||
def _generate_schedule_no() -> str:
|
||||
return f"SCH{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
|
||||
|
||||
|
||||
def _generate_run_no() -> str:
|
||||
return f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
|
||||
|
||||
|
||||
def _generate_test_run_no() -> str:
|
||||
return f"TESTRUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
|
||||
|
||||
|
||||
_WECOM_STATUS_LABEL = {
|
||||
'success': '成功',
|
||||
'failed': '失败',
|
||||
'partial_failed': '部分失败',
|
||||
}
|
||||
|
||||
_WECOM_EVENT_TYPE = 'schedule_completed'
|
||||
|
||||
|
||||
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
from app.services.wecom_notify import (
|
||||
upload_wecom_temp_media,
|
||||
send_wecom_file_message,
|
||||
send_wecom_textcard_message,
|
||||
_create_audit,
|
||||
_build_jump_url,
|
||||
_get_enabled_events,
|
||||
)
|
||||
|
||||
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
||||
run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false'
|
||||
return
|
||||
|
||||
if _WECOM_EVENT_TYPE not in _get_enabled_events():
|
||||
run.wecom_notify_error = f'event {_WECOM_EVENT_TYPE} disabled'
|
||||
return
|
||||
|
||||
user_ids = task.notify_user_ids_json or []
|
||||
if not user_ids:
|
||||
return
|
||||
|
||||
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
||||
wecom_users = [u for u in users if u.wecom_userid]
|
||||
if not wecom_users:
|
||||
run.wecom_notify_error = 'no wecom_userid bound users in notify list'
|
||||
return
|
||||
|
||||
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
|
||||
title = f'排程执行结果: {task.name}'
|
||||
description = (
|
||||
f'执行单号: {run.run_no}\n'
|
||||
f'状态: {status_label}\n'
|
||||
f'总数: {run.total_count} 成功: {run.success_count} 失败: {run.failed_count}'
|
||||
)
|
||||
|
||||
media_id = None
|
||||
if run.excel_file_data and run.excel_file_name:
|
||||
try:
|
||||
media_id = upload_wecom_temp_media(run.excel_file_data, run.excel_file_name)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning(
|
||||
'[wecom-schedule] media upload failed for run %s: %s',
|
||||
run.run_no, exc,
|
||||
)
|
||||
|
||||
textcard_ok_count = 0
|
||||
errors = []
|
||||
|
||||
for u in wecom_users:
|
||||
trace_id = uuid.uuid4().hex
|
||||
jump_url = _build_jump_url('/workspace', trace_id, {'tab': 'schedule-runs'})
|
||||
|
||||
try:
|
||||
audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id)
|
||||
audit.jump_url = jump_url
|
||||
|
||||
data = send_wecom_textcard_message(u.wecom_userid, title, description, jump_url)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
textcard_ok_count += 1
|
||||
else:
|
||||
audit.error_code = str(data.get('errcode'))
|
||||
audit.error_message = str(data.get('errmsg', 'unknown'))[:255]
|
||||
errors.append(f'{u.real_name or u.username}: textcard errcode={data.get("errcode")}')
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: textcard exception={exc}')
|
||||
|
||||
if media_id:
|
||||
try:
|
||||
file_audit = _create_audit(
|
||||
f'{_WECOM_EVENT_TYPE}_file', u,
|
||||
title, f'[文件] {run.excel_file_name}', uuid.uuid4().hex,
|
||||
)
|
||||
file_data = send_wecom_file_message(u.wecom_userid, media_id)
|
||||
if file_data.get('errcode') == 0:
|
||||
file_audit.status = 'sent'
|
||||
else:
|
||||
file_audit.error_code = str(file_data.get('errcode'))
|
||||
file_audit.error_message = str(file_data.get('errmsg', 'unknown'))[:255]
|
||||
errors.append(f'{u.real_name or u.username}: file errcode={file_data.get("errcode")}')
|
||||
except Exception as exc:
|
||||
errors.append(f'{u.real_name or u.username}: file exception={exc}')
|
||||
|
||||
if textcard_ok_count > 0:
|
||||
run.wecom_notified = True
|
||||
run.wecom_notified_at = datetime.utcnow()
|
||||
else:
|
||||
run.wecom_notified = False
|
||||
|
||||
if errors:
|
||||
run.wecom_notify_error = '; '.join(errors[:5])
|
||||
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def create_task(
|
||||
*,
|
||||
name: str,
|
||||
schedule_type: str,
|
||||
owner_user_id: int,
|
||||
cron_expr: str,
|
||||
wait_seconds: int,
|
||||
dify_agent_id: int | None,
|
||||
platform_api_path: str | None,
|
||||
notify_user_ids_json: list[int] | None,
|
||||
notify_enabled: bool,
|
||||
enabled: bool,
|
||||
actor_id: int | None,
|
||||
) -> ScheduleTask:
|
||||
task = ScheduleTask(
|
||||
schedule_no=_generate_schedule_no(),
|
||||
name=name,
|
||||
schedule_type="platform_app",
|
||||
owner_user_id=owner_user_id,
|
||||
cron_expr=cron_expr,
|
||||
wait_seconds=max(0, int(wait_seconds or 0)),
|
||||
dify_agent_id=dify_agent_id,
|
||||
platform_api_path=normalize_platform_api_path(platform_api_path) or None,
|
||||
notify_user_ids_json=notify_user_ids_json or [],
|
||||
notify_enabled=bool(notify_enabled),
|
||||
enabled=bool(enabled),
|
||||
created_by=actor_id,
|
||||
updated_by=actor_id,
|
||||
)
|
||||
if task.enabled and task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.enabled = False
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int | None) -> ScheduleTask:
|
||||
for key in [
|
||||
"name",
|
||||
"owner_user_id",
|
||||
"cron_expr",
|
||||
"wait_seconds",
|
||||
"dify_agent_id",
|
||||
"notify_enabled",
|
||||
"enabled",
|
||||
]:
|
||||
if key in payload:
|
||||
setattr(task, key, payload[key])
|
||||
if "platform_api_path" in payload:
|
||||
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
|
||||
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
|
||||
task.notify_user_ids_json = payload.get("notify_user_ids_json")
|
||||
|
||||
if not normalize_platform_api_path(task.platform_api_path):
|
||||
raise ValueError("platform_api_path is required for platform_app")
|
||||
task.schedule_type = "platform_app"
|
||||
|
||||
if task.enabled and task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
else:
|
||||
task.next_run_at = None
|
||||
|
||||
task.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return task
|
||||
|
||||
|
||||
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
|
||||
if run is None:
|
||||
existing = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.schedule_task_id == task.id,
|
||||
ScheduleRun.status == "running",
|
||||
).first()
|
||||
if existing:
|
||||
return existing
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type=trigger_type,
|
||||
triggered_by_user_id=triggered_by_user_id,
|
||||
started_at=datetime.utcnow(),
|
||||
status="running",
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
|
||||
if task.cron_expr and trigger_type == "cron":
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
|
||||
start_ts = time.time()
|
||||
step_logs: list = []
|
||||
try:
|
||||
executor = resolve_schedule_executor(task)
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run)
|
||||
except Exception as exc:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)]
|
||||
step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}]
|
||||
|
||||
try:
|
||||
db.session.refresh(run)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if is_run_cancelled(run.id):
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = int((time.time() - start_ts) * 1000)
|
||||
run.status = "failed"
|
||||
run.error_message = "排程已被删除,执行中断"
|
||||
db.session.commit()
|
||||
clear_cancelled_run(run.id)
|
||||
return run
|
||||
|
||||
duration_ms = int((time.time() - start_ts) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[schedule-run] run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d",
|
||||
run.run_no, total_count, success_count, failed_count, skipped_count, len(errors),
|
||||
)
|
||||
if total_count == 0 and not errors:
|
||||
status = "success"
|
||||
run.error_message = "无待处理数据"
|
||||
elif failed_count == 0:
|
||||
status = "success"
|
||||
elif success_count == 0:
|
||||
status = "failed"
|
||||
else:
|
||||
status = "partial_failed"
|
||||
|
||||
try:
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if cfg and cfg.alias_order and cfg.header_labels:
|
||||
header_order, header_labels = cfg.alias_order, cfg.header_labels
|
||||
else:
|
||||
header_order, header_labels = resolve_schedule_header(task.platform_api_path)
|
||||
detail_alias_order = (cfg.detail_alias_order if cfg else None) or []
|
||||
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:
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-run] excel export failed: %s", excel_exc)
|
||||
file_data, file_name, file_size = None, None, 0
|
||||
errors.append(f"Excel导出失败: {excel_exc}")
|
||||
|
||||
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.response_summary_json = {
|
||||
"errors": errors[:20],
|
||||
"schedule_type": task.schedule_type,
|
||||
"platform_api_path": task.platform_api_path,
|
||||
}
|
||||
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
|
||||
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
if current_app:
|
||||
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
|
||||
|
||||
task.last_run_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
def start_scheduler(app):
|
||||
global _worker_started
|
||||
with _worker_lock:
|
||||
if _worker_started:
|
||||
return
|
||||
_worker_started = True
|
||||
|
||||
if not bool(app.config.get("SCHEDULE_WORKER_ENABLED", True)):
|
||||
return
|
||||
|
||||
import os
|
||||
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not app.debug:
|
||||
pass
|
||||
else:
|
||||
_worker_started = False
|
||||
return
|
||||
|
||||
def _loop():
|
||||
with app.app_context():
|
||||
stale = db.session.query(ScheduleTask).filter(
|
||||
ScheduleTask.enabled.is_(True),
|
||||
ScheduleTask.next_run_at.isnot(None),
|
||||
ScheduleTask.next_run_at <= datetime.utcnow(),
|
||||
).all()
|
||||
for t in stale:
|
||||
if t.cron_expr:
|
||||
try:
|
||||
it = croniter(t.cron_expr, datetime.utcnow())
|
||||
t.next_run_at = it.get_next(datetime)
|
||||
except Exception:
|
||||
t.next_run_at = None
|
||||
t.enabled = False
|
||||
else:
|
||||
t.next_run_at = None
|
||||
if stale:
|
||||
db.session.commit()
|
||||
current_app.logger.info("[schedule-worker] reset %d stale next_run_at on startup", len(stale))
|
||||
|
||||
stuck = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.status == "running",
|
||||
).all()
|
||||
for r in stuck:
|
||||
r.status = "failed"
|
||||
r.error_message = "服务重启,执行中断"
|
||||
r.finished_at = datetime.utcnow()
|
||||
if stuck:
|
||||
db.session.commit()
|
||||
current_app.logger.info("[schedule-worker] cleaned %d stuck running runs on startup", len(stuck))
|
||||
|
||||
while True:
|
||||
try:
|
||||
now = datetime.utcnow()
|
||||
due_tasks = db.session.query(ScheduleTask).filter(
|
||||
ScheduleTask.enabled.is_(True),
|
||||
ScheduleTask.next_run_at.isnot(None),
|
||||
ScheduleTask.next_run_at <= now,
|
||||
).limit(5).with_for_update(skip_locked=True).all()
|
||||
for task in due_tasks:
|
||||
has_running = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.schedule_task_id == task.id,
|
||||
ScheduleRun.status == "running",
|
||||
).first()
|
||||
if has_running:
|
||||
if task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
continue
|
||||
try:
|
||||
run_task_now(task, trigger_type="cron", triggered_by_user_id=None)
|
||||
except Exception as e:
|
||||
current_app.logger.error("[schedule-worker] task_id=%s run failed: %s", task.id, e, exc_info=True)
|
||||
db.session.rollback()
|
||||
|
||||
if task.cron_expr:
|
||||
try:
|
||||
iter = croniter(task.cron_expr, datetime.utcnow())
|
||||
task.next_run_at = iter.get_next(datetime)
|
||||
except Exception:
|
||||
task.next_run_at = None
|
||||
task.enabled = False
|
||||
else:
|
||||
task.next_run_at = None
|
||||
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
time.sleep(30)
|
||||
|
||||
t = threading.Thread(target=_loop, daemon=True, name="schedule-worker")
|
||||
t.start()
|
||||
@@ -0,0 +1,243 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
_ENV_VAR_PATTERN = re.compile(r"\$\{(\w+)\}")
|
||||
|
||||
|
||||
def resolve_env_value(val: str) -> str:
|
||||
if not val or "${" not in val:
|
||||
return val
|
||||
|
||||
def _replacer(match: re.Match) -> str:
|
||||
env_key = match.group(1)
|
||||
return os.environ.get(env_key, match.group(0))
|
||||
|
||||
return _ENV_VAR_PATTERN.sub(_replacer, val)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DataSourceConfig:
|
||||
db_type: str = "sqlserver"
|
||||
host: str = ""
|
||||
port: str = ""
|
||||
database: str = ""
|
||||
username: str = ""
|
||||
password: str = ""
|
||||
driver: str = ""
|
||||
encrypt: str = ""
|
||||
trust_cert: str = ""
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
return not self.host.strip()
|
||||
|
||||
def build_connection_string(self) -> str:
|
||||
host = resolve_env_value(self.host)
|
||||
port = resolve_env_value(self.port)
|
||||
database = resolve_env_value(self.database)
|
||||
username = resolve_env_value(self.username)
|
||||
password = resolve_env_value(self.password)
|
||||
|
||||
if not port:
|
||||
if self.db_type == "sqlserver":
|
||||
port = "1433"
|
||||
elif self.db_type == "postgresql":
|
||||
port = "5432"
|
||||
elif self.db_type == "mysql":
|
||||
port = "3306"
|
||||
|
||||
if self.db_type == "sqlserver":
|
||||
driver = resolve_env_value(self.driver) or "SQL Server"
|
||||
encrypt = resolve_env_value(self.encrypt) or "no"
|
||||
trust_cert = resolve_env_value(self.trust_cert) or "yes"
|
||||
return (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={host},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
elif self.db_type == "postgresql":
|
||||
return f"postgresql://{username}:{password}@{host}:{port}/{database}"
|
||||
elif self.db_type == "mysql":
|
||||
return f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}"
|
||||
raise ValueError(f"Unsupported db_type: {self.db_type}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExternalApiConfig:
|
||||
url: str = ""
|
||||
method: str = "POST"
|
||||
headers: dict[str, str] = field(default_factory=dict)
|
||||
body_template: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ScheduleSqlConfig:
|
||||
description: str = ""
|
||||
row_id_key: str = "id"
|
||||
log_prefix: str = ""
|
||||
fetch_sql: str = ""
|
||||
base_fetch_sql: str = ""
|
||||
fetch_where_conditions: str = ""
|
||||
fetch_order_by: str = ""
|
||||
writeback_sql: str = ""
|
||||
detail_sql: str = ""
|
||||
alias_order: list[str] = field(default_factory=list)
|
||||
detail_alias_order: list[str] = field(default_factory=list)
|
||||
header_labels: dict[str, str] = field(default_factory=dict)
|
||||
data_source: DataSourceConfig = field(default_factory=DataSourceConfig)
|
||||
external_api: ExternalApiConfig = field(default_factory=ExternalApiConfig)
|
||||
data_source_type: str = "database"
|
||||
dify_system_prompt: str = ""
|
||||
|
||||
|
||||
def _build_fetch_sql(base: str, where_conds: str, order_by: str) -> str:
|
||||
parts = [base.strip().rstrip(";").strip()]
|
||||
if where_conds.strip():
|
||||
parts.append("where")
|
||||
parts.append(where_conds.strip())
|
||||
if order_by.strip():
|
||||
parts.append(order_by.strip())
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def _config_from_model(cfg_model: Any) -> ScheduleSqlConfig:
|
||||
from app import db
|
||||
from app.models import ScheduleTask
|
||||
|
||||
task_id = cfg_model.schedule_task_id
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
|
||||
base = str(cfg_model.base_fetch_sql or "")
|
||||
where_conds = str(cfg_model.fetch_where_conditions or "")
|
||||
order_by = str(cfg_model.fetch_order_by or "")
|
||||
fetch_sql = _build_fetch_sql(base, where_conds, order_by) if base else ""
|
||||
|
||||
ds = DataSourceConfig(
|
||||
db_type=str(cfg_model.ds_db_type or "sqlserver"),
|
||||
host=str(cfg_model.ds_host or ""),
|
||||
port=str(cfg_model.ds_port or ""),
|
||||
database=str(cfg_model.ds_database or ""),
|
||||
username=str(cfg_model.ds_username or ""),
|
||||
password=str(cfg_model.ds_password or ""),
|
||||
driver=str(cfg_model.ds_driver or ""),
|
||||
encrypt=str(cfg_model.ds_encrypt or ""),
|
||||
trust_cert=str(cfg_model.ds_trust_cert or ""),
|
||||
)
|
||||
|
||||
ext = ExternalApiConfig(
|
||||
url=str(cfg_model.api_url or ""),
|
||||
method=str(cfg_model.api_method or "POST"),
|
||||
headers=dict(cfg_model.api_headers or {}),
|
||||
body_template=str(cfg_model.api_body_template or ""),
|
||||
)
|
||||
|
||||
return ScheduleSqlConfig(
|
||||
description=str(task.name if task else ""),
|
||||
row_id_key=str(cfg_model.row_id_key or "id"),
|
||||
log_prefix=str(cfg_model.log_prefix or ""),
|
||||
fetch_sql=fetch_sql,
|
||||
base_fetch_sql=base,
|
||||
fetch_where_conditions=where_conds,
|
||||
fetch_order_by=order_by,
|
||||
writeback_sql=str(cfg_model.writeback_sql or ""),
|
||||
detail_sql=str(cfg_model.detail_sql or ""),
|
||||
alias_order=list(cfg_model.alias_order or []),
|
||||
detail_alias_order=list(cfg_model.detail_alias_order or []),
|
||||
header_labels=dict(cfg_model.header_labels or {}),
|
||||
data_source=ds,
|
||||
external_api=ext,
|
||||
data_source_type=str(task.data_source_type if task else "database"),
|
||||
dify_system_prompt=str(cfg_model.dify_system_prompt or ""),
|
||||
)
|
||||
|
||||
|
||||
def get_schedule_sql_config(name: str) -> ScheduleSqlConfig | None:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
key = name.strip().lower()
|
||||
task = None
|
||||
if key.isdigit():
|
||||
task = db.session.get(ScheduleTask, int(key))
|
||||
if not task:
|
||||
task = ScheduleTask.query.filter(
|
||||
ScheduleTask.platform_api_path.ilike(f"%{key}%")
|
||||
).first()
|
||||
if not task:
|
||||
return None
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if not cfg_model:
|
||||
return None
|
||||
|
||||
return _config_from_model(cfg_model)
|
||||
|
||||
|
||||
def get_schedule_sql_config_by_task_id(task_id: int) -> ScheduleSqlConfig | None:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
return None
|
||||
return _config_from_model(cfg_model)
|
||||
|
||||
|
||||
def get_all_schedule_sql_configs() -> dict[str, ScheduleSqlConfig]:
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
results: dict[str, ScheduleSqlConfig] = {}
|
||||
configs = ScheduleTaskConfig.query.all()
|
||||
for cfg_model in configs:
|
||||
key = str(cfg_model.schedule_task_id)
|
||||
results[key] = _config_from_model(cfg_model)
|
||||
return results
|
||||
|
||||
|
||||
def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleSqlConfig:
|
||||
from app import db
|
||||
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if not cfg_model:
|
||||
cfg_model = ScheduleTaskConfig(schedule_task_id=task_id)
|
||||
db.session.add(cfg_model)
|
||||
|
||||
for k, v in data.items():
|
||||
if k == "data_source" and isinstance(v, dict):
|
||||
cfg_model.ds_db_type = str(v.get("db_type", "sqlserver"))
|
||||
cfg_model.ds_host = str(v.get("host", ""))
|
||||
cfg_model.ds_port = str(v.get("port", ""))
|
||||
cfg_model.ds_database = str(v.get("database", ""))
|
||||
cfg_model.ds_username = str(v.get("username", ""))
|
||||
cfg_model.ds_password = str(v.get("password", ""))
|
||||
cfg_model.ds_driver = str(v.get("driver", "")) if v.get("driver") else None
|
||||
cfg_model.ds_encrypt = str(v.get("encrypt", "")) if v.get("encrypt") else None
|
||||
cfg_model.ds_trust_cert = str(v.get("trust_cert", "")) if v.get("trust_cert") else None
|
||||
elif k == "external_api" and isinstance(v, dict):
|
||||
cfg_model.api_url = str(v.get("url", ""))
|
||||
cfg_model.api_method = str(v.get("method", "POST"))
|
||||
cfg_model.api_headers = dict(v.get("headers", {}))
|
||||
cfg_model.api_body_template = str(v.get("body_template", ""))
|
||||
elif k in ("row_id_key", "log_prefix"):
|
||||
setattr(cfg_model, k, str(v) if v is not None else "")
|
||||
elif k in ("base_fetch_sql", "fetch_where_conditions", "fetch_order_by",
|
||||
"writeback_sql", "detail_sql"):
|
||||
setattr(cfg_model, k, str(v) if v is not None else None)
|
||||
elif k in ("alias_order", "detail_alias_order"):
|
||||
setattr(cfg_model, k, list(v) if isinstance(v, (list, tuple)) else [])
|
||||
elif k == "header_labels":
|
||||
setattr(cfg_model, k, dict(v) if isinstance(v, dict) else {})
|
||||
elif k == "dify_system_prompt":
|
||||
setattr(cfg_model, k, str(v) if v is not None else None)
|
||||
|
||||
db.session.commit()
|
||||
db.session.refresh(cfg_model)
|
||||
return _config_from_model(cfg_model)
|
||||
@@ -0,0 +1,372 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.dify import DifyService
|
||||
|
||||
try:
|
||||
import pyodbc # type: ignore
|
||||
except Exception: # pragma: no cover
|
||||
pyodbc = None
|
||||
|
||||
|
||||
def _connect(conn_str: str):
|
||||
if pyodbc is None:
|
||||
raise RuntimeError("pyodbc is not installed")
|
||||
return pyodbc.connect(conn_str, timeout=15)
|
||||
|
||||
|
||||
def _fetch_records(conn_str: str, sql: str, params: tuple | None = None) -> list[dict[str, Any]]:
|
||||
conn = _connect(conn_str)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if params:
|
||||
cur.execute(sql, params)
|
||||
else:
|
||||
cur.execute(sql)
|
||||
cols = [c[0] for c in cur.description]
|
||||
rows = cur.fetchall()
|
||||
return [{cols[i]: row[i] for i in range(len(cols))} for row in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _execute_writeback(conn_str: str, sql: str, params: tuple) -> None:
|
||||
conn = _connect(conn_str)
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql, params)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def _derive_dify_result_and_message(data: dict[str, Any]) -> tuple[str, str]:
|
||||
dify_result = str(data.get("dify_result")).strip()
|
||||
dify_message = str(data.get("dify_message")).strip()
|
||||
if dify_result not in {"合格", "不合格", "人工判定"}:
|
||||
dify_message = (dify_message + " | 返回值异常:" + dify_result).strip(" |")
|
||||
dify_result = "人工判定"
|
||||
return dify_result, dify_message
|
||||
|
||||
|
||||
def _build_record_text(
|
||||
item: dict[str, Any],
|
||||
alias_order: list[str],
|
||||
header_labels: dict[str, str],
|
||||
detail_rows: list[dict[str, Any]] | None = None,
|
||||
detail_alias_order: list[str] | None = None,
|
||||
) -> str:
|
||||
lines: list[str] = []
|
||||
for key in alias_order:
|
||||
label = header_labels.get(key, key)
|
||||
value = item.get(key)
|
||||
text = "" if value is None else str(value)
|
||||
lines.append(f"{label}: {text}")
|
||||
if detail_rows and detail_alias_order:
|
||||
lines.append("成分明细:")
|
||||
for idx, dr in enumerate(detail_rows, 1):
|
||||
detail_parts: list[str] = []
|
||||
for dk in detail_alias_order:
|
||||
dl = header_labels.get(dk, dk)
|
||||
dv = dr.get(dk)
|
||||
detail_parts.append(f"{dl}: {'' if dv is None else str(dv)}")
|
||||
lines.append(f" [{idx}] " + ", ".join(detail_parts))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
RecordBuilder = Callable[[str, dict[str, Any], str], tuple[str, str | None]]
|
||||
WritebackFunc = Callable[..., None]
|
||||
PreDifyFunc = Callable[[str, dict[str, Any], str], dict[str, Any] | None]
|
||||
|
||||
_MAX_STEP_LOGS_PER_ROW = 200
|
||||
_MAX_DIFY_RESPONSE_LEN = 4000
|
||||
|
||||
|
||||
def _ts() -> str:
|
||||
return datetime.utcnow().isoformat()
|
||||
|
||||
|
||||
def _make_step(
|
||||
step: str,
|
||||
status: str,
|
||||
started_at: str,
|
||||
finished_at: str,
|
||||
row_id: str | None = None,
|
||||
**extra: Any,
|
||||
) -> dict[str, Any]:
|
||||
entry: dict[str, Any] = {
|
||||
"step": step,
|
||||
"status": status,
|
||||
"started_at": started_at,
|
||||
"finished_at": finished_at,
|
||||
"duration_ms": int((datetime.fromisoformat(finished_at) - datetime.fromisoformat(started_at)).total_seconds() * 1000),
|
||||
}
|
||||
if row_id:
|
||||
entry["row_id"] = row_id
|
||||
entry.update(extra)
|
||||
return entry
|
||||
|
||||
|
||||
def _truncate_str(s: str, max_len: int = _MAX_DIFY_RESPONSE_LEN) -> str:
|
||||
if len(s) <= max_len:
|
||||
return s
|
||||
return s[:max_len] + f"...[truncated, total {len(s)} chars]"
|
||||
|
||||
|
||||
def _serialize_dify_inputs_for_log(inputs: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Log Dify request inputs; keep system_prompt intact for audit."""
|
||||
out: dict[str, Any] = {}
|
||||
for k, v in inputs.items():
|
||||
if k == "system_prompt":
|
||||
out[k] = str(v)
|
||||
else:
|
||||
out[k] = _truncate_str(str(v), 500)
|
||||
return out
|
||||
|
||||
|
||||
def _run_check_job_loop(
|
||||
*,
|
||||
conn_str: str,
|
||||
run_no: str,
|
||||
agent,
|
||||
user: str,
|
||||
wait_seconds: int,
|
||||
run_id: int | None,
|
||||
fetch_fn: Callable[[str], list[dict[str, Any]]],
|
||||
build_record_fn: RecordBuilder,
|
||||
writeback_fn: WritebackFunc,
|
||||
writeback_sql: str = "",
|
||||
row_id_key: str,
|
||||
log_prefix: str,
|
||||
fetch_sql: str = "",
|
||||
max_rows: int = 0,
|
||||
pre_dify_fn: PreDifyFunc | None = None,
|
||||
dify_system_prompt: str = "",
|
||||
) -> tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]:
|
||||
from app.services.schedule.scheduler_service import is_run_cancelled
|
||||
|
||||
use_dify = agent is not None
|
||||
if use_dify and not getattr(agent, "dify_api_key", None):
|
||||
raise RuntimeError("dify_agent_id is set, but Dify api key is missing")
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
|
||||
t0 = _ts()
|
||||
try:
|
||||
rows = fetch_fn(conn_str)
|
||||
if max_rows > 0:
|
||||
rows = rows[:max_rows]
|
||||
step_logs.append(_make_step(
|
||||
"fetch_srm",
|
||||
"success",
|
||||
t0, _ts(),
|
||||
detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "row_count": len(rows)},
|
||||
))
|
||||
except Exception as fetch_exc:
|
||||
step_logs.append(_make_step(
|
||||
"fetch_srm",
|
||||
"failed",
|
||||
t0, _ts(),
|
||||
detail={"sql": _truncate_str(fetch_sql or fetch_fn.__name__, 500), "error": str(fetch_exc)},
|
||||
))
|
||||
raise
|
||||
|
||||
details: list[dict[str, Any]] = []
|
||||
success_count = 0
|
||||
failed_count = 0
|
||||
skipped_count = 0
|
||||
all_errors: list[str] = []
|
||||
|
||||
for row in rows:
|
||||
if run_id is not None and is_run_cancelled(run_id):
|
||||
item = dict(row)
|
||||
item.update({
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": "排程已被删除,执行中断",
|
||||
"writeback_srm": False,
|
||||
"writeback_err": "排程已被删除,执行中断",
|
||||
})
|
||||
skipped_count += 1
|
||||
details.append(item)
|
||||
continue
|
||||
|
||||
item = dict(row)
|
||||
row_id_value = str(row.get(row_id_key, ""))
|
||||
|
||||
if pre_dify_fn:
|
||||
t_pre = _ts()
|
||||
try:
|
||||
pre_result = pre_dify_fn(conn_str, item, row_id_value)
|
||||
except Exception as pre_exc:
|
||||
pre_result = {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"pre_dify执行异常:{pre_exc}",
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(pre_exc),
|
||||
}
|
||||
step_logs.append(_make_step("pre_dify", "failed", t_pre, _ts(), row_id=row_id_value, detail={"error": str(pre_exc)}))
|
||||
|
||||
if pre_result is not None:
|
||||
item.update(pre_result)
|
||||
failed_count += 1
|
||||
all_errors.append(pre_result.get("writeback_err", ""))
|
||||
details.append(item)
|
||||
continue
|
||||
|
||||
record_text, attachment_url = build_record_fn(conn_str, item, row_id_value)
|
||||
|
||||
dify_ok = False
|
||||
dify_result = "人工判定"
|
||||
dify_message = ""
|
||||
|
||||
try:
|
||||
if use_dify:
|
||||
dify_inputs = {
|
||||
"run_no": run_no,
|
||||
"record": record_text,
|
||||
"attachment_url": attachment_url,
|
||||
}
|
||||
prompt = str(dify_system_prompt or "").strip()
|
||||
if prompt:
|
||||
dify_inputs["system_prompt"] = prompt
|
||||
t_dify = _ts()
|
||||
try:
|
||||
dify_res = DifyService.run_workflow_streaming(
|
||||
agent=agent,
|
||||
inputs=dify_inputs,
|
||||
user=user,
|
||||
timeout=(5, max(300, int(wait_seconds))),
|
||||
)
|
||||
except Exception as dify_exc:
|
||||
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {
|
||||
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
||||
"agent_id": getattr(agent, "id", None),
|
||||
},
|
||||
"error": str(dify_exc),
|
||||
}))
|
||||
raise
|
||||
|
||||
dify_status = dify_res.get("status") if isinstance(dify_res, dict) else None
|
||||
dify_error = dify_res.get("error") if isinstance(dify_res, dict) else None
|
||||
workflow_run_id = dify_res.get("workflow_run_id") if isinstance(dify_res, dict) else None
|
||||
|
||||
if dify_status == "failed" or (dify_error and not dify_res.get("outputs")):
|
||||
err_detail = str(dify_error) if dify_error else f"Dify status={dify_status}"
|
||||
dify_result = "人工判定"
|
||||
dify_message = f"Dify执行失败:{err_detail}"
|
||||
|
||||
step_logs.append(_make_step("call_dify", "failed", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {
|
||||
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
||||
"agent_id": getattr(agent, "id", None),
|
||||
},
|
||||
"response": _truncate_str(str(dify_res)),
|
||||
"workflow_run_id": workflow_run_id,
|
||||
}))
|
||||
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"writeback_srm": False,
|
||||
"writeback_err": err_detail,
|
||||
})
|
||||
failed_count += 1
|
||||
all_errors.append(f"Dify {log_prefix}={row_id_value}: {err_detail}")
|
||||
details.append(item)
|
||||
continue
|
||||
else:
|
||||
outputs = (dify_res.get("outputs") or {}).get("output") or dify_res.get("outputs") or dify_res
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[%s] %s=%s dify_result=%s dify_message=%s",
|
||||
log_prefix, log_prefix, row_id_value,
|
||||
(outputs.get("dify_result") or outputs.get("result")) if isinstance(outputs, dict) else None,
|
||||
(outputs.get("dify_message") or outputs.get("message")) if isinstance(outputs, dict) else None,
|
||||
)
|
||||
dify_result, dify_message = _derive_dify_result_and_message(outputs if isinstance(outputs, dict) else {})
|
||||
dify_ok = True
|
||||
|
||||
step_logs.append(_make_step("call_dify", "success", t_dify, _ts(), row_id=row_id_value, detail={
|
||||
"request": {
|
||||
"inputs": _serialize_dify_inputs_for_log(dify_inputs),
|
||||
"agent_id": getattr(agent, "id", None),
|
||||
},
|
||||
"response": {
|
||||
"status": dify_status,
|
||||
"dify_result": dify_result,
|
||||
"dify_message": _truncate_str(dify_message),
|
||||
"workflow_run_id": workflow_run_id,
|
||||
},
|
||||
}))
|
||||
else:
|
||||
dify_result = "人工判定"
|
||||
dify_message = "未配置 Agent ID,跳过 Dify"
|
||||
dify_ok = True
|
||||
|
||||
wb_sql = writeback_sql
|
||||
wb_params = (run_no, dify_result, dify_message, str(row_id_value))
|
||||
t_wb = _ts()
|
||||
try:
|
||||
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||
step_logs.append(_make_step("writeback_srm", "success", t_wb, _ts(), row_id=row_id_value, detail={
|
||||
"sql": _truncate_str(wb_sql, 500),
|
||||
"params": [str(p) for p in wb_params],
|
||||
}))
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"writeback_srm": True,
|
||||
"writeback_err": item.get("writeback_err"),
|
||||
})
|
||||
if dify_ok:
|
||||
success_count += 1
|
||||
except Exception as wb_exc:
|
||||
if current_app:
|
||||
current_app.logger.error("[%s] writeback failed %s=%s error=%s", log_prefix, log_prefix, row_id_value, wb_exc)
|
||||
step_logs.append(_make_step("writeback_srm", "failed", t_wb, _ts(), row_id=row_id_value, detail={
|
||||
"sql": _truncate_str(wb_sql, 500),
|
||||
"params": [str(p) for p in wb_params],
|
||||
"error": str(wb_exc),
|
||||
}))
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(wb_exc),
|
||||
})
|
||||
if dify_ok:
|
||||
failed_count += 1
|
||||
all_errors.append(f"writeback {log_prefix}={row_id_value}: {wb_exc}")
|
||||
except Exception as exc:
|
||||
dify_result = "人工判定"
|
||||
dify_message = f"执行异常:{exc}"
|
||||
item.update({
|
||||
"dify_result": dify_result,
|
||||
"dify_message": dify_message,
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(exc),
|
||||
})
|
||||
failed_count += 1
|
||||
all_errors.append(str(exc))
|
||||
t_wb2 = _ts()
|
||||
try:
|
||||
writeback_fn(conn_str, row_id=row_id_value, run_no=run_no, dify_result=dify_result, dify_message=dify_message)
|
||||
step_logs.append(_make_step("writeback_srm", "success", t_wb2, _ts(), row_id=row_id_value, detail={"note": "fallback writeback after dify error"}))
|
||||
item["writeback_srm"] = True
|
||||
except Exception as wb_exc:
|
||||
step_logs.append(_make_step("writeback_srm", "failed", t_wb2, _ts(), row_id=row_id_value, detail={"error": str(wb_exc), "note": "fallback writeback also failed"}))
|
||||
item["writeback_srm"] = False
|
||||
item["writeback_err"] = f"{item.get('writeback_err', '')}; writeback failed: {wb_exc}"
|
||||
|
||||
details.append(item)
|
||||
|
||||
if len(step_logs) > _MAX_STEP_LOGS_PER_ROW:
|
||||
step_logs = step_logs[:_MAX_STEP_LOGS_PER_ROW]
|
||||
|
||||
total_count = success_count + failed_count + skipped_count
|
||||
return total_count, success_count, failed_count, skipped_count, details, all_errors, step_logs
|
||||
Whitespace-only changes.
@@ -0,0 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import Agent
|
||||
|
||||
CHAT_AGENT_NAME = "货代发货通知 Agent"
|
||||
|
||||
|
||||
def resolve_chat_agent() -> Agent | None:
|
||||
return Agent.query.filter_by(name=CHAT_AGENT_NAME, is_active=True).first()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Backward-compatible re-exports — canonical definitions live in state_machine.py."""
|
||||
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
ACTION_SPECS,
|
||||
ALL_ACTION_IDS,
|
||||
ALL_CHECKPOINT_IDS,
|
||||
CHECKPOINT_REGISTRY,
|
||||
TaskTransition,
|
||||
TaskUiState,
|
||||
action_buttons_for_checkpoint,
|
||||
apply_task_transition,
|
||||
build_action_buttons,
|
||||
build_chat_actions_payload,
|
||||
build_checkpoint_catalog,
|
||||
checkpoint_for_task,
|
||||
format_actions_directive,
|
||||
human_options_for_checkpoint,
|
||||
human_options_for_task,
|
||||
human_options_for_task_or_checkpoint,
|
||||
resolve_task_ui_state,
|
||||
ui_state_for_checkpoint,
|
||||
upload_req_options_for_task,
|
||||
validate_registry,
|
||||
)
|
||||
|
||||
# Legacy alias
|
||||
CHECKPOINT_OPTIONS = CHECKPOINT_REGISTRY
|
||||
|
||||
__all__ = [
|
||||
"ACTION_SPECS",
|
||||
"ALL_ACTION_IDS",
|
||||
"ALL_CHECKPOINT_IDS",
|
||||
"CHECKPOINT_OPTIONS",
|
||||
"CHECKPOINT_REGISTRY",
|
||||
"TaskTransition",
|
||||
"TaskUiState",
|
||||
"action_buttons_for_checkpoint",
|
||||
"apply_task_transition",
|
||||
"build_action_buttons",
|
||||
"build_chat_actions_payload",
|
||||
"build_checkpoint_catalog",
|
||||
"checkpoint_for_task",
|
||||
"format_actions_directive",
|
||||
"human_options_for_checkpoint",
|
||||
"human_options_for_task",
|
||||
"human_options_for_task_or_checkpoint",
|
||||
"resolve_task_ui_state",
|
||||
"ui_state_for_checkpoint",
|
||||
"upload_req_options_for_task",
|
||||
"validate_registry",
|
||||
]
|
||||
@@ -0,0 +1,74 @@
|
||||
"""Short canonical names for shipping notice API fields and state machine.
|
||||
|
||||
Naming layers (avoid drift):
|
||||
- CP_* — API `checkpoint` / Dify `flow_ckpt` (see state_machine.CHECKPOINT_REGISTRY)
|
||||
- RS_* — DB `review_status` where used
|
||||
- PH_* — DB `pending_human_reason` (may equal CP_* when aligned)
|
||||
- Button ids / registry — state_machine.py only
|
||||
- DB state writes — state_machine.py `TaskTransition` / `apply_task_transition` (tools.py only)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# HTTP JSON request/response fields
|
||||
MAP_JSON = "map_json"
|
||||
SUGGEST_OK = "suggest_ok"
|
||||
AUTO_MAP = "auto_map"
|
||||
# Workspace / Hxops chat fallback only — Dify Agent 主路径应调 auto_progress,勿在画布 HTTP 传此字段
|
||||
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
|
||||
|
||||
# Legacy request field names (read-only compat)
|
||||
MAP_JSON_LEGACY = "column_mapping_json"
|
||||
|
||||
# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py)
|
||||
CP_ALIGN_REVIEW = "align_review"
|
||||
CP_MAP_INFER = "map_infer"
|
||||
CP_UPLOAD_REQ = "upload_req"
|
||||
CP_MAP_OK = "map_ok"
|
||||
CP_PARSE_OK = "parse_ok"
|
||||
CP_PARSE_REVIEW = "parse_review"
|
||||
CP_TASK_EXISTS = "task_exists"
|
||||
CP_RSV_REQ = "rsv_req"
|
||||
CP_UPLOAD_FAILED = "upload_failed"
|
||||
CP_WAITING_UPLOAD = "waiting_upload"
|
||||
CP_REJECTED = "rejected"
|
||||
# Derived UI checkpoints (no separate pending_human_reason; from process_status)
|
||||
CP_INVENTORY_PENDING = "inventory_pending"
|
||||
CP_READY_MATCH = "ready_to_match"
|
||||
CP_READY_EXPORT = "ready_to_export"
|
||||
CP_EXPORT_READY = "export_ready"
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
|
||||
CP_EXPORT_GENERATED = "export_generated"
|
||||
CP_UPLOADED = "uploaded"
|
||||
CP_COMPLETED = "completed"
|
||||
|
||||
# review_status
|
||||
RS_ALIGN_REVIEW = "align_review"
|
||||
RS_PARSE_REVIEW = "parse_review"
|
||||
RS_SHORTAGE_REVIEW = "shortage_review"
|
||||
RS_RSV_REQ = "rsv_req"
|
||||
RS_REJECTED = "rejected"
|
||||
RS_CONFIRMED = "confirmed"
|
||||
|
||||
# pending_human_reason (internal; shortened)
|
||||
PH_ALIGN_REVIEW = CP_ALIGN_REVIEW
|
||||
PH_MAP_INFER = CP_MAP_INFER
|
||||
PH_LOW_CONF = "low_confidence"
|
||||
PH_RSV_REQ = CP_RSV_REQ
|
||||
PH_SHORTAGE = "shortage"
|
||||
PH_RPA_EXHAUSTED = "rpa_exhausted"
|
||||
PH_RPA_PENDING = "rpa_pending"
|
||||
PH_INV_UNAVAIL = "inv_unavail"
|
||||
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
|
||||
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
||||
|
||||
|
||||
def payload_map_json(payload: dict[str, Any]) -> Any:
|
||||
raw = payload.get(MAP_JSON)
|
||||
if raw is None:
|
||||
raw = payload.get(MAP_JSON_LEGACY)
|
||||
if raw is None:
|
||||
raw = payload.get("field_mapping")
|
||||
return raw
|
||||
@@ -0,0 +1,26 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
# Dify Chatflow input variable names — must match canvas Start / 输入变量配置.
|
||||
HXOPS_TOOL_API_BASE_INPUT = "hxops_tool_api_base"
|
||||
HXOPS_TOOL_API_KEY_INPUT = "hxops_tool_api_key"
|
||||
|
||||
|
||||
def is_shipping_notice_chat_agent(agent) -> bool:
|
||||
return getattr(agent, "name", None) == CHAT_AGENT_NAME
|
||||
|
||||
|
||||
def build_dify_chat_inputs() -> dict[str, str]:
|
||||
"""Build Dify chat API inputs so HTTP nodes can reference env-specific hxops URLs."""
|
||||
base = resolve_tool_api_base_url()
|
||||
key = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip()
|
||||
inputs: dict[str, str] = {}
|
||||
if base:
|
||||
inputs[HXOPS_TOOL_API_BASE_INPUT] = base
|
||||
if key:
|
||||
inputs[HXOPS_TOOL_API_KEY_INPUT] = key
|
||||
return inputs
|
||||
@@ -0,0 +1,263 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from shutil import copy2
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.path_utils import backend_dir, resolve_backend_relative_path
|
||||
|
||||
DEFAULT_HEADERS = [
|
||||
"客户名称",
|
||||
"客户代码",
|
||||
"收货地址",
|
||||
"要求交期",
|
||||
"料号",
|
||||
"发货数量",
|
||||
"单位",
|
||||
"备注",
|
||||
]
|
||||
|
||||
HEADER_SHEET = "PVMI Pull Request Header"
|
||||
DETAIL_SHEET = "PVMI Pull Request Detail"
|
||||
DATA_START_ROW = 4
|
||||
|
||||
|
||||
def _storage_root() -> Path:
|
||||
root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip()
|
||||
if root:
|
||||
return Path(resolve_backend_relative_path(root))
|
||||
return Path(current_app.instance_path) / "shipping_notice"
|
||||
|
||||
|
||||
def _default_template_path() -> Path | None:
|
||||
configured = str(current_app.config.get("FREIGHT_SHIPMENT_TEMPLATE_PATH") or "").strip()
|
||||
if configured:
|
||||
path = Path(resolve_backend_relative_path(configured))
|
||||
if path.is_file():
|
||||
return path
|
||||
bundled = backend_dir() / "templates" / "freight_shipment_upload.xlsx"
|
||||
return bundled if bundled.is_file() else None
|
||||
|
||||
|
||||
def _is_pvmi_workbook(wb) -> bool:
|
||||
return HEADER_SHEET in wb.sheetnames and DETAIL_SHEET in wb.sheetnames
|
||||
|
||||
|
||||
def _format_delivery_date(value: Any) -> str:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y", "%Y%m%d"):
|
||||
try:
|
||||
parsed = datetime.strptime(text[:10], fmt)
|
||||
return parsed.strftime("%m/%d/%Y")
|
||||
except ValueError:
|
||||
continue
|
||||
if len(text) >= 10 and text[4] == "-" and text[7] == "-":
|
||||
try:
|
||||
parsed = datetime.strptime(text[:10], "%Y-%m-%d")
|
||||
return parsed.strftime("%m/%d/%Y")
|
||||
except ValueError:
|
||||
pass
|
||||
return text
|
||||
|
||||
|
||||
def _delivery_date_for_task(task: ShippingTask) -> str:
|
||||
if task.required_date:
|
||||
formatted = _format_delivery_date(task.required_date)
|
||||
if formatted:
|
||||
return formatted
|
||||
for line in task.lines_json or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
formatted = _format_delivery_date(line.get("required_date"))
|
||||
if formatted:
|
||||
return formatted
|
||||
return ""
|
||||
|
||||
|
||||
def _resolve_odm_id(task: ShippingTask) -> str:
|
||||
notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)]
|
||||
inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
if not inventory_lines:
|
||||
return ""
|
||||
|
||||
inv_by_key: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
for row in inventory_lines:
|
||||
key = (
|
||||
str(row.get("sku") or "").strip(),
|
||||
str(row.get("reservation_id") or "").strip(),
|
||||
)
|
||||
inv_by_key[key] = row
|
||||
|
||||
for line in notice_lines:
|
||||
key = (
|
||||
str(line.get("sku") or "").strip(),
|
||||
str(line.get("reservation_id") or "").strip(),
|
||||
)
|
||||
matched = inv_by_key.get(key)
|
||||
if matched:
|
||||
odm_id = str(matched.get("odm_id") or "").strip()
|
||||
if odm_id:
|
||||
return odm_id
|
||||
|
||||
for row in inventory_lines:
|
||||
odm_id = str(row.get("odm_id") or "").strip()
|
||||
if odm_id:
|
||||
return odm_id
|
||||
return ""
|
||||
|
||||
|
||||
def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str:
|
||||
for value in (line.get("po_number"), task.po_number):
|
||||
text = str(value or "").strip()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
def _line_currency(task: ShippingTask, line: dict[str, Any]) -> str:
|
||||
for value in (line.get("currency"), getattr(task, "currency", None)):
|
||||
text = str(value or "").strip().upper()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
|
||||
|
||||
def _line_vendor_part_number(line: dict[str, Any]) -> str:
|
||||
return str(line.get("vendor_part_number") or "").strip()
|
||||
|
||||
|
||||
def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None:
|
||||
if ws.max_row < from_row:
|
||||
return
|
||||
for row_idx in range(from_row, ws.max_row + 1):
|
||||
for col_idx in range(1, ws.max_column + 1):
|
||||
ws.cell(row_idx, col_idx).value = None
|
||||
|
||||
|
||||
def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
|
||||
wb = load_workbook(filename=str(path))
|
||||
header_ws = wb[HEADER_SHEET]
|
||||
detail_ws = wb[DETAIL_SHEET]
|
||||
|
||||
_clear_sheet_data_rows(detail_ws)
|
||||
_clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW)
|
||||
|
||||
if header_ws.cell(DATA_START_ROW, 1).value in (None, ""):
|
||||
header_ws.cell(DATA_START_ROW, 1).value = "AWSDU"
|
||||
if header_ws.cell(DATA_START_ROW, 2).value in (None, ""):
|
||||
header_ws.cell(DATA_START_ROW, 2).value = "n"
|
||||
if header_ws.cell(DATA_START_ROW, 3).value in (None, ""):
|
||||
header_ws.cell(DATA_START_ROW, 3).value = "WEL"
|
||||
if header_ws.cell(DATA_START_ROW, 4).value in (None, ""):
|
||||
header_ws.cell(DATA_START_ROW, 4).value = "normal"
|
||||
|
||||
header_ws.cell(DATA_START_ROW, 5).value = _delivery_date_for_task(task)
|
||||
header_ws.cell(DATA_START_ROW, 6).value = _resolve_odm_id(task)
|
||||
header_ws.cell(DATA_START_ROW, 7).value = task.task_no
|
||||
|
||||
notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)]
|
||||
if not notice_lines:
|
||||
notice_lines = [{}]
|
||||
|
||||
for index, line in enumerate(notice_lines, start=1):
|
||||
row_idx = DATA_START_ROW + index - 1
|
||||
line_no = str(line.get("line_no") or index).strip()
|
||||
qty = line.get("qty")
|
||||
amount = line.get("amount")
|
||||
|
||||
detail_ws.cell(row_idx, 1).value = task.task_no
|
||||
detail_ws.cell(row_idx, 2).value = line_no
|
||||
detail_ws.cell(row_idx, 4).value = _line_vendor_part_number(line)
|
||||
detail_ws.cell(row_idx, 5).value = qty if qty is not None else ""
|
||||
detail_ws.cell(row_idx, 7).value = _line_po_number(task, line)
|
||||
detail_ws.cell(row_idx, 10).value = amount if amount is not None else ""
|
||||
detail_ws.cell(row_idx, 11).value = _line_currency(task, line)
|
||||
|
||||
wb.save(path)
|
||||
|
||||
|
||||
def _row_values(task: ShippingTask, line: dict | None) -> list:
|
||||
line = line or {}
|
||||
return [
|
||||
task.customer_name or "",
|
||||
task.customer_code or "",
|
||||
task.ship_to or "",
|
||||
task.required_date or "",
|
||||
line.get("sku") or "",
|
||||
line.get("qty") or "",
|
||||
line.get("uom") or "EA",
|
||||
line.get("remark") or "",
|
||||
]
|
||||
|
||||
|
||||
def _fill_legacy_template(task: ShippingTask, path: Path) -> None:
|
||||
wb = load_workbook(filename=str(path))
|
||||
ws = wb.active
|
||||
lines = task.lines_json or [None]
|
||||
if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)):
|
||||
ws.append(DEFAULT_HEADERS)
|
||||
for line in lines:
|
||||
ws.append(_row_values(task, line))
|
||||
wb.save(path)
|
||||
|
||||
|
||||
def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Shipment"
|
||||
ws.append(DEFAULT_HEADERS)
|
||||
lines = task.lines_json or [None]
|
||||
for line in lines:
|
||||
ws.append(_row_values(task, line))
|
||||
wb.save(path)
|
||||
|
||||
|
||||
def _sanitize_filename(name: str) -> str:
|
||||
cleaned = "".join(ch for ch in (name or "") if ch.isalnum() or ch in {"-", "_", "."})
|
||||
return cleaned or "shipment.xlsx"
|
||||
|
||||
|
||||
def _export_filename(task: ShippingTask, ts: str) -> str:
|
||||
pattern = str(current_app.config.get("SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN") or "").strip()
|
||||
if not pattern:
|
||||
pattern = "shipment_{task_no}_{ts}.xlsx"
|
||||
try:
|
||||
name = pattern.format(task_no=task.task_no, ts=ts, date=ts[:8])
|
||||
except Exception:
|
||||
name = f"shipment_{task.task_no}_{ts}.xlsx"
|
||||
if not str(name).lower().endswith(".xlsx"):
|
||||
name = f"{name}.xlsx"
|
||||
return _sanitize_filename(str(name))
|
||||
|
||||
|
||||
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]:
|
||||
root = _storage_root() / "exports"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
ts = datetime.utcnow().strftime("%Y%m%d%H%M%S")
|
||||
filename = _export_filename(task, ts)
|
||||
path = root / filename
|
||||
|
||||
template = _default_template_path()
|
||||
if template:
|
||||
copy2(template, path)
|
||||
wb = load_workbook(filename=str(path), read_only=True)
|
||||
try:
|
||||
is_pvmi = _is_pvmi_workbook(wb)
|
||||
finally:
|
||||
wb.close()
|
||||
if is_pvmi:
|
||||
_fill_pvmi_template(task, path)
|
||||
else:
|
||||
_fill_legacy_template(task, path)
|
||||
else:
|
||||
_fill_blank_workbook(task, path)
|
||||
|
||||
return str(path), filename
|
||||
@@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.po_number import enrich_notice_with_po_number
|
||||
from app.services.shipping_notice.reservation_id import find_reservation_id_in_document
|
||||
from app.services.shipping_notice.notice_lines import (
|
||||
enrich_notice_with_document_currency,
|
||||
enrich_notice_with_document_required_date,
|
||||
enrich_notice_with_document_reservation,
|
||||
normalize_notice_lines,
|
||||
parse_notice_table_text,
|
||||
validate_notice_lines,
|
||||
)
|
||||
|
||||
|
||||
def _finalize_notice_parse(
|
||||
parsed: dict[str, Any],
|
||||
*,
|
||||
base_confidence: float,
|
||||
raw_text: str = "",
|
||||
) -> tuple[dict[str, Any], float, list[str]]:
|
||||
lines = normalize_notice_lines(parsed.get("lines") if isinstance(parsed.get("lines"), list) else [])
|
||||
parsed = enrich_notice_with_document_reservation({**parsed, "lines": lines}, raw_text=raw_text)
|
||||
parsed = enrich_notice_with_document_required_date(parsed)
|
||||
parsed = enrich_notice_with_document_currency(parsed)
|
||||
parsed = enrich_notice_with_po_number(parsed, raw_text=raw_text)
|
||||
lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else []
|
||||
warnings = validate_notice_lines(lines)
|
||||
from app.services.shipping_notice.notice_lines import notice_parse_completeness
|
||||
|
||||
completeness = notice_parse_completeness(lines)
|
||||
confidence = min(base_confidence, 0.95) * (0.5 + 0.5 * completeness) if lines else base_confidence * 0.5
|
||||
return parsed, round(confidence, 4), warnings
|
||||
|
||||
|
||||
def extract_notice_fields(
|
||||
*,
|
||||
raw_text: str,
|
||||
source_type: str = "manual",
|
||||
structured: dict[str, Any] | None = None,
|
||||
notice_files: list[dict[str, Any]] | None = None,
|
||||
) -> tuple[dict[str, Any], float, list[str]]:
|
||||
warnings: list[str] = []
|
||||
|
||||
if structured and isinstance(structured, dict):
|
||||
return _finalize_notice_parse(
|
||||
structured,
|
||||
base_confidence=float(structured.get("confidence") or 0.95),
|
||||
raw_text=str(structured.get("raw_text") or ""),
|
||||
)
|
||||
|
||||
heuristic, confidence, heuristic_warnings = _heuristic_extract(raw_text)
|
||||
warnings.extend(heuristic_warnings)
|
||||
return _finalize_notice_parse(heuristic, base_confidence=confidence, raw_text=raw_text)
|
||||
|
||||
|
||||
def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]:
|
||||
text = str(raw_text or "").strip()
|
||||
warnings: list[str] = []
|
||||
customer_name = ""
|
||||
m = re.search(r"客户[::]\s*(\S+)", text)
|
||||
if m:
|
||||
customer_name = m.group(1)
|
||||
|
||||
lines = parse_notice_table_text(text)
|
||||
if lines:
|
||||
doc_rid = find_reservation_id_in_document(text)
|
||||
if doc_rid:
|
||||
for line in lines:
|
||||
if not line.get("reservation_id"):
|
||||
line["reservation_id"] = doc_rid
|
||||
return (
|
||||
{
|
||||
"customer_name": customer_name,
|
||||
"customer_code": "",
|
||||
"ship_to": "",
|
||||
"required_date": "",
|
||||
"lines": lines,
|
||||
"confidence": 0.72,
|
||||
},
|
||||
0.72,
|
||||
warnings,
|
||||
)
|
||||
|
||||
lines = []
|
||||
for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text):
|
||||
lines.append({"sku": m.group(1), "qty": float(m.group(2)), "uom": "EA"})
|
||||
|
||||
# 尝试纯数字 Reservation ID + SKU + Qty 的自由文本模式(如 1000140351 10-40594-001 2)
|
||||
if not lines:
|
||||
for m in re.finditer(
|
||||
r"(?P<resv>\d{8,12})\s+([A-Za-z0-9\-_]{3,})\s+(\d+(?:\.\d+)?)",
|
||||
text,
|
||||
):
|
||||
lines.append(
|
||||
{
|
||||
"reservation_id": m.group("resv"),
|
||||
"sku": m.group(2),
|
||||
"qty": float(m.group(3)),
|
||||
"uom": "EA",
|
||||
}
|
||||
)
|
||||
|
||||
if not lines:
|
||||
warnings.append("heuristic_no_lines_detected")
|
||||
|
||||
confidence = 0.5 if lines else 0.3
|
||||
return (
|
||||
{
|
||||
"customer_name": customer_name,
|
||||
"customer_code": "",
|
||||
"ship_to": "",
|
||||
"required_date": "",
|
||||
"lines": lines,
|
||||
"confidence": confidence,
|
||||
},
|
||||
confidence,
|
||||
warnings,
|
||||
)
|
||||
@@ -0,0 +1,178 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
|
||||
|
||||
def _cell(value: Any) -> str:
|
||||
text = str(value or "").strip()
|
||||
return text if text else "-"
|
||||
|
||||
|
||||
def _fmt_qty(qty: Any) -> str:
|
||||
if qty is None or qty == "":
|
||||
return "-"
|
||||
try:
|
||||
num = float(qty)
|
||||
except (TypeError, ValueError):
|
||||
return _cell(qty)
|
||||
return str(int(num)) if num == int(num) else f"{num:g}"
|
||||
|
||||
|
||||
def _mapping_source_column(field_alignment: dict[str, Any], key: str) -> str:
|
||||
inv_columns = field_alignment.get("inventory_columns")
|
||||
if not isinstance(inv_columns, dict):
|
||||
return "-"
|
||||
mapping = inv_columns.get("mapping")
|
||||
if not isinstance(mapping, dict):
|
||||
return "-"
|
||||
entry = mapping.get(key)
|
||||
if isinstance(entry, dict):
|
||||
value = _cell(entry.get("source_column"))
|
||||
return f"`{value}`" if value != "-" else value
|
||||
return "-"
|
||||
|
||||
|
||||
def _normalize_warning(text: str, *, lang: str) -> str:
|
||||
raw = str(text or "").strip()
|
||||
if not raw:
|
||||
return raw
|
||||
|
||||
lower = raw.lower()
|
||||
prefix_1 = "parsed with mapping from uploaded file:"
|
||||
prefix_2 = "parsed from uploaded file:"
|
||||
if lower.startswith(prefix_1):
|
||||
filename = raw[len(prefix_1) :].strip()
|
||||
if lang == "en":
|
||||
return f"Parsed from uploaded inventory file with mapping: {filename}"
|
||||
if lang == "th":
|
||||
return f"แยกข้อมูลจากไฟล์สต็อกที่อัปโหลด (พร้อมการจับคู่คอลัมน์): {filename}"
|
||||
return f"已按映射解析上传的库存文件:{filename}"
|
||||
if lower.startswith(prefix_2):
|
||||
filename = raw[len(prefix_2) :].strip()
|
||||
if lang == "en":
|
||||
return f"Parsed from uploaded inventory file: {filename}"
|
||||
if lang == "th":
|
||||
return f"แยกข้อมูลจากไฟล์สต็อกที่อัปโหลด: {filename}"
|
||||
return f"已解析上传的库存文件:{filename}"
|
||||
return raw
|
||||
|
||||
|
||||
def _format_sample_lines(field_alignment: dict[str, Any], *, lang: str) -> list[str]:
|
||||
parts: list[str] = []
|
||||
notice_lines = field_alignment.get("sample_notice_lines") or []
|
||||
inventory_lines = field_alignment.get("sample_inventory_lines") or []
|
||||
|
||||
if notice_lines:
|
||||
parts.append(t("align.sample.notice", lang=lang))
|
||||
for index, line in enumerate(notice_lines[:3], 1):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
parts.append(
|
||||
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.sku', lang=lang)} {_cell(line.get('sku'))} | {t('field.qty', lang=lang)} {_fmt_qty(line.get('qty'))}"
|
||||
)
|
||||
|
||||
if inventory_lines:
|
||||
if parts:
|
||||
parts.append("")
|
||||
parts.append(t("align.sample.inventory", lang=lang))
|
||||
for index, line in enumerate(inventory_lines[:3], 1):
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
parts.append(
|
||||
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.sku', lang=lang)} {_cell(line.get('sku'))} | {t('field.available_qty', lang=lang)} {_fmt_qty(line.get('available_qty'))}"
|
||||
)
|
||||
return parts
|
||||
|
||||
|
||||
def format_field_alignment_summary(
|
||||
*,
|
||||
task_no: str,
|
||||
field_alignment: dict[str, Any],
|
||||
inventory_row_count: int | None = None,
|
||||
notice_line_count: int | None = None,
|
||||
warnings: list[Any] | None = None,
|
||||
lang: str | None = None,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
"""Fixed Markdown summary for apply_inventory_mapping / field alignment review."""
|
||||
resolved = resolve_lang(payload) if payload is not None else resolve_lang({"lang": lang} if lang else None)
|
||||
inv_count = inventory_row_count
|
||||
if inv_count is None:
|
||||
inv_count = field_alignment.get("inventory_row_count")
|
||||
notice_count = notice_line_count
|
||||
if notice_count is None:
|
||||
notice_count = field_alignment.get("notice_line_count")
|
||||
|
||||
match_rule = _cell(field_alignment.get("match_rule"))
|
||||
match_rule_source = str(field_alignment.get("match_rule_source") or "").strip()
|
||||
source_note = ""
|
||||
if match_rule_source == "llm":
|
||||
source_note = t("align.source.llm", lang=resolved)
|
||||
elif match_rule_source == "fallback":
|
||||
source_note = t("align.source.fallback", lang=resolved)
|
||||
elif match_rule_source:
|
||||
source_note = t("align.source.other", lang=resolved).format(source=match_rule_source)
|
||||
|
||||
parts = [
|
||||
t("align.title", lang=resolved).format(task_no=task_no),
|
||||
"",
|
||||
t("align.match_rule", lang=resolved).format(rule=match_rule, note=source_note),
|
||||
"",
|
||||
f"| {t('align.table.sys_field', lang=resolved)} | {t('align.table.inv_col', lang=resolved)} | {t('align.table.notice_field', lang=resolved)} |",
|
||||
"|---------|--------------|---------|",
|
||||
f"| {t('field.reservation_id', lang=resolved)} | {_mapping_source_column(field_alignment, 'reservation_id')} | {t('field.reservation_id', lang=resolved)} |",
|
||||
f"| {t('field.aws_sku', lang=resolved)} | {_mapping_source_column(field_alignment, 'sku')} | {t('field.sku', lang=resolved)} |",
|
||||
f"| {t('field.available_qty', lang=resolved)} | {_mapping_source_column(field_alignment, 'available_qty')} | {t('field.qty', lang=resolved)} |",
|
||||
f"| — | — | {t('align.table.display_only', lang=resolved)} |",
|
||||
]
|
||||
|
||||
if inv_count is not None or notice_count is not None:
|
||||
parts.append("")
|
||||
stat_bits = []
|
||||
if notice_count is not None:
|
||||
if resolved == "en":
|
||||
stat_bits.append(f"Order {notice_count} rows")
|
||||
elif resolved == "th":
|
||||
stat_bits.append(f"คำสั่งซื้อ {notice_count} แถว")
|
||||
else:
|
||||
stat_bits.append(f"订单 {notice_count} 行")
|
||||
if inv_count is not None:
|
||||
if resolved == "en":
|
||||
stat_bits.append(f"Inventory {inv_count} rows")
|
||||
elif resolved == "th":
|
||||
stat_bits.append(f"สต็อก {inv_count} แถว")
|
||||
else:
|
||||
stat_bits.append(f"库存 {inv_count} 行")
|
||||
if stat_bits:
|
||||
sep = "; " if resolved == "en" else ";"
|
||||
parts.append(t("align.stats", lang=resolved).format(stats=sep.join(stat_bits)))
|
||||
|
||||
sample_lines = _format_sample_lines(field_alignment, lang=resolved)
|
||||
if sample_lines:
|
||||
parts.append("")
|
||||
parts.extend(sample_lines)
|
||||
|
||||
warn_items = [str(w).strip() for w in (warnings or []) if str(w).strip()]
|
||||
for item in field_alignment.get("warnings") or []:
|
||||
text = str(item).strip()
|
||||
if text and text not in warn_items:
|
||||
warn_items.append(text)
|
||||
if warn_items:
|
||||
parts.append("")
|
||||
parts.append(t("common.tips", lang=resolved))
|
||||
for warning in warn_items[:8]:
|
||||
parts.append(f"- {_normalize_warning(warning, lang=resolved)}")
|
||||
|
||||
parts.extend(
|
||||
[
|
||||
"",
|
||||
t("align.confirm", lang=resolved),
|
||||
t("align.hint", lang=resolved),
|
||||
]
|
||||
)
|
||||
hint_btn = t("align.hint_btn", lang=resolved).strip()
|
||||
if hint_btn:
|
||||
parts.append(hint_btn)
|
||||
return "\n".join(parts).strip()
|
||||
@@ -0,0 +1,208 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import has_request_context, request
|
||||
|
||||
SUPPORTED_LANGS = ("zh", "en", "th")
|
||||
|
||||
_MESSAGES: dict[str, dict[str, str]] = {
|
||||
"zh": {
|
||||
"parse.title": "【发货通知解析确认】任务编号:{task_no}",
|
||||
"parse.no_lines": "未解析到订单明细行,请重新上传或重新解析。",
|
||||
"parse.low_conf": "解析置信度较低,请重点核对料号、预订单号、数量、单价与金额。",
|
||||
"parse.confirm": "请确认以上信息是否正确?",
|
||||
"parse.hint": "回复「确认」进入库存检查;「重新解析」重试;「驳回」终止本任务。",
|
||||
"parse.hint_btn": "",
|
||||
"align.title": "【库存字段对齐确认 — 确认后再匹配】任务编号:{task_no}",
|
||||
"align.match_rule": "匹配规则:{rule}{note}",
|
||||
"align.table.sys_field": "系统字段",
|
||||
"align.table.inv_col": "库存 Excel 列",
|
||||
"align.table.notice_field": "订单字段",
|
||||
"align.table.display_only": "unit_price / amount(展示用,不参与匹配)",
|
||||
"align.sample.notice": "订单样例:",
|
||||
"align.sample.inventory": "库存样例:",
|
||||
"align.stats": "统计:{stats}",
|
||||
"align.source.llm": "(LLM 推断)",
|
||||
"align.source.fallback": "(后端动态兜底)",
|
||||
"align.source.other": "({source})",
|
||||
"align.confirm": "请确认以上字段对齐是否正确。",
|
||||
"align.hint": "回复「确认」进入匹配;「更正映射」重选列;「重新上传」换库存文件;「驳回」终止本任务。",
|
||||
"align.hint_btn": "",
|
||||
"common.tips": "提示:",
|
||||
"table.field": "字段",
|
||||
"table.value": "值",
|
||||
"field.po": "采购单号",
|
||||
"field.sku": "料号",
|
||||
"field.reservation_id": "预订单号",
|
||||
"field.qty": "数量",
|
||||
"field.unit_price": "单价",
|
||||
"field.amount": "金额",
|
||||
"field.required_date": "需求日期",
|
||||
"field.ship_to": "收货方",
|
||||
"field.vendor_part_number": "供应商料号",
|
||||
"field.line_no": "项次",
|
||||
"field.available_qty": "可用数量",
|
||||
"field.aws_sku": "料号",
|
||||
"match.title": "【库存匹配结果】任务编号:{task_no}",
|
||||
"match.subtitle": "匹配明细(订单数量 vs 库存可用量)",
|
||||
"match.col.order_qty": "订单需求",
|
||||
"match.col.inv_qty": "库存可用",
|
||||
"match.col.gap": "缺口",
|
||||
"match.col.status": "状态",
|
||||
"match.status.ok": "✅ 充足",
|
||||
"match.status.partial": "⚠️ 部分满足",
|
||||
"match.status.shortage": "❌ 不足",
|
||||
"match.status.unknown": "未知",
|
||||
"match.conclusion.fulfillable": "**结论**:库存充足,可生成发货 Excel 并上传货代系统。",
|
||||
"match.conclusion.partial": "**结论**:部分行库存不足,请复核缺口后决定是否部分发货。",
|
||||
"match.conclusion.unfulfillable": "**结论**:库存均不足,无法整单发货。",
|
||||
"match.conclusion.other": "**结论**:match_status={status}",
|
||||
"match.no_lines": "无订单明细,无法比对数量。",
|
||||
},
|
||||
"en": {
|
||||
"parse.title": "[Shipping notice parsed] Task: {task_no}",
|
||||
"parse.no_lines": "No order lines found. Please re-upload or re-parse.",
|
||||
"parse.low_conf": "Low confidence. Please double-check SKU, Qty, Reservation ID, Unit Price and Amount.",
|
||||
"parse.confirm": "Please confirm the above information.",
|
||||
"parse.hint": 'Reply "Confirm" to proceed; "Re-parse" to retry; "Reject" to stop this task.',
|
||||
"parse.hint_btn": "",
|
||||
"align.title": "[Inventory mapping confirmation] Task: {task_no}",
|
||||
"align.match_rule": "Match rule: {rule}{note}",
|
||||
"align.table.sys_field": "System field",
|
||||
"align.table.inv_col": "Inventory column",
|
||||
"align.table.notice_field": "Order field",
|
||||
"align.table.display_only": "unit_price / amount (display only)",
|
||||
"align.sample.notice": "Order samples:",
|
||||
"align.sample.inventory": "Inventory samples:",
|
||||
"align.stats": "Stats: {stats}",
|
||||
"align.source.llm": " (LLM)",
|
||||
"align.source.fallback": " (backend fallback)",
|
||||
"align.source.other": " ({source})",
|
||||
"align.confirm": "Please confirm the field alignment above.",
|
||||
"align.hint": 'Reply "Confirm" to match; "Fix mapping" to reselect columns; "Re-upload" to change the inventory file; "Reject" to stop.',
|
||||
"align.hint_btn": "",
|
||||
"common.tips": "Notes:",
|
||||
"table.field": "Field",
|
||||
"table.value": "Value",
|
||||
"field.po": "PO",
|
||||
"field.sku": "SKU",
|
||||
"field.reservation_id": "Reservation ID",
|
||||
"field.qty": "Qty",
|
||||
"field.unit_price": "Unit Price",
|
||||
"field.amount": "Amount",
|
||||
"field.required_date": "Required date",
|
||||
"field.ship_to": "Ship to",
|
||||
"field.vendor_part_number": "Vendor PN",
|
||||
"field.line_no": "Line",
|
||||
"field.available_qty": "Available qty",
|
||||
"field.aws_sku": "AWS Sku",
|
||||
"match.title": "[Inventory match result] Task: {task_no}",
|
||||
"match.subtitle": "Match details (order qty vs inventory available)",
|
||||
"match.col.order_qty": "Order qty",
|
||||
"match.col.inv_qty": "Available",
|
||||
"match.col.gap": "Gap",
|
||||
"match.col.status": "Status",
|
||||
"match.status.ok": "✅ OK",
|
||||
"match.status.partial": "⚠️ Partial",
|
||||
"match.status.shortage": "❌ Short",
|
||||
"match.status.unknown": "Unknown",
|
||||
"match.conclusion.fulfillable": "**Result**: Inventory is sufficient. You may generate the shipment Excel and upload.",
|
||||
"match.conclusion.partial": "**Result**: Some lines are short. Review gaps before partial shipment.",
|
||||
"match.conclusion.unfulfillable": "**Result**: Insufficient inventory for all lines.",
|
||||
"match.conclusion.other": "**Result**: match_status={status}",
|
||||
"match.no_lines": "No order lines to compare.",
|
||||
},
|
||||
"th": {
|
||||
"parse.title": "【ยืนยันการแยกใบแจ้งส่งสินค้า】งาน: {task_no}",
|
||||
"parse.no_lines": "ไม่พบบรรทัดรายการสั่งซื้อ กรุณาอัปโหลดใหม่หรือแยกใหม่อีกครั้ง",
|
||||
"parse.low_conf": "ความมั่นใจต่ำ กรุณาตรวจสอบ SKU, จำนวน, Reservation ID, ราคาต่อหน่วย และจำนวนเงิน",
|
||||
"parse.confirm": "กรุณายืนยันว่าข้อมูลด้านบนถูกต้องหรือไม่",
|
||||
"parse.hint": 'พิมพ์ "ยืนยัน" เพื่อไปต่อ; "แยกใหม่" เพื่อลองใหม่; "ปฏิเสธ" เพื่อยุติงานนี้',
|
||||
"parse.hint_btn": "",
|
||||
"align.title": "【ยืนยันการจับคู่คอลัมน์สต็อก】งาน: {task_no}",
|
||||
"align.match_rule": "กฎการจับคู่: {rule}{note}",
|
||||
"align.table.sys_field": "ฟิลด์ระบบ",
|
||||
"align.table.inv_col": "คอลัมน์สต็อก",
|
||||
"align.table.notice_field": "ฟิลด์คำสั่งซื้อ",
|
||||
"align.table.display_only": "unit_price / amount (แสดงผลเท่านั้น)",
|
||||
"align.sample.notice": "ตัวอย่างคำสั่งซื้อ:",
|
||||
"align.sample.inventory": "ตัวอย่างสต็อก:",
|
||||
"align.stats": "สถิติ: {stats}",
|
||||
"align.source.llm": " (LLM)",
|
||||
"align.source.fallback": " (สำรองโดยระบบ)",
|
||||
"align.source.other": " ({source})",
|
||||
"align.confirm": "กรุณายืนยันว่าการจับคู่ฟิลด์ด้านบนถูกต้อง",
|
||||
"align.hint": 'พิมพ์ "ยืนยัน" เพื่อจับคู่; "แก้ไขการจับคู่" เพื่อเลือกคอลัมน์ใหม่; "อัปโหลดใหม่" เพื่อเปลี่ยนไฟล์สต็อก; "ปฏิเสธ" เพื่อยุติ',
|
||||
"align.hint_btn": "",
|
||||
"common.tips": "หมายเหตุ:",
|
||||
"table.field": "ฟิลด์",
|
||||
"table.value": "ค่า",
|
||||
"field.po": "PO",
|
||||
"field.sku": "SKU",
|
||||
"field.reservation_id": "Reservation ID",
|
||||
"field.qty": "จำนวน",
|
||||
"field.unit_price": "ราคาต่อหน่วย",
|
||||
"field.amount": "จำนวนเงิน",
|
||||
"field.required_date": "วันที่ต้องการ",
|
||||
"field.ship_to": "ผู้รับ",
|
||||
"field.vendor_part_number": "หมายเลขชิ้นส่วนผู้ขาย",
|
||||
"field.line_no": "รายการ",
|
||||
"field.available_qty": "จำนวนคงเหลือ",
|
||||
"field.aws_sku": "AWS Sku",
|
||||
"match.title": "【ผลการจับคู่สต็อก】งาน: {task_no}",
|
||||
"match.subtitle": "รายละเอียดการจับคู่ (จำนวนสั่งซื้อ vs สต็อกคงเหลือ)",
|
||||
"match.col.order_qty": "จำนวนสั่ง",
|
||||
"match.col.inv_qty": "สต็อกคงเหลือ",
|
||||
"match.col.gap": "ส่วนต่าง",
|
||||
"match.col.status": "สถานะ",
|
||||
"match.status.ok": "✅ เพียงพอ",
|
||||
"match.status.partial": "⚠️ บางส่วน",
|
||||
"match.status.shortage": "❌ ไม่พอ",
|
||||
"match.status.unknown": "ไม่ทราบ",
|
||||
"match.conclusion.fulfillable": "**สรุป**: สต็อกเพียงพอ สามารถสร้าง Excel และอัปโหลดได้",
|
||||
"match.conclusion.partial": "**สรุป**: บางรายการสต็อกไม่พอ กรุณาตรวจสอบส่วนต่าง",
|
||||
"match.conclusion.unfulfillable": "**สรุป**: สต็อกไม่เพียงพอทั้งหมด",
|
||||
"match.conclusion.other": "**สรุป**: match_status={status}",
|
||||
"match.no_lines": "ไม่มีรายการสั่งซื้อสำหรับเปรียบเทียบ",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def normalize_lang(raw: Any) -> str:
|
||||
text = str(raw or "").strip().lower()
|
||||
if not text:
|
||||
return "zh"
|
||||
if text in {"zh-cn", "zh_hans", "zh-hans", "cn", "zh"}:
|
||||
return "zh"
|
||||
if text in {"en-us", "en_us", "en"}:
|
||||
return "en"
|
||||
if text in {"th-th", "th_th", "th"}:
|
||||
return "th"
|
||||
for prefix in SUPPORTED_LANGS:
|
||||
if text.startswith(prefix):
|
||||
return prefix
|
||||
return "zh"
|
||||
|
||||
|
||||
def resolve_lang(payload: dict[str, Any] | None = None) -> str:
|
||||
if isinstance(payload, dict):
|
||||
for key in ("lang", "locale", "language"):
|
||||
if key in payload:
|
||||
val = str(payload.get(key) or "").strip()
|
||||
if val:
|
||||
return normalize_lang(val)
|
||||
|
||||
if has_request_context():
|
||||
hdr = str(request.headers.get("X-Lang") or "").strip()
|
||||
if hdr:
|
||||
return normalize_lang(hdr)
|
||||
accept = str(request.headers.get("Accept-Language") or "").strip()
|
||||
if accept:
|
||||
return normalize_lang(accept.split(",")[0].strip())
|
||||
return "zh"
|
||||
|
||||
|
||||
def t(key: str, *, lang: str | None = None) -> str:
|
||||
resolved = normalize_lang(lang) if lang else "zh"
|
||||
return _MESSAGES.get(resolved, {}).get(key) or _MESSAGES["zh"].get(key) or key
|
||||
@@ -0,0 +1,199 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
|
||||
|
||||
SYSTEM_FIELDS = ("sku", "reservation_id", "available_qty")
|
||||
|
||||
|
||||
def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
|
||||
data: dict[str, Any] | None = None
|
||||
if isinstance(raw, dict):
|
||||
data = raw
|
||||
elif isinstance(raw, str) and raw.strip():
|
||||
import json
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
if isinstance(parsed, dict):
|
||||
data = parsed
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
if not data:
|
||||
return None
|
||||
|
||||
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
|
||||
if not isinstance(inner, dict):
|
||||
return None
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for key in SYSTEM_FIELDS:
|
||||
value = inner.get(key)
|
||||
if value is None:
|
||||
continue
|
||||
text = str(value).strip()
|
||||
if text:
|
||||
result[key] = text
|
||||
return result if "sku" in result and "available_qty" in result and "reservation_id" in result else None
|
||||
|
||||
|
||||
def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
|
||||
"""Rule-based fallback mapping from header names."""
|
||||
from app.services.shipping_notice.inventory_snapshot import _column_map, _map_header
|
||||
|
||||
col_map = _column_map()
|
||||
norm_headers = [str(h or "").strip() for h in headers]
|
||||
lower_index = {h.lower(): h for h in norm_headers if h}
|
||||
|
||||
def pick(*candidates: str) -> str | None:
|
||||
for cand in candidates:
|
||||
if cand in norm_headers:
|
||||
return cand
|
||||
hit = lower_index.get(cand.lower())
|
||||
if hit:
|
||||
return hit
|
||||
for h in norm_headers:
|
||||
mapped = _map_header(h, col_map)
|
||||
if mapped in candidates:
|
||||
return h
|
||||
return None
|
||||
|
||||
mapping: dict[str, str] = {}
|
||||
sku = pick("sku", "AWS Sku", "AWS SKU", "料号", "Part Number", "Material")
|
||||
if sku:
|
||||
mapping["sku"] = sku
|
||||
|
||||
reservation = pick(
|
||||
"reservation_id",
|
||||
"Reservation ID",
|
||||
"COM ID",
|
||||
"Reservation Order",
|
||||
"Resevation Order",
|
||||
"Reservation No",
|
||||
)
|
||||
if reservation:
|
||||
mapping["reservation_id"] = reservation
|
||||
|
||||
qty = pick("available_qty", "Qty Available", "可用数量", "Available Qty", "On Hand Qty")
|
||||
if not qty:
|
||||
qty = pick("qty", "Qty", "数量", "Quantity")
|
||||
if qty:
|
||||
mapping["available_qty"] = qty
|
||||
|
||||
return mapping
|
||||
|
||||
|
||||
def mapping_is_complete(field_mapping: dict[str, str]) -> bool:
|
||||
return bool(field_mapping.get("sku") and field_mapping.get("available_qty") and field_mapping.get("reservation_id"))
|
||||
|
||||
|
||||
def validate_field_mapping_against_headers(
|
||||
headers: list[str],
|
||||
field_mapping: dict[str, str],
|
||||
) -> list[str]:
|
||||
"""Return error messages when mapped column names are missing from headers."""
|
||||
norm_headers = [str(h or "").strip() for h in headers]
|
||||
lower_set = {h.lower() for h in norm_headers if h}
|
||||
errors: list[str] = []
|
||||
labels = {
|
||||
"sku": "sku",
|
||||
"reservation_id": "reservation_id",
|
||||
"available_qty": "available_qty",
|
||||
}
|
||||
for key, label in labels.items():
|
||||
name = str(field_mapping.get(key) or "").strip()
|
||||
if not name:
|
||||
if key in ("sku", "available_qty", "reservation_id"):
|
||||
errors.append(f"缺少 {label} 列映射")
|
||||
continue
|
||||
if name not in norm_headers and name.lower() not in lower_set:
|
||||
preview = ", ".join(norm_headers[:8])
|
||||
if len(norm_headers) > 8:
|
||||
preview += "..."
|
||||
errors.append(f'列名 "{name}" 不在表头中(当前表头: {preview})')
|
||||
return errors
|
||||
|
||||
|
||||
def resolve_columns_from_field_mapping(
|
||||
headers: list[str],
|
||||
field_mapping: dict[str, str],
|
||||
) -> dict[str, int | None]:
|
||||
"""Map system fields to column indexes using explicit header names."""
|
||||
from app.services.shipping_notice.inventory_snapshot import DEFAULT_COLUMN_MAP, _resolve_inventory_columns
|
||||
|
||||
norm_headers = [str(h or "").strip() for h in headers]
|
||||
lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h}
|
||||
|
||||
def idx_for(header_name: str | None) -> int | None:
|
||||
if not header_name:
|
||||
return None
|
||||
name = str(header_name).strip()
|
||||
if not name:
|
||||
return None
|
||||
if name in norm_headers:
|
||||
return norm_headers.index(name)
|
||||
return lower_to_idx.get(name.lower())
|
||||
|
||||
# Keep auto-detected optional columns (e.g. odm_id / qty) even when the
|
||||
# required mapping is provided explicitly by LLM or user.
|
||||
columns = _resolve_inventory_columns(norm_headers, DEFAULT_COLUMN_MAP)
|
||||
columns.update({
|
||||
"sku": idx_for(field_mapping.get("sku")),
|
||||
"reservation_id": idx_for(field_mapping.get("reservation_id")),
|
||||
"available_qty": None,
|
||||
})
|
||||
avail_header = field_mapping.get("available_qty")
|
||||
if avail_header:
|
||||
columns["available_qty"] = idx_for(avail_header)
|
||||
return columns
|
||||
|
||||
|
||||
def build_column_meta_from_mapping(
|
||||
headers: list[str],
|
||||
field_mapping: dict[str, str],
|
||||
*,
|
||||
mapping_source: str = "rules",
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
columns = resolve_columns_from_field_mapping(headers, field_mapping)
|
||||
|
||||
def source_column(index: int | None) -> str | None:
|
||||
if index is None or index >= len(headers):
|
||||
return None
|
||||
text = str(headers[index] or "").strip()
|
||||
return text or None
|
||||
|
||||
qty_header = field_mapping.get("available_qty")
|
||||
match_rule, match_key, match_rule_source = resolve_match_rule(
|
||||
field_mapping,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
return {
|
||||
"headers": [str(h or "").strip() for h in headers],
|
||||
"mapping_source": mapping_source,
|
||||
"field_mapping": dict(field_mapping),
|
||||
"mapping": {
|
||||
"sku": {
|
||||
"system_field": "sku",
|
||||
"label": "AWS Sku / 料号",
|
||||
"source_column": source_column(columns.get("sku")),
|
||||
},
|
||||
"reservation_id": {
|
||||
"system_field": "reservation_id",
|
||||
"label": "Reservation ID",
|
||||
"source_column": source_column(columns.get("reservation_id")),
|
||||
},
|
||||
"available_qty": {
|
||||
"system_field": "available_qty",
|
||||
"label": "可用数量",
|
||||
"source_column": qty_header or source_column(columns.get("available_qty")),
|
||||
"qty_preference": "available_qty",
|
||||
},
|
||||
},
|
||||
"match_key": match_key,
|
||||
"match_rule": match_rule,
|
||||
"match_rule_source": match_rule_source,
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingInventoryMapping
|
||||
|
||||
|
||||
_GLOBAL_CUSTOMER_CODE = "GLOBAL"
|
||||
|
||||
|
||||
def _customer_key(customer_code: str | None) -> str:
|
||||
key = str(customer_code or "").strip()
|
||||
return key or _GLOBAL_CUSTOMER_CODE
|
||||
|
||||
|
||||
def compute_inventory_header_hash(headers: list[str], header_row_index: int | None = None) -> str:
|
||||
norm_headers = [str(h or "").strip() for h in headers]
|
||||
payload = {
|
||||
"header_row_index": int(header_row_index or 1),
|
||||
"headers": norm_headers,
|
||||
}
|
||||
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
return sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def find_inventory_mapping(customer_code: str | None, header_hash: str) -> ShippingInventoryMapping | None:
|
||||
customer = _customer_key(customer_code)
|
||||
if not header_hash:
|
||||
return None
|
||||
return ShippingInventoryMapping.query.filter_by(customer_code=customer, header_hash=header_hash).first()
|
||||
|
||||
|
||||
def resolve_inventory_mapping(
|
||||
customer_code: str | None,
|
||||
*,
|
||||
preview: dict[str, Any],
|
||||
) -> dict[str, str] | None:
|
||||
customer = _customer_key(customer_code)
|
||||
headers = preview.get("headers") if isinstance(preview.get("headers"), list) else []
|
||||
header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index"))
|
||||
record = find_inventory_mapping(customer, header_hash)
|
||||
if not record:
|
||||
return None
|
||||
record.last_used_at = datetime.utcnow()
|
||||
if isinstance(record.field_mapping_json, dict) and record.field_mapping_json:
|
||||
return {str(k): str(v) for k, v in record.field_mapping_json.items() if v}
|
||||
return None
|
||||
|
||||
|
||||
def upsert_inventory_mapping(
|
||||
customer_code: str | None,
|
||||
*,
|
||||
preview: dict[str, Any],
|
||||
field_mapping: dict[str, str],
|
||||
) -> ShippingInventoryMapping | None:
|
||||
customer = _customer_key(customer_code)
|
||||
headers = preview.get("headers") if isinstance(preview.get("headers"), list) else []
|
||||
header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index"))
|
||||
record = find_inventory_mapping(customer, header_hash)
|
||||
now = datetime.utcnow()
|
||||
if record:
|
||||
record.field_mapping_json = dict(field_mapping)
|
||||
record.headers_json = [str(h or "").strip() for h in headers]
|
||||
record.updated_at = now
|
||||
record.last_used_at = now
|
||||
return record
|
||||
record = ShippingInventoryMapping(
|
||||
customer_code=customer,
|
||||
header_hash=header_hash,
|
||||
headers_json=[str(h or "").strip() for h in headers],
|
||||
field_mapping_json=dict(field_mapping),
|
||||
last_used_at=now,
|
||||
)
|
||||
db.session.add(record)
|
||||
return record
|
||||
@@ -0,0 +1,622 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app.services.shipping_notice.reservation_id import extract_reservation_id, normalize_reservation_id
|
||||
|
||||
|
||||
# 默认列映射:含 AWS DUB On Hand Inventory 模板(AWS Sku / Reservation ID / Qty)
|
||||
DEFAULT_COLUMN_MAP = {
|
||||
# SKU
|
||||
"料号": "sku",
|
||||
"SKU": "sku",
|
||||
"sku": "sku",
|
||||
"AWS Sku": "sku",
|
||||
"AWS SKU": "sku",
|
||||
"Aws Sku": "sku",
|
||||
"AWS SKU#": "sku",
|
||||
"AWS Sku#": "sku",
|
||||
"SKU#": "sku",
|
||||
"Part No": "sku",
|
||||
"Part No.": "sku",
|
||||
"P/N": "sku",
|
||||
"PN": "sku",
|
||||
# Reservation
|
||||
"Reservation ID": "reservation_id",
|
||||
"Reservation Id": "reservation_id",
|
||||
"reservation_id": "reservation_id",
|
||||
"COM ID": "reservation_id",
|
||||
"Reservation Order": "reservation_id",
|
||||
# Quantity — 优先 Qty Available,其次 Qty
|
||||
"Qty Available": "available_qty",
|
||||
"Available": "available_qty",
|
||||
"Avail Qty": "available_qty",
|
||||
"可用数量": "available_qty",
|
||||
"可用量": "available_qty",
|
||||
"available_qty": "available_qty",
|
||||
"库存": "available_qty",
|
||||
"On Hand": "available_qty",
|
||||
"OnHand": "available_qty",
|
||||
"On Hand Qty": "available_qty",
|
||||
"OnHand Qty": "available_qty",
|
||||
"Qty On Hand": "available_qty",
|
||||
"Qty": "qty",
|
||||
"qty": "qty",
|
||||
"数量": "qty",
|
||||
# ODM
|
||||
"ODM ID": "odm_id",
|
||||
"ODM Id": "odm_id",
|
||||
"ODM Code": "odm_id",
|
||||
"Ship to ODM Code": "odm_id",
|
||||
"Ship To ODM Code": "odm_id",
|
||||
}
|
||||
|
||||
_RESERVATION_HEADER_PRIORITY = (
|
||||
"reservation_id",
|
||||
"Reservation ID",
|
||||
"COM ID",
|
||||
"Reservation Order",
|
||||
)
|
||||
|
||||
|
||||
def _column_map() -> dict[str, str]:
|
||||
raw = current_app.config.get("FREIGHT_INVENTORY_COLUMN_MAP")
|
||||
if isinstance(raw, dict) and raw:
|
||||
return {str(k): str(v) for k, v in raw.items()}
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
if isinstance(parsed, dict):
|
||||
return {str(k): str(v) for k, v in parsed.items()}
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return DEFAULT_COLUMN_MAP
|
||||
|
||||
|
||||
def _normalize_ascii_key(text: str) -> str:
|
||||
raw = str(text or "").strip().lower()
|
||||
if not raw:
|
||||
return ""
|
||||
return re.sub(r"[^a-z0-9]+", "", raw)
|
||||
|
||||
|
||||
def _map_header(header: str, col_map: dict[str, str]) -> str | None:
|
||||
text = str(header or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
if text in col_map:
|
||||
return col_map[text]
|
||||
lower = text.lower()
|
||||
for key, value in col_map.items():
|
||||
if key.lower() == lower:
|
||||
return value
|
||||
norm = _normalize_ascii_key(text)
|
||||
if not norm:
|
||||
return None
|
||||
norm_map = {_normalize_ascii_key(k): v for k, v in col_map.items() if _normalize_ascii_key(k)}
|
||||
return norm_map.get(norm)
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> dict[str, int | None]:
|
||||
idx_sku = idx_reservation = idx_available = idx_qty = idx_odm = None
|
||||
for i, h in enumerate(headers):
|
||||
mapped = _map_header(h, col_map)
|
||||
if mapped == "sku" and idx_sku is None:
|
||||
idx_sku = i
|
||||
elif mapped == "reservation_id" and idx_reservation is None:
|
||||
idx_reservation = i
|
||||
elif mapped == "available_qty" and idx_available is None:
|
||||
idx_available = i
|
||||
elif mapped == "qty" and idx_qty is None:
|
||||
idx_qty = i
|
||||
elif mapped == "odm_id" and idx_odm is None:
|
||||
idx_odm = i
|
||||
|
||||
# 若 reservation 列未命中,按 AWS 模板常见列名再试
|
||||
if idx_reservation is None:
|
||||
for i, h in enumerate(headers):
|
||||
norm = str(h or "").strip().lower()
|
||||
if norm in {"com id", "reservation order", "reservation id"}:
|
||||
idx_reservation = i
|
||||
break
|
||||
|
||||
return {
|
||||
"sku": idx_sku,
|
||||
"reservation_id": idx_reservation,
|
||||
"available_qty": idx_available,
|
||||
"qty": idx_qty,
|
||||
"odm_id": idx_odm,
|
||||
}
|
||||
|
||||
|
||||
def _cell(row: list[Any] | tuple[Any, ...], index: int | None) -> Any:
|
||||
if index is None or index >= len(row):
|
||||
return None
|
||||
return row[index]
|
||||
|
||||
|
||||
def _parse_qty(value: Any) -> float:
|
||||
try:
|
||||
return float(str(value).replace(",", "").strip())
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _normalize_inventory_row(
|
||||
row: list[Any] | tuple[Any, ...],
|
||||
columns: dict[str, int | None],
|
||||
*,
|
||||
default_sku_index: int = 0,
|
||||
default_qty_index: int = 1,
|
||||
) -> dict[str, Any] | None:
|
||||
idx_sku = columns.get("sku")
|
||||
if idx_sku is None:
|
||||
idx_sku = default_sku_index
|
||||
|
||||
sku = str(_cell(row, idx_sku) or "").strip()
|
||||
if not sku:
|
||||
return None
|
||||
|
||||
skip_tokens = {
|
||||
"sku",
|
||||
"料号",
|
||||
"aws sku",
|
||||
"qty",
|
||||
"qty available",
|
||||
"可用数量",
|
||||
"reservation id",
|
||||
"com id",
|
||||
}
|
||||
if sku.lower() in skip_tokens:
|
||||
return None
|
||||
|
||||
reservation_id = ""
|
||||
idx_res = columns.get("reservation_id")
|
||||
if idx_res is not None:
|
||||
reservation_id = extract_reservation_id(_cell(row, idx_res))
|
||||
|
||||
idx_avail = columns.get("available_qty")
|
||||
idx_qty = columns.get("qty")
|
||||
if idx_avail is not None:
|
||||
available_qty = _parse_qty(_cell(row, idx_avail))
|
||||
elif idx_qty is not None:
|
||||
available_qty = _parse_qty(_cell(row, idx_qty))
|
||||
else:
|
||||
available_qty = _parse_qty(_cell(row, default_qty_index))
|
||||
|
||||
parsed: dict[str, Any] = {
|
||||
"sku": sku,
|
||||
"available_qty": available_qty,
|
||||
}
|
||||
if reservation_id:
|
||||
parsed["reservation_id"] = reservation_id
|
||||
idx_odm = columns.get("odm_id")
|
||||
if idx_odm is not None:
|
||||
odm_id = str(_cell(row, idx_odm) or "").strip()
|
||||
if odm_id:
|
||||
parsed["odm_id"] = odm_id
|
||||
return parsed
|
||||
|
||||
|
||||
def _score_header_candidate(cells: list[Any]) -> int:
|
||||
"""Score how likely a row is the inventory column header (not a title row)."""
|
||||
headers = [str(c or "").strip() for c in cells]
|
||||
non_empty = [h for h in headers if h]
|
||||
if len(non_empty) < 2:
|
||||
return 0
|
||||
|
||||
col_map = _column_map()
|
||||
mapped_fields: set[str] = set()
|
||||
for h in headers:
|
||||
mapped = _map_header(h, col_map)
|
||||
if mapped:
|
||||
mapped_fields.add(mapped)
|
||||
|
||||
score = len(mapped_fields) * 10
|
||||
if "sku" in mapped_fields and ("available_qty" in mapped_fields or "qty" in mapped_fields):
|
||||
score += 30
|
||||
return score
|
||||
|
||||
|
||||
def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40) -> int:
|
||||
"""Pick the row that best matches known inventory column names (skip title rows)."""
|
||||
best_idx = 0
|
||||
best_score = 0
|
||||
for i, row in enumerate(rows[:max_scan]):
|
||||
score = _score_header_candidate(list(row))
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_idx = i
|
||||
return best_idx if best_score > 0 else 0
|
||||
|
||||
|
||||
def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[list[Any]], int]:
|
||||
"""Load worksheet rows; returns (rows, total_row_count_hint)."""
|
||||
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
|
||||
try:
|
||||
ws = wb.active
|
||||
rows: list[list[Any]] = []
|
||||
for i, row in enumerate(ws.iter_rows(values_only=True)):
|
||||
if max_rows is not None and i >= max_rows:
|
||||
break
|
||||
rows.append(list(row))
|
||||
total = ws.max_row or len(rows)
|
||||
finally:
|
||||
wb.close()
|
||||
return rows, int(total)
|
||||
|
||||
|
||||
def _rows_from_table_text(raw_text: str) -> list[list[str]]:
|
||||
rows: list[list[str]] = []
|
||||
for line in raw_text.splitlines():
|
||||
stripped = line.strip()
|
||||
if not stripped or re.match(r"^[\|\-\s]+$", stripped) or stripped.startswith("#"):
|
||||
continue
|
||||
if "|" in stripped:
|
||||
cells = [c.strip() for c in stripped.strip("|").split("|")]
|
||||
cells = [c for c in cells if c]
|
||||
elif "\t" in stripped:
|
||||
cells = [c.strip() for c in stripped.split("\t") if c.strip()]
|
||||
else:
|
||||
cells = [c.strip() for c in re.split(r"[,,;;]+", stripped) if c.strip()]
|
||||
if cells:
|
||||
rows.append(cells)
|
||||
return rows
|
||||
|
||||
|
||||
from app.services.shipping_notice.notice_lines import NOTICE_FIELD_LABELS
|
||||
|
||||
|
||||
def describe_inventory_columns(
|
||||
headers: list[str],
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Human-readable column mapping for field-alignment review."""
|
||||
if field_mapping:
|
||||
from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping
|
||||
|
||||
return build_column_meta_from_mapping(
|
||||
headers,
|
||||
field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
|
||||
|
||||
col_map = _column_map()
|
||||
columns = _resolve_inventory_columns(headers, col_map)
|
||||
|
||||
def source_column(index: int | None) -> str | None:
|
||||
if index is None or index >= len(headers):
|
||||
return None
|
||||
text = str(headers[index] or "").strip()
|
||||
return text or None
|
||||
|
||||
qty_source = source_column(columns.get("available_qty"))
|
||||
qty_note = "Qty Available"
|
||||
if not qty_source:
|
||||
qty_source = source_column(columns.get("qty"))
|
||||
qty_note = "Qty"
|
||||
|
||||
inferred_mapping: dict[str, str] = {}
|
||||
sku_src = source_column(columns.get("sku"))
|
||||
if sku_src:
|
||||
inferred_mapping["sku"] = sku_src
|
||||
rid_src = source_column(columns.get("reservation_id"))
|
||||
if rid_src:
|
||||
inferred_mapping["reservation_id"] = rid_src
|
||||
if qty_source:
|
||||
inferred_mapping["available_qty"] = qty_source
|
||||
|
||||
match_rule, match_key, match_rule_source = resolve_match_rule(
|
||||
inferred_mapping,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
|
||||
return {
|
||||
"headers": [str(h or "").strip() for h in headers],
|
||||
"mapping": {
|
||||
"sku": {
|
||||
"system_field": "sku",
|
||||
"label": "AWS Sku",
|
||||
"source_column": sku_src,
|
||||
},
|
||||
"reservation_id": {
|
||||
"system_field": "reservation_id",
|
||||
"label": "Reservation ID",
|
||||
"source_column": rid_src,
|
||||
"alternatives": list(_RESERVATION_HEADER_PRIORITY),
|
||||
},
|
||||
"available_qty": {
|
||||
"system_field": "available_qty",
|
||||
"label": "可用数量",
|
||||
"source_column": qty_source,
|
||||
"qty_preference": qty_note,
|
||||
},
|
||||
},
|
||||
"match_key": match_key,
|
||||
"match_rule": match_rule,
|
||||
"match_rule_source": match_rule_source,
|
||||
}
|
||||
|
||||
|
||||
def build_field_alignment_preview(
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
notice_lines: list[dict[str, Any]],
|
||||
*,
|
||||
column_meta: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Preview for human confirmation before match_inventory."""
|
||||
warnings: list[str] = []
|
||||
mapping = column_meta or {}
|
||||
inv_mapping = mapping.get("mapping") if isinstance(mapping.get("mapping"), dict) else {}
|
||||
|
||||
order_has_reservation = any(str(line.get("reservation_id") or "").strip() for line in notice_lines)
|
||||
inv_has_reservation = any(str(line.get("reservation_id") or "").strip() for line in inventory_lines)
|
||||
res_source = (inv_mapping.get("reservation_id") or {}).get("source_column")
|
||||
|
||||
if notice_lines and not order_has_reservation:
|
||||
warnings.append("订单未解析到 Reservation ID,但当前规则要求 Reservation ID 必填;请重新解析发货通知。")
|
||||
if inventory_lines and not inv_has_reservation:
|
||||
warnings.append("库存行未提供 Reservation ID(这些行将不参与匹配);如需按 Reservation ID 精确匹配,请补齐库存 Reservation ID。")
|
||||
if inventory_lines and not res_source:
|
||||
warnings.append("库存表未识别到 Reservation ID 相关列(COM ID / Reservation Order 等)。")
|
||||
|
||||
sku_source = (inv_mapping.get("sku") or {}).get("source_column")
|
||||
if notice_lines and inventory_lines and not sku_source:
|
||||
warnings.append("库存表未识别到 AWS Sku 列,当前按第一列作为料号解析。")
|
||||
|
||||
qty_source = (inv_mapping.get("available_qty") or {}).get("source_column")
|
||||
if inventory_lines and not qty_source:
|
||||
warnings.append("库存表未识别 Qty Available / Qty 列,请核对数量列映射。")
|
||||
|
||||
notice_preview = [
|
||||
{
|
||||
"sku": str(line.get("sku") or "").strip(),
|
||||
"reservation_id": str(line.get("reservation_id") or "").strip(),
|
||||
"qty": line.get("qty"),
|
||||
"unit_price": line.get("unit_price"),
|
||||
"amount": line.get("amount"),
|
||||
}
|
||||
for line in notice_lines[:5]
|
||||
]
|
||||
sample_inventory = [
|
||||
{
|
||||
"sku": line.get("sku"),
|
||||
"reservation_id": line.get("reservation_id", ""),
|
||||
"available_qty": line.get("available_qty"),
|
||||
}
|
||||
for line in inventory_lines[:5]
|
||||
]
|
||||
|
||||
field_mapping_meta = mapping.get("field_mapping") if isinstance(mapping.get("field_mapping"), dict) else {}
|
||||
fallback_mapping = {
|
||||
k: str((inv_mapping.get(k) or {}).get("source_column") or "").strip()
|
||||
for k in ("sku", "reservation_id", "available_qty")
|
||||
}
|
||||
fallback_mapping = {k: v for k, v in fallback_mapping.items() if v}
|
||||
if not fallback_mapping and field_mapping_meta:
|
||||
fallback_mapping = {k: str(v).strip() for k, v in field_mapping_meta.items() if str(v).strip()}
|
||||
|
||||
from app.services.shipping_notice.match_rule_desc import build_match_rule_fallback, resolve_match_rule
|
||||
|
||||
match_rule = str(mapping.get("match_rule") or "").strip()
|
||||
if not match_rule and fallback_mapping:
|
||||
match_rule = build_match_rule_fallback(
|
||||
fallback_mapping,
|
||||
match_key=mapping.get("match_key") if isinstance(mapping.get("match_key"), list) else None,
|
||||
)
|
||||
if not match_rule:
|
||||
match_rule, _, _ = resolve_match_rule(fallback_mapping or {"sku": "sku", "available_qty": "qty"})
|
||||
|
||||
return {
|
||||
"match_rule": match_rule,
|
||||
"match_rule_source": mapping.get("match_rule_source"),
|
||||
"inventory_columns": mapping,
|
||||
"notice_fields": NOTICE_FIELD_LABELS,
|
||||
"sample_notice_lines": notice_preview,
|
||||
"sample_inventory_lines": sample_inventory,
|
||||
"inventory_row_count": len(inventory_lines),
|
||||
"notice_line_count": len(notice_lines),
|
||||
"warnings": warnings,
|
||||
}
|
||||
|
||||
|
||||
def parse_inventory_rows(
|
||||
headers: list[str],
|
||||
data_rows: list[list[Any]],
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Parse inventory table rows (Excel or document-extractor text)."""
|
||||
if field_mapping:
|
||||
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
|
||||
|
||||
columns = resolve_columns_from_field_mapping(headers, field_mapping)
|
||||
else:
|
||||
col_map = _column_map()
|
||||
columns = _resolve_inventory_columns(headers, col_map)
|
||||
has_header = columns["sku"] is not None or columns["available_qty"] is not None or columns["qty"] is not None
|
||||
if not has_header and headers and not field_mapping:
|
||||
has_header = any(_map_header(h, _column_map()) for h in headers)
|
||||
|
||||
lines: list[dict[str, Any]] = []
|
||||
for row in data_rows:
|
||||
if not row:
|
||||
continue
|
||||
parsed = _normalize_inventory_row(list(row), columns)
|
||||
if parsed:
|
||||
lines.append(parsed)
|
||||
return lines
|
||||
|
||||
|
||||
def parse_inventory_text(
|
||||
raw_text: str,
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], list[str], dict[str, Any]]:
|
||||
"""Parse inventory from chat text or document-extractor output (Excel/CSV tables)."""
|
||||
warnings: list[str] = []
|
||||
empty_meta: dict[str, Any] = {"headers": [], "mapping": {}, "match_key": ["sku", "reservation_id"]}
|
||||
text = str(raw_text or "").strip()
|
||||
if not text:
|
||||
return [], ["empty inventory text"], empty_meta
|
||||
|
||||
rows = _rows_from_table_text(text)
|
||||
if not rows:
|
||||
return [], ["no table rows detected"], empty_meta
|
||||
|
||||
header = rows[0]
|
||||
if field_mapping:
|
||||
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
|
||||
|
||||
has_header = True
|
||||
column_meta = describe_inventory_columns(
|
||||
header,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source="manual",
|
||||
)
|
||||
else:
|
||||
col_map = _column_map()
|
||||
columns = _resolve_inventory_columns(header, col_map)
|
||||
has_header = columns["sku"] is not None or any(_map_header(h, col_map) for h in header)
|
||||
column_meta = describe_inventory_columns(header) if has_header else empty_meta
|
||||
|
||||
data_rows: list[list[Any]] = rows[1:] if has_header else rows
|
||||
|
||||
lines = parse_inventory_rows(
|
||||
header if has_header else [],
|
||||
data_rows if has_header else rows,
|
||||
field_mapping=field_mapping,
|
||||
)
|
||||
if not lines:
|
||||
warnings.append("no inventory lines parsed from text")
|
||||
return lines, warnings, column_meta
|
||||
|
||||
|
||||
def read_inventory_schema_preview(
|
||||
path: Path,
|
||||
*,
|
||||
max_sample_rows: int = 5,
|
||||
) -> dict[str, Any]:
|
||||
"""Read headers + sample rows only (safe for LLM context)."""
|
||||
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
|
||||
|
||||
scan_rows, total_rows = _load_excel_rows(path, max_rows=40)
|
||||
if not scan_rows:
|
||||
return {
|
||||
"headers": [],
|
||||
"sample_rows": [],
|
||||
"suggested_mapping": {},
|
||||
"row_count_hint": 0,
|
||||
"header_row_index": 1,
|
||||
}
|
||||
|
||||
header_idx = find_inventory_header_row_index(scan_rows)
|
||||
headers = [str(c or "").strip() for c in scan_rows[header_idx]]
|
||||
sample_rows = [
|
||||
[str(c) if c is not None else "" for c in r]
|
||||
for r in scan_rows[header_idx + 1 : header_idx + 1 + max_sample_rows]
|
||||
]
|
||||
suggested = suggest_field_mapping(headers)
|
||||
data_row_count = max(0, total_rows - header_idx - 1)
|
||||
return {
|
||||
"headers": headers,
|
||||
"sample_rows": sample_rows,
|
||||
"suggested_mapping": suggested,
|
||||
"header_row_index": header_idx + 1,
|
||||
"mapping_targets": {
|
||||
"sku": "料号 / AWS Sku",
|
||||
"reservation_id": "Reservation ID / COM ID(可选)",
|
||||
"available_qty": "可用数量 / Qty Available / Qty",
|
||||
"match_rule": "匹配规则说明(LLM 根据表头与订单字段生成,写入 map_json.match_rule)",
|
||||
},
|
||||
"row_count_hint": data_row_count,
|
||||
}
|
||||
|
||||
|
||||
def parse_inventory_excel_with_meta(
|
||||
path: Path,
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
header_row_index: int | None = None,
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
rows, _total = _load_excel_rows(path)
|
||||
if not rows:
|
||||
return [], {"headers": [], "mapping": {}, "match_key": ["sku", "reservation_id"]}
|
||||
|
||||
header_idx: int | None = None
|
||||
if header_row_index is not None:
|
||||
try:
|
||||
idx = int(header_row_index) - 1
|
||||
except (TypeError, ValueError):
|
||||
idx = -1
|
||||
if 0 <= idx < len(rows):
|
||||
header_idx = idx
|
||||
if header_idx is None:
|
||||
header_idx = find_inventory_header_row_index(rows)
|
||||
headers = [str(c or "").strip() for c in rows[header_idx]]
|
||||
data_rows = [list(r) for r in rows[header_idx + 1 :] if r]
|
||||
if not field_mapping:
|
||||
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
|
||||
|
||||
suggested = suggest_field_mapping(headers)
|
||||
if suggested.get("sku") and suggested.get("available_qty"):
|
||||
field_mapping = suggested
|
||||
mapping_source = "rules"
|
||||
|
||||
lines = parse_inventory_rows(headers, data_rows, field_mapping=field_mapping)
|
||||
meta = describe_inventory_columns(
|
||||
headers,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source if field_mapping else "rules",
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
meta["header_row_index"] = header_idx + 1
|
||||
return lines, meta
|
||||
|
||||
|
||||
def parse_inventory_excel(path: Path) -> list[dict[str, Any]]:
|
||||
lines, _meta = parse_inventory_excel_with_meta(path)
|
||||
return lines
|
||||
|
||||
|
||||
def ingest_inventory_file(
|
||||
source_path: Path,
|
||||
*,
|
||||
move_to: Path | None = None,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
lines, column_meta = parse_inventory_excel_with_meta(
|
||||
source_path,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
)
|
||||
if move_to:
|
||||
move_to.mkdir(parents=True, exist_ok=True)
|
||||
target = move_to / source_path.name
|
||||
if target.exists():
|
||||
target = move_to / f"{source_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{source_path.suffix}"
|
||||
shutil.move(str(source_path), str(target))
|
||||
return lines, column_meta
|
||||
@@ -0,0 +1,69 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_snapshot import (
|
||||
parse_inventory_excel_with_meta,
|
||||
read_inventory_schema_preview,
|
||||
)
|
||||
|
||||
|
||||
def inventory_text_max_chars() -> int:
|
||||
try:
|
||||
return int(current_app.config.get("SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS") or 80000)
|
||||
except (TypeError, ValueError):
|
||||
return 80000
|
||||
|
||||
|
||||
def task_inventory_upload_path(task_no: str) -> Path:
|
||||
safe = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
|
||||
return _storage_root() / "inventory_uploads" / safe / "inventory.xlsx"
|
||||
|
||||
|
||||
def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
|
||||
path = task_inventory_upload_path(task_no)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
upload.save(str(path))
|
||||
return path
|
||||
|
||||
|
||||
def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]:
|
||||
path = task_inventory_upload_path(task_no)
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = path.name
|
||||
return preview
|
||||
|
||||
|
||||
def parse_uploaded_task_inventory(
|
||||
task_no: str,
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
header_row_index: int | None = None,
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any], Path]:
|
||||
path = task_inventory_upload_path(task_no)
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
|
||||
lines, column_meta = parse_inventory_excel_with_meta(
|
||||
path,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=header_row_index,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
return lines, column_meta, path
|
||||
|
||||
|
||||
def has_uploaded_task_inventory(task_no: str) -> bool:
|
||||
return task_inventory_upload_path(task_no).is_file()
|
||||
@@ -0,0 +1,187 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.reservation_id import extract_reservation_id
|
||||
|
||||
|
||||
def _norm(value: Any) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
def _norm_reservation(value: Any) -> str:
|
||||
return extract_reservation_id(value)
|
||||
|
||||
|
||||
def _line_key(sku: str, reservation_id: str | None) -> tuple[str, str]:
|
||||
return (_norm(sku), _norm_reservation(reservation_id))
|
||||
|
||||
|
||||
def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[str, str], float]:
|
||||
"""Sum available_qty by (AWS Sku, Reservation ID). Same key rows are aggregated."""
|
||||
totals: dict[tuple[str, str], float] = {}
|
||||
for row in inventory_lines:
|
||||
sku = _norm(row.get("sku"))
|
||||
if not sku:
|
||||
continue
|
||||
reservation_id = _norm_reservation(row.get("reservation_id"))
|
||||
if not reservation_id:
|
||||
continue
|
||||
try:
|
||||
qty = float(row.get("available_qty") or 0)
|
||||
except (TypeError, ValueError):
|
||||
qty = 0.0
|
||||
key = _line_key(sku, reservation_id)
|
||||
totals[key] = totals.get(key, 0.0) + qty
|
||||
return totals
|
||||
|
||||
|
||||
def _available_for_notice_line(
|
||||
sku: str,
|
||||
reservation_id: str | None,
|
||||
inv_totals: dict[tuple[str, str], float],
|
||||
) -> float:
|
||||
sku_n = _norm(sku)
|
||||
rid = _norm_reservation(reservation_id)
|
||||
if not rid:
|
||||
return 0.0
|
||||
return inv_totals.get((sku_n, rid), 0.0)
|
||||
|
||||
|
||||
def match_notice_lines(
|
||||
notice_lines: list[dict[str, Any]],
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
) -> tuple[str, list[dict[str, Any]], dict[str, Any]]:
|
||||
inv_totals = _aggregate_inventory(inventory_lines)
|
||||
|
||||
line_results: list[dict[str, Any]] = []
|
||||
shortages: list[dict[str, Any]] = []
|
||||
has_partial = False
|
||||
has_shortage = False
|
||||
|
||||
for line in notice_lines:
|
||||
sku = _norm(line.get("sku"))
|
||||
reservation_id = _norm_reservation(line.get("reservation_id")) or None
|
||||
try:
|
||||
required = float(line.get("qty") or 0)
|
||||
except (TypeError, ValueError):
|
||||
required = 0.0
|
||||
|
||||
available = _available_for_notice_line(sku, reservation_id, inv_totals)
|
||||
if available >= required:
|
||||
line_status = "ok"
|
||||
shortage = 0.0
|
||||
elif available > 0:
|
||||
line_status = "partial"
|
||||
shortage = required - available
|
||||
has_partial = True
|
||||
else:
|
||||
line_status = "shortage"
|
||||
shortage = required
|
||||
has_shortage = True
|
||||
|
||||
result = {
|
||||
"sku": sku,
|
||||
"reservation_id": reservation_id or "",
|
||||
"required_qty": required,
|
||||
"available_qty": available,
|
||||
"shortage_qty": shortage,
|
||||
"line_status": line_status,
|
||||
}
|
||||
line_results.append(result)
|
||||
if shortage > 0:
|
||||
shortages.append(result)
|
||||
|
||||
if not notice_lines:
|
||||
return "unfulfillable", line_results, {"lines": shortages}
|
||||
|
||||
if has_shortage and not has_partial and all(r["line_status"] == "shortage" for r in line_results):
|
||||
match_status = "unfulfillable"
|
||||
elif has_partial or has_shortage:
|
||||
match_status = "partial"
|
||||
else:
|
||||
match_status = "fulfillable"
|
||||
|
||||
return match_status, line_results, {"lines": shortages}
|
||||
|
||||
|
||||
def _fmt_qty(value: float) -> str:
|
||||
if value == int(value):
|
||||
return str(int(value))
|
||||
return f"{value:g}"
|
||||
|
||||
|
||||
def _md_cell(value: Any) -> str:
|
||||
text = str(value or "").strip() or "-"
|
||||
return text.replace("|", "\\|")
|
||||
|
||||
|
||||
def format_match_summary(
|
||||
match_status: str,
|
||||
line_results: list[dict[str, Any]],
|
||||
*,
|
||||
task_no: str | None = None,
|
||||
lang: str | None = None,
|
||||
) -> str:
|
||||
"""Fixed Markdown table for match_inventory responses (Agent must display verbatim)."""
|
||||
resolved = resolve_lang({"lang": lang} if lang else None)
|
||||
if not line_results:
|
||||
return t("match.no_lines", lang=resolved)
|
||||
|
||||
lines: list[str] = []
|
||||
if task_no:
|
||||
lines.append(t("match.title", lang=resolved).format(task_no=task_no))
|
||||
lines.append("")
|
||||
lines.append(t("match.subtitle", lang=resolved))
|
||||
lines.append("")
|
||||
lines.append(
|
||||
"| # | "
|
||||
f"{t('field.reservation_id', lang=resolved)} | "
|
||||
f"{t('field.sku', lang=resolved)} | "
|
||||
f"{t('match.col.order_qty', lang=resolved)} | "
|
||||
f"{t('match.col.inv_qty', lang=resolved)} | "
|
||||
f"{t('match.col.gap', lang=resolved)} | "
|
||||
f"{t('match.col.status', lang=resolved)} |"
|
||||
)
|
||||
lines.append("|---:|---|---|---:|---:|---:|---|")
|
||||
|
||||
status_keys = {
|
||||
"ok": "match.status.ok",
|
||||
"partial": "match.status.partial",
|
||||
"shortage": "match.status.shortage",
|
||||
}
|
||||
for index, row in enumerate(line_results, 1):
|
||||
try:
|
||||
required = float(row.get("required_qty") or 0)
|
||||
except (TypeError, ValueError):
|
||||
required = 0.0
|
||||
try:
|
||||
available = float(row.get("available_qty") or 0)
|
||||
except (TypeError, ValueError):
|
||||
available = 0.0
|
||||
try:
|
||||
shortage = float(row.get("shortage_qty") or 0)
|
||||
except (TypeError, ValueError):
|
||||
shortage = 0.0
|
||||
status = str(row.get("line_status") or "")
|
||||
status_label = t(status_keys.get(status, "match.status.unknown"), lang=resolved)
|
||||
gap_cell = "-" if shortage <= 0 else _fmt_qty(shortage)
|
||||
lines.append(
|
||||
"| "
|
||||
f"{index} | "
|
||||
f"{_md_cell(row.get('reservation_id'))} | "
|
||||
f"{_md_cell(row.get('sku'))} | "
|
||||
f"{_fmt_qty(required)} | "
|
||||
f"{_fmt_qty(available)} | "
|
||||
f"{gap_cell} | "
|
||||
f"{status_label} |"
|
||||
)
|
||||
|
||||
lines.append("")
|
||||
conclusion_key = f"match.conclusion.{match_status}"
|
||||
conclusion = t(conclusion_key, lang=resolved)
|
||||
if conclusion == conclusion_key:
|
||||
conclusion = t("match.conclusion.other", lang=resolved).format(status=match_status)
|
||||
lines.append(conclusion)
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,94 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _payload_root(raw: Any) -> dict[str, Any] | None:
|
||||
data: dict[str, Any] | None = None
|
||||
if isinstance(raw, dict):
|
||||
data = raw
|
||||
elif isinstance(raw, str) and raw.strip():
|
||||
import json
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
if isinstance(parsed, dict):
|
||||
data = parsed
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
def extract_mapping_payload_extras(raw: Any) -> dict[str, Any]:
|
||||
"""Read optional LLM fields from map_json (not column names)."""
|
||||
data = _payload_root(raw)
|
||||
if not data:
|
||||
return {}
|
||||
|
||||
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
|
||||
if not isinstance(inner, dict):
|
||||
inner = data
|
||||
|
||||
match_rule = str(
|
||||
data.get("match_rule")
|
||||
or data.get("matching_rule")
|
||||
or inner.get("match_rule")
|
||||
or inner.get("matching_rule")
|
||||
or ""
|
||||
).strip()
|
||||
|
||||
match_key_raw = data.get("match_key") or inner.get("match_key")
|
||||
match_key: list[str] | None = None
|
||||
if isinstance(match_key_raw, list):
|
||||
match_key = [str(k).strip() for k in match_key_raw if str(k).strip()]
|
||||
elif isinstance(match_key_raw, str) and match_key_raw.strip():
|
||||
match_key = [part.strip() for part in match_key_raw.split(",") if part.strip()]
|
||||
|
||||
extras: dict[str, Any] = {}
|
||||
if match_rule:
|
||||
extras["match_rule"] = match_rule
|
||||
if match_key:
|
||||
extras["match_key"] = match_key
|
||||
return extras
|
||||
|
||||
|
||||
def infer_match_key(field_mapping: dict[str, str]) -> list[str]:
|
||||
keys = ["sku"]
|
||||
if str(field_mapping.get("reservation_id") or "").strip():
|
||||
keys.append("reservation_id")
|
||||
return keys
|
||||
|
||||
|
||||
def build_match_rule_fallback(
|
||||
field_mapping: dict[str, str],
|
||||
*,
|
||||
match_key: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Dynamic fallback when LLM did not supply match_rule."""
|
||||
sku_col = str(field_mapping.get("sku") or "sku").strip() or "sku"
|
||||
qty_col = str(field_mapping.get("available_qty") or "可用数量").strip() or "可用数量"
|
||||
keys = match_key or infer_match_key(field_mapping)
|
||||
|
||||
if "reservation_id" in keys:
|
||||
rid_col = str(field_mapping.get("reservation_id") or "Reservation ID").strip() or "Reservation ID"
|
||||
return (
|
||||
f"以库存列「{sku_col}」→ 订单 sku、「{rid_col}」→ 订单 reservation_id 为匹配键,"
|
||||
f"汇总「{qty_col}」可用量后与订单 qty 比对(库存缺 reservation_id 的行不参与)。"
|
||||
)
|
||||
return (
|
||||
f"以库存列「{sku_col}」→ 订单 sku 为匹配键,"
|
||||
f"汇总「{qty_col}」可用量后与订单 qty 比对。"
|
||||
)
|
||||
|
||||
|
||||
def resolve_match_rule(
|
||||
field_mapping: dict[str, str],
|
||||
*,
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> tuple[str, list[str], str]:
|
||||
"""Return (match_rule, match_key, match_rule_source)."""
|
||||
keys = llm_match_key or infer_match_key(field_mapping)
|
||||
if llm_match_rule and str(llm_match_rule).strip():
|
||||
return str(llm_match_rule).strip(), keys, "llm"
|
||||
return build_match_rule_fallback(field_mapping, match_key=keys), keys, "fallback"
|
||||
@@ -0,0 +1,751 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.reservation_id import (
|
||||
extract_reservation_id,
|
||||
find_reservation_id_in_document,
|
||||
looks_like_reservation_id,
|
||||
normalize_reservation_id,
|
||||
)
|
||||
|
||||
NOTICE_LINE_FIELDS = (
|
||||
"line_no",
|
||||
"sku",
|
||||
"qty",
|
||||
"unit_price",
|
||||
"amount",
|
||||
"currency",
|
||||
"reservation_id",
|
||||
"required_date",
|
||||
"vendor_part_number",
|
||||
"uom",
|
||||
"remark",
|
||||
)
|
||||
|
||||
# 订单行表头 → 系统字段(发货通知 PDF/Excel/邮件表格)
|
||||
NOTICE_COLUMN_MAP: dict[str, str] = {
|
||||
# SKU
|
||||
"料号": "sku",
|
||||
"SKU": "sku",
|
||||
"sku": "sku",
|
||||
"AWS Sku": "sku",
|
||||
"AWS SKU": "sku",
|
||||
"Part Number": "sku",
|
||||
"Material": "sku",
|
||||
"Material No": "sku",
|
||||
"产品编号": "sku",
|
||||
# 项次 / Item
|
||||
"项次": "line_no",
|
||||
"line_no": "line_no",
|
||||
"Line No": "line_no",
|
||||
"Line Number": "line_no",
|
||||
"Line #": "line_no",
|
||||
"Line": "line_no",
|
||||
"Item": "line_no",
|
||||
"Item No": "line_no",
|
||||
"Item Number": "line_no",
|
||||
# 需求数量
|
||||
"数量": "qty",
|
||||
"Qty": "qty",
|
||||
"qty": "qty",
|
||||
"Quantity": "qty",
|
||||
"需求数量": "qty",
|
||||
"订购数量": "qty",
|
||||
"Order Qty": "qty",
|
||||
"Ship Qty": "qty",
|
||||
"发货数量": "qty",
|
||||
# 单价
|
||||
"单价": "unit_price",
|
||||
"Unit Price": "unit_price",
|
||||
"unit_price": "unit_price",
|
||||
"Price": "unit_price",
|
||||
"Unit Cost": "unit_price",
|
||||
"价格": "unit_price",
|
||||
# 金额
|
||||
"金额": "amount",
|
||||
"Amount": "amount",
|
||||
"amount": "amount",
|
||||
"Total": "amount",
|
||||
"Line Amount": "amount",
|
||||
"Line Total": "amount",
|
||||
"小计": "amount",
|
||||
"总价": "amount",
|
||||
"Total Amount": "amount",
|
||||
# 币种
|
||||
"Currency": "currency",
|
||||
"currency": "currency",
|
||||
"Curr": "currency",
|
||||
"CCY": "currency",
|
||||
"币种": "currency",
|
||||
"币别": "currency",
|
||||
# Reservation ID
|
||||
"Reservation ID": "reservation_id",
|
||||
"Reservation Id": "reservation_id",
|
||||
"reservation_id": "reservation_id",
|
||||
"COM ID": "reservation_id",
|
||||
"Reservation Order": "reservation_id",
|
||||
"Reservation No": "reservation_id",
|
||||
"Resv ID": "reservation_id",
|
||||
"PR Number": "reservation_id",
|
||||
"PR No": "reservation_id",
|
||||
"PR#": "reservation_id",
|
||||
# 交货日期
|
||||
"Required Date": "required_date",
|
||||
"Delivery Date": "required_date",
|
||||
"required_date": "required_date",
|
||||
"ETA": "required_date",
|
||||
"交期": "required_date",
|
||||
"交货日期": "required_date",
|
||||
"要求交期": "required_date",
|
||||
"Required Delivery Date": "required_date",
|
||||
# 供应商料号
|
||||
"Vendor Part Number": "vendor_part_number",
|
||||
"Vendor Part No": "vendor_part_number",
|
||||
"Vendor PN": "vendor_part_number",
|
||||
"vendor_part_number": "vendor_part_number",
|
||||
"Supplier Part No": "vendor_part_number",
|
||||
"Supplier Part Number": "vendor_part_number",
|
||||
"MPN": "vendor_part_number",
|
||||
"供应商料号": "vendor_part_number",
|
||||
# 单位
|
||||
"单位": "uom",
|
||||
"UOM": "uom",
|
||||
"uom": "uom",
|
||||
"Unit": "uom",
|
||||
}
|
||||
|
||||
NOTICE_FIELD_LABELS = {
|
||||
"line_no": "项次 / Item / Line No",
|
||||
"sku": "SKU / 料号",
|
||||
"qty": "需求数量",
|
||||
"unit_price": "单价",
|
||||
"amount": "金额",
|
||||
"currency": "币种",
|
||||
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
|
||||
"required_date": "要求交期 / 交货日期",
|
||||
"vendor_part_number": "供应商料号",
|
||||
}
|
||||
|
||||
_HEADER_SKIP_TOKENS = {
|
||||
"sku",
|
||||
"料号",
|
||||
"aws sku",
|
||||
"qty",
|
||||
"quantity",
|
||||
"数量",
|
||||
"reservation id",
|
||||
"com id",
|
||||
"单价",
|
||||
"unit price",
|
||||
"金额",
|
||||
"amount",
|
||||
"currency",
|
||||
"币种",
|
||||
"line no",
|
||||
"item no",
|
||||
"项次",
|
||||
}
|
||||
|
||||
|
||||
def _norm_header(value: Any) -> str:
|
||||
return re.sub(r"\s+", " ", str(value or "").strip().lower())
|
||||
|
||||
|
||||
def _map_notice_header(header: str, col_map: dict[str, str] | None = None) -> str | None:
|
||||
text = str(header or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
mapping = col_map or NOTICE_COLUMN_MAP
|
||||
if text in mapping:
|
||||
return mapping[text]
|
||||
norm = _norm_header(text)
|
||||
for key, field in mapping.items():
|
||||
if _norm_header(key) == norm:
|
||||
return field
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_notice_columns(headers: list[str]) -> dict[str, int | None]:
|
||||
columns: dict[str, int | None] = {field: None for field in NOTICE_LINE_FIELDS if field not in {"uom", "remark"}}
|
||||
for i, header in enumerate(headers):
|
||||
mapped = _map_notice_header(header)
|
||||
if mapped and columns.get(mapped) is None:
|
||||
columns[mapped] = i
|
||||
|
||||
# Reservation 列名兜底
|
||||
if columns.get("reservation_id") is None:
|
||||
for i, header in enumerate(headers):
|
||||
norm = _norm_header(header)
|
||||
if norm in {"com id", "reservation order", "reservation id", "reservation no", "resv id"}:
|
||||
columns["reservation_id"] = i
|
||||
break
|
||||
return columns
|
||||
|
||||
|
||||
def _cell(row: list[Any] | tuple[Any, ...], index: int | None) -> Any:
|
||||
if index is None or index >= len(row):
|
||||
return None
|
||||
return row[index]
|
||||
|
||||
|
||||
def _normalize_line_no(value: Any) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return ""
|
||||
if text.lower() in _HEADER_SKIP_TOKENS:
|
||||
return ""
|
||||
num = _parse_number(text)
|
||||
if num is not None and num == int(num):
|
||||
compact = text.replace(",", "").replace(",", "")
|
||||
if re.fullmatch(r"\d+(?:\.0+)?", compact):
|
||||
return str(int(num))
|
||||
return text
|
||||
|
||||
|
||||
def _normalize_required_date(value: Any) -> str:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
m = re.match(r"^(\d{4})[/.-](\d{1,2})[/.-](\d{1,2})$", text)
|
||||
if m:
|
||||
return f"{m.group(1)}-{int(m.group(2)):02d}-{int(m.group(3)):02d}"
|
||||
return text
|
||||
|
||||
|
||||
_KNOWN_CURRENCY_CODES = frozenset(
|
||||
{
|
||||
"USD",
|
||||
"EUR",
|
||||
"GBP",
|
||||
"JPY",
|
||||
"CNY",
|
||||
"RMB",
|
||||
"HKD",
|
||||
"TWD",
|
||||
"SGD",
|
||||
"AUD",
|
||||
"CAD",
|
||||
"KRW",
|
||||
"INR",
|
||||
"CHF",
|
||||
"SEK",
|
||||
"NOK",
|
||||
"DKK",
|
||||
"MYR",
|
||||
"THB",
|
||||
"VND",
|
||||
"PHP",
|
||||
"IDR",
|
||||
"MXN",
|
||||
"BRL",
|
||||
"NZD",
|
||||
}
|
||||
)
|
||||
|
||||
_CURRENCY_ALIASES = {
|
||||
"人民币": "CNY",
|
||||
"美元": "USD",
|
||||
"欧元": "EUR",
|
||||
"英镑": "GBP",
|
||||
"日元": "JPY",
|
||||
"港币": "HKD",
|
||||
"港元": "HKD",
|
||||
"新台币": "TWD",
|
||||
"新加坡元": "SGD",
|
||||
"澳元": "AUD",
|
||||
"加元": "CAD",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_currency(value: Any) -> str:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
upper = text.upper()
|
||||
if upper in _KNOWN_CURRENCY_CODES:
|
||||
return "CNY" if upper == "RMB" else upper
|
||||
if text in _CURRENCY_ALIASES:
|
||||
return _CURRENCY_ALIASES[text]
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_currency(*values: Any) -> str:
|
||||
for value in values:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
continue
|
||||
normalized = _normalize_currency(text)
|
||||
if normalized:
|
||||
return normalized
|
||||
if text.startswith("$"):
|
||||
return "USD"
|
||||
if text.startswith("¥") or text.startswith("¥"):
|
||||
return "CNY"
|
||||
match = re.search(r"\b([A-Z]{3})\b", text.upper())
|
||||
if match and match.group(1) in _KNOWN_CURRENCY_CODES:
|
||||
code = match.group(1)
|
||||
return "CNY" if code == "RMB" else code
|
||||
return ""
|
||||
|
||||
|
||||
def _parse_number(value: Any) -> float | None:
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
text = text.replace(",", "").replace(",", "")
|
||||
if text.startswith("$") or text.startswith("¥") or text.startswith("¥"):
|
||||
text = text[1:].strip()
|
||||
match = re.search(r"[-+]?\d+(?:\.\d+)?", text)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
return float(match.group(0))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _infer_reservation_id_from_row(
|
||||
row: list[Any] | tuple[Any, ...],
|
||||
*,
|
||||
skip_indices: set[int],
|
||||
) -> str:
|
||||
for i, cell in enumerate(row):
|
||||
if i in skip_indices:
|
||||
continue
|
||||
if looks_like_reservation_id(cell):
|
||||
return extract_reservation_id(cell)
|
||||
return ""
|
||||
|
||||
|
||||
def _parse_notice_row(
|
||||
row: list[Any] | tuple[Any, ...],
|
||||
columns: dict[str, int | None],
|
||||
*,
|
||||
default_sku_index: int = 0,
|
||||
default_qty_index: int = 1,
|
||||
) -> dict[str, Any] | None:
|
||||
idx_sku = columns.get("sku")
|
||||
if idx_sku is None:
|
||||
idx_sku = default_sku_index
|
||||
|
||||
sku = str(_cell(row, idx_sku) or "").strip()
|
||||
if not sku:
|
||||
return None
|
||||
if sku.lower() in _HEADER_SKIP_TOKENS:
|
||||
return None
|
||||
|
||||
idx_qty = columns.get("qty")
|
||||
if idx_qty is not None:
|
||||
qty = _parse_number(_cell(row, idx_qty))
|
||||
else:
|
||||
qty = _parse_number(_cell(row, default_qty_index))
|
||||
if qty is None or qty <= 0:
|
||||
return None
|
||||
|
||||
parsed: dict[str, Any] = {"sku": sku, "qty": qty, "uom": "EA"}
|
||||
|
||||
skip_indices: set[int] = {idx_sku}
|
||||
if idx_qty is not None:
|
||||
skip_indices.add(idx_qty)
|
||||
|
||||
idx_line_no = columns.get("line_no")
|
||||
if idx_line_no is not None:
|
||||
line_no = _normalize_line_no(_cell(row, idx_line_no))
|
||||
skip_indices.add(idx_line_no)
|
||||
if line_no:
|
||||
parsed["line_no"] = line_no
|
||||
|
||||
idx_res = columns.get("reservation_id")
|
||||
reservation_id = ""
|
||||
if idx_res is not None:
|
||||
reservation_id = extract_reservation_id(_cell(row, idx_res))
|
||||
skip_indices.add(idx_res)
|
||||
else:
|
||||
reservation_id = _infer_reservation_id_from_row(row, skip_indices=skip_indices)
|
||||
if reservation_id:
|
||||
parsed["reservation_id"] = reservation_id
|
||||
|
||||
idx_price = columns.get("unit_price")
|
||||
price_cell = None
|
||||
if idx_price is not None:
|
||||
price_cell = _cell(row, idx_price)
|
||||
unit_price = _parse_number(price_cell)
|
||||
if unit_price is not None:
|
||||
parsed["unit_price"] = unit_price
|
||||
|
||||
idx_amount = columns.get("amount")
|
||||
amount_cell = None
|
||||
if idx_amount is not None:
|
||||
amount_cell = _cell(row, idx_amount)
|
||||
amount = _parse_number(amount_cell)
|
||||
if amount is not None:
|
||||
parsed["amount"] = amount
|
||||
|
||||
idx_currency = columns.get("currency")
|
||||
currency = _extract_currency(
|
||||
_cell(row, idx_currency) if idx_currency is not None else None,
|
||||
price_cell,
|
||||
amount_cell,
|
||||
)
|
||||
if currency:
|
||||
parsed["currency"] = currency
|
||||
|
||||
idx_uom = columns.get("uom")
|
||||
if idx_uom is not None:
|
||||
uom = str(_cell(row, idx_uom) or "").strip()
|
||||
if uom:
|
||||
parsed["uom"] = uom
|
||||
|
||||
idx_required_date = columns.get("required_date")
|
||||
if idx_required_date is not None:
|
||||
required_date = _normalize_required_date(_cell(row, idx_required_date))
|
||||
if required_date:
|
||||
parsed["required_date"] = required_date
|
||||
|
||||
idx_vendor_part = columns.get("vendor_part_number")
|
||||
if idx_vendor_part is not None:
|
||||
vendor_part_number = str(_cell(row, idx_vendor_part) or "").strip()
|
||||
if vendor_part_number:
|
||||
parsed["vendor_part_number"] = vendor_part_number
|
||||
|
||||
# 若仅有 qty * unit_price,可推算 amount
|
||||
if "amount" not in parsed and "unit_price" in parsed:
|
||||
computed = round(parsed["unit_price"] * qty, 4)
|
||||
if computed > 0:
|
||||
parsed["amount"] = computed
|
||||
|
||||
return parsed
|
||||
|
||||
|
||||
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
|
||||
sku = str(raw.get("sku") or raw.get("part_number") or raw.get("material") or "").strip()
|
||||
if not sku:
|
||||
return None
|
||||
|
||||
qty = _parse_number(raw.get("qty") if raw.get("qty") is not None else raw.get("quantity"))
|
||||
if qty is None or qty <= 0:
|
||||
return None
|
||||
|
||||
line: dict[str, Any] = {
|
||||
"sku": sku,
|
||||
"qty": qty,
|
||||
"uom": str(raw.get("uom") or "EA").strip() or "EA",
|
||||
}
|
||||
|
||||
line_no = _normalize_line_no(
|
||||
raw.get("line_no")
|
||||
or raw.get("lineNo")
|
||||
or raw.get("item")
|
||||
or raw.get("item_no")
|
||||
or raw.get("itemNo")
|
||||
or raw.get("Item")
|
||||
or raw.get("Item No")
|
||||
)
|
||||
if line_no:
|
||||
line["line_no"] = line_no
|
||||
|
||||
reservation_id = extract_reservation_id(
|
||||
raw.get("reservation_id")
|
||||
or raw.get("reservationId")
|
||||
or raw.get("com_id")
|
||||
or raw.get("reservation_order")
|
||||
or raw.get("pr_number")
|
||||
or raw.get("prNumber")
|
||||
or raw.get("PR Number")
|
||||
)
|
||||
if reservation_id:
|
||||
line["reservation_id"] = reservation_id
|
||||
|
||||
unit_price = _parse_number(raw.get("unit_price") if raw.get("unit_price") is not None else raw.get("price"))
|
||||
if unit_price is not None:
|
||||
line["unit_price"] = unit_price
|
||||
|
||||
amount = _parse_number(raw.get("amount") if raw.get("amount") is not None else raw.get("total"))
|
||||
if amount is not None:
|
||||
line["amount"] = amount
|
||||
elif unit_price is not None:
|
||||
line["amount"] = round(unit_price * qty, 4)
|
||||
|
||||
currency = _normalize_currency(raw.get("currency") or raw.get("Currency"))
|
||||
if not currency:
|
||||
currency = _extract_currency(
|
||||
raw.get("unit_price"),
|
||||
raw.get("price"),
|
||||
raw.get("amount"),
|
||||
raw.get("total"),
|
||||
)
|
||||
if currency:
|
||||
line["currency"] = currency
|
||||
|
||||
required_date = _normalize_required_date(
|
||||
raw.get("required_date")
|
||||
or raw.get("delivery_date")
|
||||
or raw.get("deliveryDate")
|
||||
or raw.get("eta")
|
||||
or raw.get("ETA")
|
||||
)
|
||||
if required_date:
|
||||
line["required_date"] = required_date
|
||||
|
||||
vendor_part_number = str(
|
||||
raw.get("vendor_part_number")
|
||||
or raw.get("vendorPartNumber")
|
||||
or raw.get("vendor_pn")
|
||||
or raw.get("supplier_part_number")
|
||||
or raw.get("supplierPartNumber")
|
||||
or ""
|
||||
).strip()
|
||||
if vendor_part_number:
|
||||
line["vendor_part_number"] = vendor_part_number
|
||||
|
||||
remark = str(raw.get("remark") or raw.get("note") or "").strip()
|
||||
if remark:
|
||||
line["remark"] = remark
|
||||
|
||||
return line
|
||||
|
||||
|
||||
def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
|
||||
if not isinstance(lines, list):
|
||||
return []
|
||||
normalized: list[dict[str, Any]] = []
|
||||
for item in lines:
|
||||
parsed = normalize_notice_line(item if isinstance(item, dict) else None)
|
||||
if parsed:
|
||||
normalized.append(parsed)
|
||||
return normalized
|
||||
|
||||
|
||||
def enrich_notice_with_document_reservation(
|
||||
parsed: dict[str, Any],
|
||||
*,
|
||||
raw_text: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""Apply document-level PR Number / @1000140351 reservation id to lines missing it."""
|
||||
doc_rid = ""
|
||||
for key in (
|
||||
"reservation_id",
|
||||
"reservationId",
|
||||
"document_reservation_id",
|
||||
"pr_number",
|
||||
"prNumber",
|
||||
"PR Number",
|
||||
):
|
||||
extracted = extract_reservation_id(parsed.get(key))
|
||||
if extracted and looks_like_reservation_id(extracted):
|
||||
doc_rid = extracted
|
||||
break
|
||||
|
||||
if not doc_rid:
|
||||
doc_rid = find_reservation_id_in_document(raw_text)
|
||||
|
||||
if not doc_rid:
|
||||
return parsed
|
||||
|
||||
lines = parsed.get("lines")
|
||||
if not isinstance(lines, list):
|
||||
return parsed
|
||||
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
if not str(line.get("reservation_id") or "").strip():
|
||||
line["reservation_id"] = doc_rid
|
||||
|
||||
parsed["reservation_id"] = doc_rid
|
||||
parsed.pop("document_reservation_id", None)
|
||||
return parsed
|
||||
|
||||
|
||||
def enrich_notice_with_document_required_date(parsed: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Apply document-level required_date to lines missing their own delivery date."""
|
||||
doc_date = _normalize_required_date(
|
||||
parsed.get("required_date") or parsed.get("document_required_date")
|
||||
)
|
||||
if not doc_date:
|
||||
return parsed
|
||||
|
||||
lines = parsed.get("lines")
|
||||
if not isinstance(lines, list):
|
||||
return parsed
|
||||
|
||||
has_line_dates = any(
|
||||
isinstance(line, dict) and str(line.get("required_date") or "").strip() for line in lines
|
||||
)
|
||||
if not has_line_dates:
|
||||
parsed["required_date"] = doc_date
|
||||
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
if not str(line.get("required_date") or "").strip():
|
||||
line["required_date"] = doc_date
|
||||
|
||||
parsed.pop("document_required_date", None)
|
||||
return parsed
|
||||
|
||||
|
||||
def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Apply document-level currency to lines missing their own currency."""
|
||||
doc_currency = _normalize_currency(
|
||||
parsed.get("currency") or parsed.get("document_currency")
|
||||
)
|
||||
if not doc_currency:
|
||||
return parsed
|
||||
|
||||
lines = parsed.get("lines")
|
||||
if not isinstance(lines, list):
|
||||
return parsed
|
||||
|
||||
has_line_currency = any(
|
||||
isinstance(line, dict) and str(line.get("currency") or "").strip() for line in lines
|
||||
)
|
||||
if not has_line_currency:
|
||||
parsed["currency"] = doc_currency
|
||||
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
if not str(line.get("currency") or "").strip():
|
||||
line["currency"] = doc_currency
|
||||
|
||||
parsed.pop("document_currency", None)
|
||||
return parsed
|
||||
|
||||
|
||||
def parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]:
|
||||
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
|
||||
|
||||
text = str(raw_text or "").strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
rows = _rows_from_table_text(text)
|
||||
if not rows:
|
||||
return []
|
||||
|
||||
header_idx = _find_notice_header_row_index(rows)
|
||||
header = [str(c or "").strip() for c in rows[header_idx]]
|
||||
data_rows = rows[header_idx + 1 :]
|
||||
lines = parse_notice_table_rows(header, data_rows)
|
||||
doc_rid = find_reservation_id_in_document(text)
|
||||
if doc_rid:
|
||||
for line in lines:
|
||||
if not line.get("reservation_id"):
|
||||
line["reservation_id"] = doc_rid
|
||||
return lines
|
||||
|
||||
|
||||
def _score_notice_header_row(cells: list[Any]) -> int:
|
||||
headers = [str(c or "").strip() for c in cells]
|
||||
if len([h for h in headers if h]) < 2:
|
||||
return 0
|
||||
mapped: set[str] = set()
|
||||
for h in headers:
|
||||
field = _map_notice_header(h)
|
||||
if field:
|
||||
mapped.add(field)
|
||||
score = len(mapped) * 10
|
||||
if "sku" in mapped and "qty" in mapped:
|
||||
score += 30
|
||||
if "reservation_id" in mapped:
|
||||
score += 10
|
||||
if "unit_price" in mapped or "amount" in mapped:
|
||||
score += 5
|
||||
return score
|
||||
|
||||
|
||||
def _find_notice_header_row_index(rows: list[list[Any]], *, max_scan: int = 40) -> int:
|
||||
best_idx = 0
|
||||
best_score = 0
|
||||
for i, row in enumerate(rows[:max_scan]):
|
||||
score = _score_notice_header_row(list(row))
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
best_idx = i
|
||||
return best_idx if best_score > 0 else 0
|
||||
|
||||
|
||||
def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> list[dict[str, Any]]:
|
||||
columns = _resolve_notice_columns(headers)
|
||||
has_header = columns.get("sku") is not None or columns.get("qty") is not None
|
||||
if not has_header and headers:
|
||||
has_header = any(_map_notice_header(h) for h in headers)
|
||||
if not has_header:
|
||||
return []
|
||||
|
||||
lines: list[dict[str, Any]] = []
|
||||
for row in data_rows:
|
||||
if not row:
|
||||
continue
|
||||
parsed = _parse_notice_row(list(row), columns)
|
||||
if parsed:
|
||||
lines.append(parsed)
|
||||
return lines
|
||||
|
||||
|
||||
def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
|
||||
warnings: list[str] = []
|
||||
if not lines:
|
||||
warnings.append("未解析到有效订单行(需至少包含 SKU 与需求数量)。")
|
||||
return warnings
|
||||
|
||||
missing_reservation = [line["sku"] for line in lines if not str(line.get("reservation_id") or "").strip()]
|
||||
if missing_reservation and len(missing_reservation) == len(lines):
|
||||
warnings.append(
|
||||
"订单行未解析到 Reservation ID;后续将仅按 SKU 汇总库存比对,"
|
||||
"若订单含 COM ID / Reservation Order 请核对表头。"
|
||||
)
|
||||
elif missing_reservation:
|
||||
warnings.append(
|
||||
f"部分订单行缺少 Reservation ID({len(missing_reservation)}/{len(lines)} 行),"
|
||||
"这些行将按 SKU 汇总库存比对。"
|
||||
)
|
||||
|
||||
invalid_reservation = [
|
||||
line["sku"]
|
||||
for line in lines
|
||||
if str(line.get("reservation_id") or "").strip()
|
||||
and not looks_like_reservation_id(line.get("reservation_id"))
|
||||
]
|
||||
if invalid_reservation:
|
||||
warnings.append(
|
||||
f"{len(invalid_reservation)} 行 Reservation ID 非典型纯数字格式(常见为 8~12 位,如 1000140351),"
|
||||
"请核对是否解析正确。"
|
||||
)
|
||||
|
||||
missing_price = sum(1 for line in lines if line.get("unit_price") is None and line.get("amount") is None)
|
||||
if missing_price:
|
||||
warnings.append(f"{missing_price} 行未解析到单价或金额(不影响库存匹配)。")
|
||||
|
||||
return warnings
|
||||
|
||||
|
||||
def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
|
||||
"""0~1 score for how complete order lines are (sku/qty/reservation/price)."""
|
||||
if not lines:
|
||||
return 0.0
|
||||
scores: list[float] = []
|
||||
for line in lines:
|
||||
item = 0.0
|
||||
if line.get("sku"):
|
||||
item += 0.35
|
||||
if line.get("qty"):
|
||||
item += 0.35
|
||||
if line.get("reservation_id"):
|
||||
item += 0.15
|
||||
if line.get("unit_price") is not None or line.get("amount") is not None:
|
||||
item += 0.15
|
||||
scores.append(item)
|
||||
return round(sum(scores) / len(scores), 4)
|
||||
@@ -0,0 +1,162 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import re
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from edkb_system.contracts import Block, Context
|
||||
from edkb_system.skills import loader_csv, loader_docx, loader_pdf, ocr
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
|
||||
|
||||
def task_notice_upload_path(task_no: str, filename: str) -> Path:
|
||||
safe_task = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
|
||||
name = str(filename or "").strip() or "notice"
|
||||
safe_name = re.sub(r"[^\w\-.]+", "_", name)[:120] or "notice"
|
||||
return _storage_root() / "notice_uploads" / safe_task / safe_name
|
||||
|
||||
|
||||
def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path:
|
||||
path = task_notice_upload_path(task_no, filename)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(data)
|
||||
return path
|
||||
|
||||
|
||||
def _decode_text(data: bytes) -> str:
|
||||
if not data:
|
||||
return ""
|
||||
for enc in ("utf-8", "utf-8-sig", "gb18030", "gbk"):
|
||||
try:
|
||||
return data.decode(enc)
|
||||
except Exception:
|
||||
continue
|
||||
return data.decode("utf-8", errors="ignore")
|
||||
|
||||
|
||||
def _html_to_text(html: str) -> str:
|
||||
s = re.sub(r"(?is)<(script|style).*?>.*?</\\1>", "", html or "")
|
||||
s = re.sub(r"(?is)<br\\s*/?>", "\n", s)
|
||||
s = re.sub(r"(?is)</p\\s*>", "\n", s)
|
||||
s = re.sub(r"(?is)<[^>]+>", " ", s)
|
||||
s = re.sub(r"[ \t]+", " ", s)
|
||||
s = re.sub(r"\\n\\s*\\n+", "\n\n", s)
|
||||
return s.strip()
|
||||
|
||||
|
||||
def _eml_to_text(data: bytes) -> str:
|
||||
msg = BytesParser(policy=policy.default).parsebytes(data)
|
||||
parts: list[str] = []
|
||||
subject = str(msg.get("subject") or "").strip()
|
||||
if subject:
|
||||
parts.append(f"Subject: {subject}")
|
||||
if msg.is_multipart():
|
||||
for part in msg.walk():
|
||||
if part.is_multipart():
|
||||
continue
|
||||
ctype = str(part.get_content_type() or "")
|
||||
payload = part.get_payload(decode=True) or b""
|
||||
if ctype == "text/plain":
|
||||
parts.append(_decode_text(payload).strip())
|
||||
elif ctype == "text/html":
|
||||
parts.append(_html_to_text(_decode_text(payload)).strip())
|
||||
else:
|
||||
payload = msg.get_payload(decode=True) or b""
|
||||
ctype = str(msg.get_content_type() or "")
|
||||
if ctype == "text/html":
|
||||
parts.append(_html_to_text(_decode_text(payload)).strip())
|
||||
else:
|
||||
parts.append(_decode_text(payload).strip())
|
||||
return "\n\n".join(x for x in parts if x)
|
||||
|
||||
|
||||
def _image_bytes_to_blocks(raw: bytes) -> list[Block]:
|
||||
if not raw:
|
||||
return []
|
||||
data_uri = "data:image/png;base64," + base64.b64encode(raw).decode("ascii")
|
||||
return [
|
||||
Block(
|
||||
id="img-1",
|
||||
page=1,
|
||||
type="image",
|
||||
text="",
|
||||
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
||||
meta={"data_uri": data_uri},
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _blocks_to_text(blocks: list[Block]) -> str:
|
||||
lines: list[str] = []
|
||||
for b in blocks:
|
||||
if b.type not in {"paragraph", "ocr_text"}:
|
||||
continue
|
||||
txt = str(b.text or "").strip()
|
||||
if not txt:
|
||||
continue
|
||||
if b.type == "ocr_text":
|
||||
if txt.startswith("OCR_TEXT:"):
|
||||
txt = txt[len("OCR_TEXT:") :].strip()
|
||||
txt = re.sub(r"(?m)^\s*-\s*", "", txt).strip()
|
||||
lines.append(txt)
|
||||
text = "\n\n".join(lines)
|
||||
text = re.sub(r"\n{3,}", "\n\n", text).strip()
|
||||
return text
|
||||
|
||||
|
||||
def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]:
|
||||
path = Path(file_path)
|
||||
ext = path.suffix.lower().lstrip(".")
|
||||
ctx = Context(file_type=ext)
|
||||
warnings: list[str] = []
|
||||
|
||||
if ext in {"txt", "md", "log"}:
|
||||
return _decode_text(path.read_bytes()).strip(), {"warnings": warnings, "file_type": ext}
|
||||
if ext in {"html", "htm"}:
|
||||
return _html_to_text(_decode_text(path.read_bytes())), {"warnings": warnings, "file_type": ext}
|
||||
if ext in {"eml"}:
|
||||
return _eml_to_text(path.read_bytes()), {"warnings": warnings, "file_type": ext}
|
||||
|
||||
blocks: list[Block] = []
|
||||
if ext in {"pdf"}:
|
||||
blocks = loader_pdf.run({"file_path": str(path)}, ctx)
|
||||
elif ext in {"docx"}:
|
||||
blocks = loader_docx.run({"file_path": str(path)}, ctx)
|
||||
elif ext in {"csv"}:
|
||||
blocks = loader_csv.run({"file_path": str(path)}, ctx)
|
||||
elif ext in {"png", "jpg", "jpeg", "webp"}:
|
||||
blocks = _image_bytes_to_blocks(path.read_bytes())
|
||||
else:
|
||||
warnings.append(f"unsupported_file_type:{ext}")
|
||||
|
||||
if blocks:
|
||||
has_images = any(b.type == "image" for b in blocks)
|
||||
if has_images:
|
||||
blocks = ocr.run(blocks, ctx)
|
||||
text = _blocks_to_text(blocks)
|
||||
return text.strip(), {"warnings": warnings + list(ctx.warnings), "file_type": ext}
|
||||
|
||||
return "", {"warnings": warnings + list(ctx.warnings), "file_type": ext}
|
||||
|
||||
|
||||
def guess_source_type(filename: str) -> str:
|
||||
ext = str(Path(filename or "").suffix or "").lower().lstrip(".")
|
||||
if ext in {"pdf"}:
|
||||
return "pdf"
|
||||
if ext in {"eml"}:
|
||||
return "email"
|
||||
return "manual"
|
||||
|
||||
|
||||
def max_notice_chars() -> int:
|
||||
raw = str(current_app.config.get("SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS") or "").strip()
|
||||
try:
|
||||
value = int(raw) if raw else 0
|
||||
except Exception:
|
||||
value = 0
|
||||
return value if value > 0 else 200000
|
||||
@@ -0,0 +1,220 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.constants import MAP_JSON
|
||||
|
||||
|
||||
def _str_prop(description: str, *, enum: list[str] | None = None) -> dict[str, Any]:
|
||||
prop: dict[str, Any] = {"type": "string", "description": description}
|
||||
if enum:
|
||||
prop["enum"] = enum
|
||||
return prop
|
||||
|
||||
|
||||
def _int_prop(description: str) -> dict[str, Any]:
|
||||
return {"type": "integer", "description": description}
|
||||
|
||||
|
||||
def _post_op(
|
||||
operation_id: str,
|
||||
summary: str,
|
||||
properties: dict[str, Any],
|
||||
*,
|
||||
required: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
schema: dict[str, Any] = {"type": "object", "properties": properties}
|
||||
if required:
|
||||
schema["required"] = required
|
||||
return {
|
||||
"post": {
|
||||
"operationId": operation_id,
|
||||
"summary": summary,
|
||||
"description": summary,
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": True,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": schema,
|
||||
}
|
||||
},
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": (
|
||||
"Tool response (status: ok|running|needs_human|failed). "
|
||||
"May include checkpoint, human_options, action_buttons."
|
||||
),
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {"type": "object"},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"""Build OpenAPI 3.0 spec for Dify Chatflow custom tools (agent-facing only)."""
|
||||
server = str(base_url or "").strip().rstrip("/")
|
||||
if not server.endswith("/api/shipping-notice"):
|
||||
server = f"{server}/api/shipping-notice" if server else "/api/shipping-notice"
|
||||
|
||||
task_id = _str_prop("发货任务编号(task id),如 SN-20260529-ABCD1234")
|
||||
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
"title": "Hxops Shipping Notice Tools",
|
||||
"version": "1.0.0",
|
||||
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。",
|
||||
},
|
||||
"servers": [{"url": server}],
|
||||
"paths": {
|
||||
"/tools/create_task": _post_op(
|
||||
"create_task",
|
||||
"创建发货任务 task",
|
||||
{
|
||||
"task_id": _str_prop("已存在的发货任务编号(可选)。传入时将直接复用该任务,禁止重复创建。"),
|
||||
"user_id": _int_prop("Hxops 用户 ID(可选)"),
|
||||
"conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"),
|
||||
"source_type": _str_prop("来源:manual|email|wecom|pdf", enum=["manual", "email", "wecom", "pdf"]),
|
||||
"raw_content": _str_prop("原始发货通知文本(可选,后续 parse 也可传入)"),
|
||||
},
|
||||
),
|
||||
"/tools/parse_notice": _post_op(
|
||||
"parse_notice",
|
||||
"解析发货通知文本",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"raw_text": _str_prop("待解析的发货通知全文"),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/parse_inventory": _post_op(
|
||||
"parse_inventory",
|
||||
"解析库存。大 Excel 禁止 raw_inventory_text(会超 LLM token);"
|
||||
"先 POST /tools/upload_inventory_file 上传,再 get_inventory_schema_preview → "
|
||||
"apply_inventory_mapping;或 use_uploaded_file=true(规则映射兜底)。小表可粘贴文本。"
|
||||
"成功后 stop_agent_turn,等 confirm_inventory_mapping 后再 match。",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"use_uploaded_file": _str_prop(
|
||||
"true=解析该任务已上传的 Excel(服务端直传,不经过 LLM)",
|
||||
enum=["true", "false"],
|
||||
),
|
||||
MAP_JSON: _str_prop(
|
||||
'可选,列映射 JSON 字符串,如 {"sku":"AWS Sku","available_qty":"Qty Available"}'
|
||||
),
|
||||
"raw_inventory_text": _str_prop(
|
||||
"仅小表(约 <8 万字符)。大 Excel 勿传此字段,改用 upload_inventory_file"
|
||||
),
|
||||
"inventory_lines_json": _str_prop(
|
||||
'可选,已整理好的 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
|
||||
),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/get_inventory_schema_preview": _post_op(
|
||||
"get_inventory_schema_preview",
|
||||
"读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
|
||||
{"task_id": task_id},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/apply_inventory_mapping": _post_op(
|
||||
"apply_inventory_mapping",
|
||||
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
|
||||
{
|
||||
"task_id": task_id,
|
||||
MAP_JSON: _str_prop(
|
||||
'列映射 JSON,含 sku/reservation_id/available_qty;可选 match_rule(LLM 自然语言匹配说明,缺省则后端动态兜底)'
|
||||
),
|
||||
},
|
||||
required=["task_id", MAP_JSON],
|
||||
),
|
||||
"/tools/ensure_inventory": _post_op(
|
||||
"ensure_inventory",
|
||||
"确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"mode": _str_prop("auto=自动/RPA;retry_rpa=重试 RPA", enum=["auto", "retry_rpa"]),
|
||||
"inventory_lines_json": _str_prop(
|
||||
'手工库存 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
|
||||
),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/auto_progress": _post_op(
|
||||
"auto_progress",
|
||||
"按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID(可选,用于仅知道会话时定位任务)"),
|
||||
},
|
||||
),
|
||||
"/tools/match_inventory": _post_op(
|
||||
"match_inventory",
|
||||
"匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;"
|
||||
"未确认时调用会被拒绝并返回 forbidden_next_tools",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"inventory_lines_json": _str_prop("可选,覆盖库存 JSON 数组后再匹配"),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/submit_decision": _post_op(
|
||||
"submit_decision",
|
||||
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
|
||||
"decision": _str_prop(
|
||||
"confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;"
|
||||
"confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
|
||||
enum=[
|
||||
"confirm",
|
||||
"confirm_parse",
|
||||
"reject",
|
||||
"rematch",
|
||||
"reparse",
|
||||
"confirm_inventory_mapping",
|
||||
"correct_inventory_mapping",
|
||||
"reparse_inventory",
|
||||
],
|
||||
),
|
||||
"comment": _str_prop("备注(可选)"),
|
||||
},
|
||||
required=["decision"],
|
||||
),
|
||||
"/tools/generate_shipment_excel": _post_op(
|
||||
"generate_shipment_excel",
|
||||
"生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
|
||||
{"task_id": task_id},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/upload_to_freight": _post_op(
|
||||
"upload_to_freight",
|
||||
"上传 Excel 到货代系统(RPA 或手工确认)",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"mode": _str_prop(
|
||||
"auto=触发 RPA;retry_upload=重试;manual_confirm=手工上传完成",
|
||||
enum=["auto", "retry_upload", "manual_confirm"],
|
||||
),
|
||||
"freight_ref_no": _str_prop("货代系统单号(可选;manual_confirm 通常无需填写)"),
|
||||
},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/get_task_status": _post_op(
|
||||
"get_task_status",
|
||||
"查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID"),
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
|
||||
|
||||
def _cell(value: Any) -> str:
|
||||
text = str(value or "").strip()
|
||||
return text if text else "-"
|
||||
|
||||
|
||||
def _fmt_qty(qty: Any, uom: Any = None) -> str:
|
||||
if qty is None or qty == "":
|
||||
return "-"
|
||||
try:
|
||||
num = float(qty)
|
||||
except (TypeError, ValueError):
|
||||
return _cell(qty)
|
||||
qty_text = str(int(num)) if num == int(num) else f"{num:g}"
|
||||
unit = str(uom or "").strip() or "PCS"
|
||||
return f"{qty_text} {unit}"
|
||||
|
||||
|
||||
def _fmt_money(value: Any, currency: Any = None) -> str:
|
||||
if value is None or value == "":
|
||||
return "-"
|
||||
try:
|
||||
num = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return _cell(value)
|
||||
curr = str(currency or "").strip().upper()
|
||||
formatted = f"{num:,.2f}"
|
||||
if curr == "USD":
|
||||
return f"${formatted}"
|
||||
if curr == "CNY" or curr == "RMB":
|
||||
return f"¥{formatted}"
|
||||
if curr:
|
||||
return f"{formatted} {curr}"
|
||||
return formatted
|
||||
|
||||
|
||||
def _append_table_row(rows: list[str], label: str, value: Any) -> None:
|
||||
rows.append(f"| {label} | {_cell(value)} |")
|
||||
|
||||
|
||||
def _format_line_block(
|
||||
line: dict[str, Any],
|
||||
*,
|
||||
doc_required_date: str = "",
|
||||
lang: str,
|
||||
) -> list[str]:
|
||||
currency = line.get("currency")
|
||||
required_date = str(line.get("required_date") or doc_required_date or "").strip()
|
||||
rows: list[str] = [
|
||||
f"| {t('table.field', lang=lang)} | {t('table.value', lang=lang)} |",
|
||||
"|------|-----|",
|
||||
]
|
||||
_append_table_row(rows, t("field.reservation_id", lang=lang), line.get("reservation_id"))
|
||||
_append_table_row(rows, t("field.sku", lang=lang), line.get("sku"))
|
||||
_append_table_row(rows, t("field.qty", lang=lang), _fmt_qty(line.get("qty"), line.get("uom")))
|
||||
_append_table_row(rows, t("field.unit_price", lang=lang), _fmt_money(line.get("unit_price"), currency))
|
||||
_append_table_row(rows, t("field.amount", lang=lang), _fmt_money(line.get("amount"), currency))
|
||||
_append_table_row(rows, t("field.required_date", lang=lang), required_date)
|
||||
vendor_pn = str(line.get("vendor_part_number") or "").strip()
|
||||
if vendor_pn:
|
||||
_append_table_row(rows, t("field.vendor_part_number", lang=lang), vendor_pn)
|
||||
line_no = str(line.get("line_no") or "").strip()
|
||||
if line_no:
|
||||
_append_table_row(rows, t("field.line_no", lang=lang), line_no)
|
||||
return rows
|
||||
|
||||
|
||||
def format_parse_summary(
|
||||
*,
|
||||
task_no: str,
|
||||
po_number: str | None = None,
|
||||
ship_to: str | None = None,
|
||||
customer_name: str | None = None,
|
||||
required_date: str | None = None,
|
||||
lines: list[dict[str, Any]] | None = None,
|
||||
warnings: list[Any] | None = None,
|
||||
low_confidence: bool = False,
|
||||
lang: str | None = None,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
"""Fixed Markdown summary for parse_notice / Agent display."""
|
||||
resolved = resolve_lang(payload) if payload is not None else resolve_lang({"lang": lang} if lang else None)
|
||||
order_lines = [line for line in (lines or []) if isinstance(line, dict)]
|
||||
doc_date = str(required_date or "").strip()
|
||||
parts = [t("parse.title", lang=resolved).format(task_no=task_no), ""]
|
||||
|
||||
if not order_lines:
|
||||
parts.extend([f"| {t('table.field', lang=resolved)} | {t('table.value', lang=resolved)} |", "|------|-----|"])
|
||||
_append_table_row(parts, t("field.po", lang=resolved), po_number)
|
||||
_append_table_row(parts, t("field.ship_to", lang=resolved), ship_to or customer_name)
|
||||
_append_table_row(parts, t("field.required_date", lang=resolved), doc_date)
|
||||
parts.append("")
|
||||
parts.append(t("parse.no_lines", lang=resolved))
|
||||
elif len(order_lines) == 1:
|
||||
line = order_lines[0]
|
||||
parts.extend([f"| {t('table.field', lang=resolved)} | {t('table.value', lang=resolved)} |", "|------|-----|"])
|
||||
_append_table_row(parts, t("field.po", lang=resolved), po_number)
|
||||
_append_table_row(parts, t("field.reservation_id", lang=resolved), line.get("reservation_id"))
|
||||
_append_table_row(parts, t("field.sku", lang=resolved), line.get("sku"))
|
||||
_append_table_row(parts, t("field.qty", lang=resolved), _fmt_qty(line.get("qty"), line.get("uom")))
|
||||
_append_table_row(parts, t("field.unit_price", lang=resolved), _fmt_money(line.get("unit_price"), line.get("currency")))
|
||||
_append_table_row(parts, t("field.amount", lang=resolved), _fmt_money(line.get("amount"), line.get("currency")))
|
||||
line_date = str(line.get("required_date") or doc_date or "").strip()
|
||||
_append_table_row(parts, t("field.required_date", lang=resolved), line_date)
|
||||
recipient = str(ship_to or customer_name or "").strip()
|
||||
_append_table_row(parts, t("field.ship_to", lang=resolved), recipient)
|
||||
vendor_pn = str(line.get("vendor_part_number") or "").strip()
|
||||
if vendor_pn:
|
||||
_append_table_row(parts, t("field.vendor_part_number", lang=resolved), vendor_pn)
|
||||
else:
|
||||
if po_number:
|
||||
parts.append(f"{t('field.po', lang=resolved)}:{_cell(po_number)}")
|
||||
recipient = str(ship_to or customer_name or "").strip()
|
||||
if recipient:
|
||||
parts.append(f"{t('field.ship_to', lang=resolved)}:{recipient}")
|
||||
if doc_date:
|
||||
parts.append(f"{t('field.required_date', lang=resolved)}:{doc_date}")
|
||||
parts.append("")
|
||||
for index, line in enumerate(order_lines, 1):
|
||||
line_no = str(line.get("line_no") or index).strip()
|
||||
if resolved == "en":
|
||||
parts.append(f"[Line {index}] {t('field.line_no', lang=resolved)} {line_no}")
|
||||
else:
|
||||
parts.append(f"【明细 {index}】{t('field.line_no', lang=resolved)} {line_no}")
|
||||
parts.extend(_format_line_block(line, doc_required_date=doc_date, lang=resolved))
|
||||
parts.append("")
|
||||
|
||||
warn_items = [str(w).strip() for w in (warnings or []) if str(w).strip()]
|
||||
if warn_items:
|
||||
parts.append("")
|
||||
parts.append(t("common.tips", lang=resolved))
|
||||
for warning in warn_items[:8]:
|
||||
parts.append(f"- {warning}")
|
||||
|
||||
parts.append("")
|
||||
if low_confidence:
|
||||
parts.append(t("parse.low_conf", lang=resolved))
|
||||
parts.append(t("parse.confirm", lang=resolved))
|
||||
parts.append(t("parse.hint", lang=resolved))
|
||||
hint_btn = t("parse.hint_btn", lang=resolved).strip()
|
||||
if hint_btn:
|
||||
parts.append(hint_btn)
|
||||
|
||||
return "\n".join(parts).strip()
|
||||
@@ -0,0 +1,41 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
_PO_NUMBER_PATTERNS = (
|
||||
r"(?i)(?:PO|P\.O\.)\s*(?:Number|No\.?|#)?\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
|
||||
r"(?i)Purchase\s+Order\s*(?:Number|No\.?|#)?\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
|
||||
r"(?:采购订单号|采购单号|订单号|PO号)\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
|
||||
)
|
||||
|
||||
|
||||
def normalize_po_number(value: Any) -> str:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
if text.lower() in {"number", "no", "n/a", "na", "none"}:
|
||||
return ""
|
||||
return text
|
||||
|
||||
|
||||
def find_po_number_in_document(text: str) -> str:
|
||||
raw = str(text or "")
|
||||
if not raw.strip():
|
||||
return ""
|
||||
for pattern in _PO_NUMBER_PATTERNS:
|
||||
match = re.search(pattern, raw)
|
||||
if match:
|
||||
return normalize_po_number(match.group(1))
|
||||
return ""
|
||||
|
||||
|
||||
def enrich_notice_with_po_number(parsed: dict[str, Any], *, raw_text: str = "") -> dict[str, Any]:
|
||||
po_number = normalize_po_number(
|
||||
parsed.get("po_number") or parsed.get("PO Number") or parsed.get("purchase_order_number")
|
||||
)
|
||||
if not po_number:
|
||||
po_number = find_po_number_in_document(raw_text)
|
||||
if po_number:
|
||||
parsed["po_number"] = po_number
|
||||
return parsed
|
||||
@@ -0,0 +1,73 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import desc
|
||||
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
|
||||
|
||||
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
|
||||
return {
|
||||
"id": task.id,
|
||||
"task_no": task.task_no,
|
||||
"source_type": task.source_type,
|
||||
"customer_name": task.customer_name,
|
||||
"process_status": task.process_status,
|
||||
"review_status": task.review_status,
|
||||
"match_status": task.match_status,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"conversation_id": task.conversation_id,
|
||||
"export_file_name": task.export_file_name,
|
||||
"freight_ref_no": task.freight_ref_no,
|
||||
"created_at": task.created_at.isoformat() if task.created_at else None,
|
||||
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
|
||||
data = serialize_task_summary(task)
|
||||
data.update({
|
||||
"customer_code": task.customer_code,
|
||||
"ship_to": task.ship_to,
|
||||
"po_number": task.po_number,
|
||||
"required_date": task.required_date,
|
||||
"lines": task.lines_json or [],
|
||||
"shortage": task.shortage_json,
|
||||
"line_results": task.line_results_json or [],
|
||||
"parse_confidence": task.parse_confidence,
|
||||
"error_message": task.error_message,
|
||||
"events": [
|
||||
{
|
||||
"event_type": e.event_type,
|
||||
"detail_json": e.detail_json,
|
||||
"created_at": e.created_at.isoformat() if e.created_at else None,
|
||||
}
|
||||
for e in sorted(task.events or [], key=lambda x: x.created_at or "")
|
||||
],
|
||||
})
|
||||
return data
|
||||
|
||||
|
||||
def list_tasks_for_user(
|
||||
user_id: int,
|
||||
*,
|
||||
process_status: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> list[dict[str, Any]]:
|
||||
q = ShippingTask.query.filter(
|
||||
(ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None))
|
||||
)
|
||||
if process_status:
|
||||
q = q.filter(ShippingTask.process_status == process_status)
|
||||
rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all()
|
||||
return [serialize_task_summary(c) for c in rows]
|
||||
|
||||
|
||||
def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None:
|
||||
task = ShippingTask.query.filter_by(task_no=task_no).first()
|
||||
if not task:
|
||||
return None
|
||||
if task.user_id is not None and task.user_id != user_id:
|
||||
return None
|
||||
return task
|
||||
@@ -0,0 +1,89 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
# 常见 Reservation ID:纯数字,如 1000140351(通常 8~12 位)
|
||||
RESERVATION_ID_NUMERIC_RE = re.compile(r"^\d{8,12}$")
|
||||
# Wistron 等 PO:PR Number = ADU_S-ENCWIW260528126265@1000140351
|
||||
RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{8,12})\b")
|
||||
PR_NUMBER_LINE_RE = re.compile(
|
||||
r"PR\s*Number\s*[::]?\s*([^\n\r]+)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def normalize_reservation_id(value: Any) -> str:
|
||||
"""Normalize reservation id; Excel often stores numeric ids as float."""
|
||||
if value is None:
|
||||
return ""
|
||||
|
||||
if isinstance(value, bool):
|
||||
return ""
|
||||
|
||||
if isinstance(value, float):
|
||||
if value != value: # NaN
|
||||
return ""
|
||||
if value.is_integer():
|
||||
return str(int(value))
|
||||
text = str(value).strip()
|
||||
elif isinstance(value, int):
|
||||
text = str(value)
|
||||
else:
|
||||
text = str(value).strip()
|
||||
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
text = text.replace(",", "").replace(",", "").strip()
|
||||
if re.fullmatch(r"\d+\.0+", text):
|
||||
text = text.split(".", 1)[0]
|
||||
|
||||
return text
|
||||
|
||||
|
||||
def extract_reservation_id(value: Any) -> str:
|
||||
"""Extract reservation id from plain numeric, Excel float, or PR Number (xxx@1000140351)."""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
|
||||
direct = normalize_reservation_id(text)
|
||||
if looks_like_reservation_id(direct):
|
||||
return direct
|
||||
|
||||
match = RESERVATION_AT_SUFFIX_RE.search(text)
|
||||
if match:
|
||||
return match.group(1)
|
||||
|
||||
if "@" in text:
|
||||
tail = normalize_reservation_id(text.rsplit("@", 1)[-1])
|
||||
if looks_like_reservation_id(tail):
|
||||
return tail
|
||||
|
||||
return direct
|
||||
|
||||
|
||||
def find_reservation_id_in_document(text: str) -> str:
|
||||
"""Scan document text for PR Number @ reservation id or standalone @1000140351."""
|
||||
body = str(text or "")
|
||||
if not body.strip():
|
||||
return ""
|
||||
|
||||
pr_match = PR_NUMBER_LINE_RE.search(body)
|
||||
if pr_match:
|
||||
extracted = extract_reservation_id(pr_match.group(1))
|
||||
if extracted and looks_like_reservation_id(extracted):
|
||||
return extracted
|
||||
|
||||
for match in RESERVATION_AT_SUFFIX_RE.finditer(body):
|
||||
candidate = match.group(1)
|
||||
if looks_like_reservation_id(candidate):
|
||||
return candidate
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def looks_like_reservation_id(value: Any) -> bool:
|
||||
text = normalize_reservation_id(value)
|
||||
return bool(text and RESERVATION_ID_NUMERIC_RE.fullmatch(text))
|
||||
@@ -0,0 +1,94 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
|
||||
def _path(key: str) -> Path | None:
|
||||
value = str(current_app.config.get(key) or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
return Path(value)
|
||||
|
||||
|
||||
def inventory_drop_dir() -> Path | None:
|
||||
return _path("FREIGHT_INVENTORY_DROP_DIR")
|
||||
|
||||
|
||||
def inventory_processed_dir() -> Path | None:
|
||||
base = inventory_drop_dir()
|
||||
if not base:
|
||||
return None
|
||||
return base / "processed"
|
||||
|
||||
|
||||
def inventory_trigger_dir() -> Path | None:
|
||||
return _path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
|
||||
|
||||
|
||||
def upload_queue_dir() -> Path | None:
|
||||
return _path("FREIGHT_UPLOAD_QUEUE_DIR")
|
||||
|
||||
|
||||
def upload_trigger_dir() -> Path | None:
|
||||
return _path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
|
||||
|
||||
|
||||
def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
|
||||
trigger_dir = inventory_trigger_dir()
|
||||
if not trigger_dir:
|
||||
return None
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
body = {
|
||||
"action": "inventory_export",
|
||||
"task_no": task_no,
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
path = trigger_dir / f"inventory_export_{task_no}.json"
|
||||
path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return str(path)
|
||||
|
||||
|
||||
def write_upload_trigger(task_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]:
|
||||
queue = upload_queue_dir()
|
||||
trigger_dir = upload_trigger_dir()
|
||||
if not queue or not trigger_dir:
|
||||
return None, None
|
||||
queue.mkdir(parents=True, exist_ok=True)
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
src = Path(export_file_path)
|
||||
if not src.is_file():
|
||||
return None, None
|
||||
dest = queue / f"{task_no}_{src.name}"
|
||||
shutil.copy2(src, dest)
|
||||
|
||||
body = {
|
||||
"action": "shipment_upload",
|
||||
"task_no": task_no,
|
||||
"file_path": str(dest),
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
trigger_path = trigger_dir / f"upload_{task_no}.json"
|
||||
trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return str(dest), str(trigger_path)
|
||||
|
||||
|
||||
def find_latest_inventory_file() -> Path | None:
|
||||
drop = inventory_drop_dir()
|
||||
if not drop or not drop.is_dir():
|
||||
return None
|
||||
candidates = [
|
||||
p for p in drop.iterdir()
|
||||
if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"}
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
return max(candidates, key=lambda p: p.stat().st_mtime)
|
||||
@@ -0,0 +1,94 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
|
||||
DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS = 3
|
||||
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
|
||||
|
||||
_INVENTORY_SUCCESS_EVENTS = {
|
||||
"inventory_uploaded",
|
||||
"inventory_parsed",
|
||||
"inventory_rpa_drop_ingested",
|
||||
"inventory_rpa_ready",
|
||||
"inventory_template_mapping_used",
|
||||
}
|
||||
|
||||
_UPLOAD_SUCCESS_EVENTS = {
|
||||
"upload_rpa_success",
|
||||
"upload_manual_confirmed",
|
||||
}
|
||||
|
||||
|
||||
def inventory_rpa_attempts(task: ShippingTask | None) -> int:
|
||||
if not task or task.id is None:
|
||||
return 0
|
||||
|
||||
last_success = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||||
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_SUCCESS_EVENTS))
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
since: datetime | None = last_success.created_at if last_success else None
|
||||
|
||||
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
|
||||
)
|
||||
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||
ShippingTaskEvent.event_type == "inventory_rpa_failed"
|
||||
)
|
||||
if since:
|
||||
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
|
||||
failed = failed.filter(ShippingTaskEvent.created_at >= since)
|
||||
|
||||
return max(triggered.count(), failed.count())
|
||||
|
||||
|
||||
def upload_rpa_attempts(task: ShippingTask | None) -> int:
|
||||
if not task or task.id is None:
|
||||
return 0
|
||||
|
||||
last_success = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||||
.filter(ShippingTaskEvent.event_type.in_(_UPLOAD_SUCCESS_EVENTS))
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
since: datetime | None = last_success.created_at if last_success else None
|
||||
|
||||
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||
ShippingTaskEvent.event_type == "upload_rpa_triggered"
|
||||
)
|
||||
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
|
||||
ShippingTaskEvent.event_type == "upload_rpa_failed"
|
||||
)
|
||||
if since:
|
||||
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
|
||||
failed = failed.filter(ShippingTaskEvent.created_at >= since)
|
||||
|
||||
return max(triggered.count(), failed.count())
|
||||
|
||||
|
||||
def max_rpa_inventory_attempts() -> int:
|
||||
value = os.getenv("SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS")
|
||||
if value is None or not str(value).strip():
|
||||
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
|
||||
return max(parsed, 1)
|
||||
|
||||
|
||||
def max_rpa_upload_attempts() -> int:
|
||||
value = os.getenv("SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS")
|
||||
if value is None or not str(value).strip():
|
||||
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
|
||||
return max(parsed, 1)
|
||||
@@ -0,0 +1,552 @@
|
||||
"""
|
||||
Canonical registry for shipping-notice human nodes.
|
||||
|
||||
Single source of truth for:
|
||||
- checkpoint ids (API `checkpoint`, Dify `flow_ckpt`)
|
||||
- action button specs (`action_buttons`, HXOPS_SHIPPING_ACTIONS)
|
||||
- task DB fields → checkpoint + human_options (chat-actions API)
|
||||
- task DB field writes (`TaskTransition` / `apply_task_transition` — tools.py must use these)
|
||||
|
||||
When adding a human node, update ONLY this module (+ tests), then:
|
||||
- tools.py sets task fields via `apply_task_transition(...)` and calls `tool_response(..., checkpoint=CP_*)`
|
||||
- Dify `组装直接回复` embeds directive only from HTTP `act_json` (approach B); text-only rounds use Hxops `/chat-actions`
|
||||
- `GET /tools/checkpoint-catalog` is for developers/docs/CI — not wired in Dify canvas
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_ALIGN_REVIEW,
|
||||
CP_EXPORT_READY,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_INVENTORY_PENDING,
|
||||
CP_MAP_INFER,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_READY_EXPORT,
|
||||
CP_READY_MATCH,
|
||||
CP_REJECTED,
|
||||
CP_RSV_REQ,
|
||||
CP_UPLOADED,
|
||||
CP_COMPLETED,
|
||||
CP_UPLOAD_FAILED,
|
||||
CP_UPLOAD_REQ,
|
||||
CP_WAITING_UPLOAD,
|
||||
PH_ALIGN_REVIEW,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_LOW_CONF,
|
||||
PH_MAP_INFER,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
PH_RSV_REQ,
|
||||
PH_SHORTAGE,
|
||||
PH_UPLOAD_RPA_FAILED,
|
||||
PH_UPLOAD_RPA_PENDING,
|
||||
RS_ALIGN_REVIEW,
|
||||
RS_CONFIRMED,
|
||||
RS_PARSE_REVIEW,
|
||||
RS_REJECTED,
|
||||
RS_RSV_REQ,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
max_rpa_inventory_attempts,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action buttons (id → label / message / variant)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
"confirm": {"label": "确认", "message": "确认", "variant": "primary"},
|
||||
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
|
||||
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
|
||||
"confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"},
|
||||
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
|
||||
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
|
||||
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
|
||||
"retry_rpa": {"label": "重试 RPA", "message": "重试 RPA 导出库存", "variant": "secondary"},
|
||||
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
|
||||
"upload_inventory_file": {
|
||||
"label": "选择库存文件",
|
||||
"message": "我要上传库存 Excel",
|
||||
"variant": "secondary",
|
||||
},
|
||||
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
|
||||
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
|
||||
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
|
||||
"mark_manual_uploaded": {
|
||||
"label": "已手工上传",
|
||||
"message": "已在货代系统手工上传完成",
|
||||
"variant": "primary",
|
||||
},
|
||||
"paste_inventory_json": {
|
||||
"label": "粘贴库存",
|
||||
"message": "我粘贴库存小表",
|
||||
"variant": "secondary",
|
||||
},
|
||||
"edit_inventory_mapping": {
|
||||
"label": "修改映射",
|
||||
"message": "修改库存列映射",
|
||||
"variant": "primary",
|
||||
},
|
||||
"match_inventory": {
|
||||
"label": "匹配库存",
|
||||
"message": "匹配库存",
|
||||
"variant": "primary",
|
||||
},
|
||||
}
|
||||
|
||||
# checkpoint id → default human option ids (HTTP / Dify before task reload)
|
||||
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
|
||||
CP_ALIGN_REVIEW: (
|
||||
"confirm_inventory_mapping",
|
||||
"correct_inventory_mapping",
|
||||
"reparse_inventory",
|
||||
"reject",
|
||||
),
|
||||
CP_MAP_INFER: (
|
||||
"edit_inventory_mapping",
|
||||
"upload_inventory_file",
|
||||
"paste_inventory_json",
|
||||
"retry_rpa",
|
||||
),
|
||||
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
|
||||
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
|
||||
CP_RSV_REQ: ("reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"),
|
||||
RS_SHORTAGE_REVIEW: ("confirm", "reject", "rematch"),
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("reparse", "reject"),
|
||||
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
|
||||
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
|
||||
CP_READY_MATCH: ("match_inventory",),
|
||||
CP_READY_EXPORT: ("generate_excel",),
|
||||
CP_EXPORT_READY: ("download_excel", "mark_manual_uploaded"),
|
||||
CP_EXPORT_GENERATED: ("download_excel", "mark_manual_uploaded"),
|
||||
CP_REJECTED: (),
|
||||
CP_UPLOADED: (),
|
||||
CP_COMPLETED: (),
|
||||
}
|
||||
|
||||
ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_REGISTRY.keys())
|
||||
ALL_ACTION_IDS: frozenset[str] = frozenset(ACTION_SPECS.keys())
|
||||
|
||||
# Dynamic subsets of upload_req (RPA attempts); default full set is CHECKPOINT_REGISTRY[CP_UPLOAD_REQ]
|
||||
OPTIONS_UPLOAD_FILE_ONLY: tuple[str, ...] = ("upload_inventory_file",)
|
||||
OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("retry_rpa", "upload_inventory_file")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TaskUiState:
|
||||
checkpoint: str | None
|
||||
human_options: list[str] | None
|
||||
|
||||
@property
|
||||
def action_buttons(self) -> list[dict[str, str]]:
|
||||
return build_action_buttons(self.human_options)
|
||||
|
||||
|
||||
def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
|
||||
if not option_ids:
|
||||
return []
|
||||
buttons: list[dict[str, str]] = []
|
||||
for option_id in option_ids:
|
||||
spec = ACTION_SPECS.get(option_id)
|
||||
if not spec:
|
||||
continue
|
||||
buttons.append({"id": option_id, **spec})
|
||||
return buttons
|
||||
|
||||
|
||||
def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
|
||||
if not checkpoint:
|
||||
return None
|
||||
key = str(checkpoint).strip()
|
||||
options = CHECKPOINT_REGISTRY.get(key)
|
||||
if options is None:
|
||||
return None
|
||||
return list(options)
|
||||
|
||||
|
||||
def action_buttons_for_checkpoint(checkpoint: str | None) -> list[dict[str, str]]:
|
||||
return build_action_buttons(human_options_for_checkpoint(checkpoint))
|
||||
|
||||
|
||||
def format_actions_directive(option_ids: list[str] | None) -> str:
|
||||
buttons = build_action_buttons(option_ids)
|
||||
if not buttons:
|
||||
return ""
|
||||
body = json.dumps(buttons, ensure_ascii=False)
|
||||
return f"<!-- HXOPS_SHIPPING_ACTIONS: {body} -->"
|
||||
|
||||
|
||||
def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
cp = str(checkpoint).strip() if checkpoint else None
|
||||
if cp and cp not in CHECKPOINT_REGISTRY:
|
||||
cp = None
|
||||
return TaskUiState(checkpoint=cp, human_options=options)
|
||||
|
||||
|
||||
def upload_req_options_for_task(task: ShippingTask) -> list[str]:
|
||||
"""upload_req checkpoint with RPA-attempt-aware button subsets."""
|
||||
if task.pending_human_reason == PH_RPA_EXHAUSTED:
|
||||
return list(OPTIONS_UPLOAD_FILE_ONLY)
|
||||
if inventory_rpa_attempts(task) >= max_rpa_inventory_attempts():
|
||||
return list(OPTIONS_UPLOAD_FILE_ONLY)
|
||||
if task.pending_human_reason in {PH_INV_UNAVAIL, PH_RPA_PENDING}:
|
||||
return list(OPTIONS_RPA_OR_UPLOAD)
|
||||
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
|
||||
|
||||
|
||||
def human_options_for_task_or_checkpoint(
|
||||
*,
|
||||
task: ShippingTask | None = None,
|
||||
checkpoint: str | None = None,
|
||||
) -> list[str] | None:
|
||||
"""Prefer task DB state; fall back to static checkpoint registry (for tool_response)."""
|
||||
if task is not None:
|
||||
opts = resolve_task_ui_state(task).human_options
|
||||
if opts is not None:
|
||||
return opts
|
||||
return human_options_for_checkpoint(checkpoint)
|
||||
|
||||
|
||||
def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
"""Map ShippingTask DB fields → checkpoint + human_options for /chat-actions."""
|
||||
if task.process_status == "uploaded":
|
||||
return TaskUiState(checkpoint=CP_UPLOADED, human_options=[])
|
||||
if task.process_status == "closed":
|
||||
return TaskUiState(checkpoint=CP_COMPLETED, human_options=[])
|
||||
|
||||
if task.process_status == "rejected" or task.review_status == "rejected":
|
||||
return TaskUiState(checkpoint=CP_REJECTED, human_options=[])
|
||||
|
||||
if task.pending_human_reason == PH_RPA_EXHAUSTED:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
|
||||
if (
|
||||
task.process_status == "parsed"
|
||||
and not task.review_status
|
||||
and not task.pending_human_reason
|
||||
and not task.inventory_lines_json
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_INVENTORY_PENDING,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]),
|
||||
)
|
||||
|
||||
if (
|
||||
task.process_status == "inventory_ready"
|
||||
and not task.review_status
|
||||
and not task.pending_human_reason
|
||||
and not task.match_status
|
||||
and isinstance(task.lines_json, list)
|
||||
and len(task.lines_json) > 0
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_READY_MATCH,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]),
|
||||
)
|
||||
|
||||
if task.process_status == "matched":
|
||||
if task.export_file_path:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_EXPORT_READY,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]),
|
||||
)
|
||||
return TaskUiState(
|
||||
checkpoint=CP_READY_EXPORT,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]),
|
||||
)
|
||||
|
||||
reason = task.pending_human_reason
|
||||
if reason == PH_ALIGN_REVIEW or task.review_status == RS_ALIGN_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_ALIGN_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_ALIGN_REVIEW]),
|
||||
)
|
||||
if reason == PH_MAP_INFER:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_MAP_INFER,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_MAP_INFER]),
|
||||
)
|
||||
if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_RSV_REQ,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]),
|
||||
)
|
||||
if reason == PH_INV_UNAVAIL:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
if reason == PH_SHORTAGE or task.review_status == RS_SHORTAGE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=RS_SHORTAGE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]),
|
||||
)
|
||||
if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_PARSE_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]),
|
||||
)
|
||||
if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_FAILED,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]),
|
||||
)
|
||||
if reason == PH_RPA_PENDING or (
|
||||
task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING
|
||||
):
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
human_options=upload_req_options_for_task(task),
|
||||
)
|
||||
if reason == PH_UPLOAD_RPA_PENDING or task.process_status == "waiting_upload":
|
||||
return TaskUiState(
|
||||
checkpoint=CP_WAITING_UPLOAD,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]),
|
||||
)
|
||||
return TaskUiState(checkpoint=None, human_options=None)
|
||||
|
||||
|
||||
def checkpoint_for_task(task: ShippingTask) -> str | None:
|
||||
return resolve_task_ui_state(task).checkpoint
|
||||
|
||||
|
||||
def human_options_for_task(task: ShippingTask) -> list[str] | None:
|
||||
return resolve_task_ui_state(task).human_options
|
||||
|
||||
|
||||
def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
|
||||
ui = resolve_task_ui_state(task)
|
||||
return {
|
||||
"task_no": task.task_no,
|
||||
"checkpoint": ui.checkpoint,
|
||||
"process_status": task.process_status,
|
||||
"review_status": task.review_status,
|
||||
"pending_human_reason": task.pending_human_reason,
|
||||
"action_buttons": ui.action_buttons,
|
||||
}
|
||||
|
||||
|
||||
def build_checkpoint_catalog() -> dict[str, Any]:
|
||||
"""Export for docs, CI, and developer reference — not embedded in Dify (approach B)."""
|
||||
checkpoints = []
|
||||
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
|
||||
buttons = build_action_buttons(list(option_ids))
|
||||
checkpoints.append(
|
||||
{
|
||||
"id": checkpoint_id,
|
||||
"human_options": list(option_ids),
|
||||
"action_buttons": buttons,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"checkpoints": checkpoints,
|
||||
"action_specs": ACTION_SPECS,
|
||||
"dify_fallback": {
|
||||
cp: build_action_buttons(list(opts)) for cp, opts in CHECKPOINT_REGISTRY.items()
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def validate_registry() -> list[str]:
|
||||
"""Return list of validation errors (empty if ok). Used in tests."""
|
||||
errors: list[str] = []
|
||||
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
|
||||
for option_id in option_ids:
|
||||
if option_id not in ACTION_SPECS:
|
||||
errors.append(f"checkpoint {checkpoint_id}: unknown action id {option_id!r}")
|
||||
return errors
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task DB field transitions (tools.py writes via apply_task_transition only)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_UNSET = object()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _TransitionSpec:
|
||||
process_status: Any = _UNSET
|
||||
review_status: Any = _UNSET
|
||||
pending_human_reason: Any = _UNSET
|
||||
clear_error_message: bool = False
|
||||
|
||||
|
||||
class TaskTransition(StrEnum):
|
||||
"""Named DB state writes used by shipping notice tools."""
|
||||
|
||||
PARSED = "parsed"
|
||||
PARSE_NEEDS_REVIEW = "parse_needs_review"
|
||||
INVENTORY_READY = "inventory_ready"
|
||||
INVENTORY_ALIGN_REVIEW = "inventory_align_review"
|
||||
MAP_INFER = "map_infer"
|
||||
RPA_EXHAUSTED = "rpa_exhausted"
|
||||
RPA_PENDING = "rpa_pending"
|
||||
INV_UNAVAIL = "inv_unavail"
|
||||
RSV_REQUIRED = "rsv_required"
|
||||
MATCHED_FULFILLABLE = "matched_fulfillable"
|
||||
MATCH_SHORTAGE = "match_shortage"
|
||||
REJECTED = "rejected"
|
||||
CLOSED = "closed"
|
||||
CONFIRM_SHORTAGE = "confirm_shortage"
|
||||
CONFIRM_PARSE = "confirm_parse"
|
||||
CONFIRM_MATCHED = "confirm_matched"
|
||||
ALIGN_REVIEW_HOLD = "align_review_hold"
|
||||
MAPPING_CONFIRMED = "mapping_confirmed"
|
||||
CORRECT_MAPPING = "correct_mapping"
|
||||
REPARSE_INVENTORY = "reparse_inventory"
|
||||
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
|
||||
WAITING_UPLOAD = "waiting_upload"
|
||||
UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
||||
UPLOAD_FAILED = "upload_failed"
|
||||
UPLOADED = "uploaded"
|
||||
|
||||
|
||||
TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
TaskTransition.PARSED: _TransitionSpec(
|
||||
process_status="parsed",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.PARSE_NEEDS_REVIEW: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=RS_PARSE_REVIEW,
|
||||
pending_human_reason=PH_LOW_CONF,
|
||||
),
|
||||
TaskTransition.INVENTORY_READY: _TransitionSpec(
|
||||
process_status="inventory_ready",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.INVENTORY_ALIGN_REVIEW: _TransitionSpec(
|
||||
process_status="inventory_ready",
|
||||
review_status=RS_ALIGN_REVIEW,
|
||||
pending_human_reason=PH_ALIGN_REVIEW,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.MAP_INFER: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_MAP_INFER,
|
||||
),
|
||||
TaskTransition.RPA_EXHAUSTED: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_RPA_EXHAUSTED,
|
||||
),
|
||||
TaskTransition.RPA_PENDING: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_RPA_PENDING,
|
||||
),
|
||||
TaskTransition.INV_UNAVAIL: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_INV_UNAVAIL,
|
||||
),
|
||||
TaskTransition.RSV_REQUIRED: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=RS_RSV_REQ,
|
||||
pending_human_reason=PH_RSV_REQ,
|
||||
),
|
||||
TaskTransition.MATCHED_FULFILLABLE: _TransitionSpec(
|
||||
process_status="matched",
|
||||
review_status=RS_CONFIRMED,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.MATCH_SHORTAGE: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=RS_SHORTAGE_REVIEW,
|
||||
pending_human_reason=PH_SHORTAGE,
|
||||
),
|
||||
TaskTransition.REJECTED: _TransitionSpec(
|
||||
process_status="rejected",
|
||||
review_status=RS_REJECTED,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.CLOSED: _TransitionSpec(
|
||||
process_status="closed",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.CONFIRM_SHORTAGE: _TransitionSpec(
|
||||
process_status="matched",
|
||||
review_status=RS_CONFIRMED,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.CONFIRM_PARSE: _TransitionSpec(
|
||||
process_status="parsed",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.CONFIRM_MATCHED: _TransitionSpec(
|
||||
review_status=RS_CONFIRMED,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.ALIGN_REVIEW_HOLD: _TransitionSpec(
|
||||
review_status=RS_ALIGN_REVIEW,
|
||||
pending_human_reason=PH_ALIGN_REVIEW,
|
||||
),
|
||||
TaskTransition.MAPPING_CONFIRMED: _TransitionSpec(
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.CORRECT_MAPPING: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_MAP_INFER,
|
||||
),
|
||||
TaskTransition.REPARSE_INVENTORY: _TransitionSpec(
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.REPARSE_INVENTORY_DEMOTE: _TransitionSpec(
|
||||
process_status="parsed",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.WAITING_UPLOAD: _TransitionSpec(process_status="waiting_upload"),
|
||||
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
|
||||
process_status="waiting_upload",
|
||||
pending_human_reason=PH_UPLOAD_RPA_PENDING,
|
||||
),
|
||||
TaskTransition.UPLOAD_FAILED: _TransitionSpec(
|
||||
process_status="upload_failed",
|
||||
pending_human_reason=PH_UPLOAD_RPA_FAILED,
|
||||
),
|
||||
TaskTransition.UPLOADED: _TransitionSpec(
|
||||
process_status="uploaded",
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def apply_task_transition(task: ShippingTask, transition: TaskTransition) -> None:
|
||||
"""Apply a named transition to task process/review/pending_human_reason fields."""
|
||||
spec = TASK_TRANSITIONS[transition]
|
||||
if spec.process_status is not _UNSET:
|
||||
task.process_status = spec.process_status
|
||||
if spec.review_status is not _UNSET:
|
||||
task.review_status = spec.review_status
|
||||
if spec.pending_human_reason is not _UNSET:
|
||||
task.pending_human_reason = spec.pending_human_reason
|
||||
if spec.clear_error_message:
|
||||
task.error_message = None
|
||||
@@ -0,0 +1,24 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, has_request_context, request
|
||||
|
||||
|
||||
def resolve_tool_api_base_url(*, config: dict | None = None, request_host: str | None = None) -> str:
|
||||
"""Resolve hxops Tool API base URL (…/api/shipping-notice, no trailing slash)."""
|
||||
cfg = config
|
||||
if cfg is None and current_app:
|
||||
cfg = current_app.config
|
||||
cfg = cfg or {}
|
||||
|
||||
configured = str(cfg.get("SHIPPING_NOTICE_TOOL_API_BASE") or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
configured = str(cfg.get("PUBLIC_BASE_URL") or "").strip().rstrip("/")
|
||||
if configured:
|
||||
return configured
|
||||
|
||||
host = request_host
|
||||
if host is None and has_request_context():
|
||||
host = request.host_url.rstrip("/")
|
||||
return host or ""
|
||||
@@ -0,0 +1,75 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models import ShippingTask
|
||||
|
||||
|
||||
def tool_response(
|
||||
*,
|
||||
status: str,
|
||||
task: ShippingTask | None = None,
|
||||
task_id: str | None = None,
|
||||
message: str = "",
|
||||
data: dict[str, Any] | None = None,
|
||||
human_options: list[str] | None = None,
|
||||
action_buttons: list[dict[str, str]] | None = None,
|
||||
checkpoint: str | None = None,
|
||||
next_required_action: str | None = None,
|
||||
forbidden_next_tools: list[str] | None = None,
|
||||
stop_agent_turn: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Build a shipping-notice tool JSON response.
|
||||
|
||||
When ``checkpoint`` is omitted and ``task`` is given, checkpoint / human_options /
|
||||
action_buttons are derived from ``resolve_task_ui_state(task)`` (single read path).
|
||||
Explicit ``checkpoint`` wins (e.g. ``parse_ok``, ``task_exists``).
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
build_action_buttons,
|
||||
resolve_task_ui_state,
|
||||
)
|
||||
|
||||
if task is not None and not task_id:
|
||||
task_id = task.task_no
|
||||
|
||||
resolved_checkpoint = checkpoint
|
||||
resolved_human_options = human_options
|
||||
resolved_action_buttons = action_buttons
|
||||
|
||||
if checkpoint is None and task is not None:
|
||||
ui = resolve_task_ui_state(task)
|
||||
resolved_checkpoint = ui.checkpoint
|
||||
if human_options is None:
|
||||
resolved_human_options = ui.human_options
|
||||
if action_buttons is None and ui.action_buttons:
|
||||
resolved_action_buttons = ui.action_buttons
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"status": status,
|
||||
"message": message,
|
||||
"data": data or {},
|
||||
}
|
||||
if task_id:
|
||||
payload["task_id"] = task_id
|
||||
if resolved_human_options is not None:
|
||||
payload["human_options"] = resolved_human_options
|
||||
if resolved_action_buttons is not None:
|
||||
payload["action_buttons"] = resolved_action_buttons
|
||||
elif resolved_human_options is not None:
|
||||
payload["action_buttons"] = build_action_buttons(resolved_human_options)
|
||||
elif resolved_checkpoint:
|
||||
buttons = action_buttons_for_checkpoint(resolved_checkpoint)
|
||||
if buttons:
|
||||
payload["action_buttons"] = buttons
|
||||
if resolved_checkpoint:
|
||||
payload["checkpoint"] = resolved_checkpoint
|
||||
if next_required_action:
|
||||
payload["next_required_action"] = next_required_action
|
||||
if forbidden_next_tools:
|
||||
payload["forbidden_next_tools"] = forbidden_next_tools
|
||||
if stop_agent_turn:
|
||||
payload["stop_agent_turn"] = True
|
||||
return payload
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,95 @@
|
||||
"""Human-readable task progress — never expose DB / state-machine codes to end users."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_ALIGN_REVIEW,
|
||||
CP_EXPORT_READY,
|
||||
CP_INVENTORY_PENDING,
|
||||
CP_MAP_INFER,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_READY_EXPORT,
|
||||
CP_READY_MATCH,
|
||||
CP_REJECTED,
|
||||
CP_RSV_REQ,
|
||||
CP_UPLOADED,
|
||||
CP_COMPLETED,
|
||||
CP_UPLOAD_FAILED,
|
||||
CP_UPLOAD_REQ,
|
||||
CP_WAITING_UPLOAD,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
PH_SHORTAGE,
|
||||
PH_UPLOAD_RPA_PENDING,
|
||||
RS_PARSE_REVIEW,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
|
||||
# Fields omitted from Dify Tool `data` — Agent must not parrot these to users.
|
||||
TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset(
|
||||
{
|
||||
"process_status",
|
||||
"review_status",
|
||||
"match_status",
|
||||
"pending_human_reason",
|
||||
"error_message",
|
||||
}
|
||||
)
|
||||
|
||||
_CHECKPOINT_LABELS: dict[str, str] = {
|
||||
CP_PARSE_REVIEW: "待确认发货通知解析",
|
||||
CP_ALIGN_REVIEW: "待确认库存字段对齐",
|
||||
CP_MAP_INFER: "待确认库存列映射",
|
||||
CP_UPLOAD_REQ: "待上传或获取库存",
|
||||
CP_INVENTORY_PENDING: "待上传库存",
|
||||
CP_RSV_REQ: "待补充 Reservation ID",
|
||||
CP_READY_MATCH: "待匹配库存",
|
||||
CP_READY_EXPORT: "待生成发货 Excel",
|
||||
CP_EXPORT_READY: "发货 Excel 已生成",
|
||||
CP_WAITING_UPLOAD: "待上传货代系统",
|
||||
CP_UPLOAD_FAILED: "货代上传失败,待处理",
|
||||
CP_REJECTED: "任务已驳回",
|
||||
CP_UPLOADED: "已完成上传",
|
||||
CP_COMPLETED: "任务已完成",
|
||||
}
|
||||
|
||||
_PROCESS_STATUS_LABELS: dict[str, str] = {
|
||||
"created": "任务已创建",
|
||||
"parsed": "发货通知已解析",
|
||||
"pending_review": "待人工确认",
|
||||
"waiting_inventory": "待获取库存",
|
||||
"inventory_ready": "库存已就绪",
|
||||
"matched": "库存已匹配",
|
||||
"waiting_upload": "待上传货代系统",
|
||||
"upload_failed": "货代上传失败",
|
||||
"uploaded": "已完成上传",
|
||||
"rejected": "已驳回",
|
||||
"closed": "已关闭",
|
||||
}
|
||||
|
||||
_PENDING_REASON_LABELS: dict[str, str] = {
|
||||
PH_RPA_PENDING: "RPA 正在导出库存,请稍候",
|
||||
PH_RPA_EXHAUSTED: "RPA 获取库存失败,请手动上传",
|
||||
PH_UPLOAD_RPA_PENDING: "RPA 正在上传货代,请稍候",
|
||||
PH_SHORTAGE: "库存不足,待确认",
|
||||
RS_SHORTAGE_REVIEW: "库存不足,待确认",
|
||||
RS_PARSE_REVIEW: "解析结果待确认",
|
||||
}
|
||||
|
||||
|
||||
def user_facing_task_stage(task: ShippingTask) -> str:
|
||||
"""Short Chinese label for chat / get_task_status — no snake_case codes."""
|
||||
ui = resolve_task_ui_state(task)
|
||||
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
|
||||
return _CHECKPOINT_LABELS[ui.checkpoint]
|
||||
reason = str(task.pending_human_reason or "").strip()
|
||||
if reason in _PENDING_REASON_LABELS:
|
||||
return _PENDING_REASON_LABELS[reason]
|
||||
process = str(task.process_status or "").strip()
|
||||
return _PROCESS_STATUS_LABELS.get(process, "处理中")
|
||||
|
||||
|
||||
def strip_internal_task_fields(data: dict) -> dict:
|
||||
return {k: v for k, v in data.items() if k not in TOOL_TASK_DATA_OMIT}
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
SiliconFlow ASR service (OpenAI-compatible /v1/audio/transcriptions).
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
from typing import Tuple
|
||||
|
||||
ALLOWED_AUDIO_EXTENSIONS = frozenset({
|
||||
'webm', 'wav', 'mp3', 'm4a', 'mp4', 'mpeg', 'mpga', 'ogg',
|
||||
})
|
||||
MAX_AUDIO_BYTES = int(os.getenv('ASR_MAX_AUDIO_BYTES', str(10 * 1024 * 1024)))
|
||||
|
||||
|
||||
class SpeechAsrService:
|
||||
@classmethod
|
||||
def _get_client(cls):
|
||||
try:
|
||||
from openai import OpenAI
|
||||
except ImportError as exc:
|
||||
raise RuntimeError('OpenAI SDK not installed') from exc
|
||||
|
||||
api_key = (os.getenv('GJL_API_KEY') or '').strip()
|
||||
base_url = (os.getenv('GJL_API_BASE') or 'https://api.siliconflow.cn/v1').strip()
|
||||
|
||||
if not api_key:
|
||||
raise RuntimeError('Missing GJL_API_KEY. Configure it in .env to enable speech recognition')
|
||||
|
||||
return OpenAI(api_key=api_key, base_url=base_url)
|
||||
|
||||
@classmethod
|
||||
def _resolve_model(cls) -> str:
|
||||
return (os.getenv('ASR_MODEL') or 'FunAudioLLM/SenseVoiceSmall').strip()
|
||||
|
||||
@classmethod
|
||||
def _normalize_filename(cls, filename: str, content_type: str) -> str:
|
||||
name = (filename or '').strip() or 'recording.webm'
|
||||
if '.' not in name:
|
||||
if 'wav' in content_type:
|
||||
name = f'{name}.wav'
|
||||
elif 'mp4' in content_type or 'm4a' in content_type:
|
||||
name = f'{name}.m4a'
|
||||
else:
|
||||
name = f'{name}.webm'
|
||||
return name
|
||||
|
||||
@classmethod
|
||||
def validate_upload(cls, filename: str, size: int) -> None:
|
||||
ext = filename.rsplit('.', 1)[-1].lower() if '.' in filename else ''
|
||||
if ext and ext not in ALLOWED_AUDIO_EXTENSIONS:
|
||||
raise ValueError(f'Unsupported audio format: .{ext}')
|
||||
if size <= 0:
|
||||
raise ValueError('Audio file is empty')
|
||||
if size > MAX_AUDIO_BYTES:
|
||||
raise ValueError(f'Audio file exceeds {MAX_AUDIO_BYTES // (1024 * 1024)}MB limit')
|
||||
|
||||
@classmethod
|
||||
def transcribe(cls, audio_bytes: bytes, filename: str, content_type: str = '') -> Tuple[str, str]:
|
||||
cls.validate_upload(filename, len(audio_bytes))
|
||||
|
||||
client = cls._get_client()
|
||||
model = cls._resolve_model()
|
||||
safe_name = cls._normalize_filename(filename, content_type)
|
||||
file_obj = io.BytesIO(audio_bytes)
|
||||
file_obj.name = safe_name
|
||||
|
||||
try:
|
||||
result = client.audio.transcriptions.create(
|
||||
model=model,
|
||||
file=file_obj,
|
||||
)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f'Speech recognition request failed: {exc}') from exc
|
||||
|
||||
text = str(getattr(result, 'text', '') or '').strip()
|
||||
return text, model
|
||||
@@ -0,0 +1,620 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
class Text2SQLService:
|
||||
_schema_text = None
|
||||
_oracle_client_initialized = False
|
||||
_oracle_dll_handles = []
|
||||
|
||||
@staticmethod
|
||||
def _backend_dir() -> str:
|
||||
return os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
@classmethod
|
||||
def _project_root(cls) -> str:
|
||||
return os.path.dirname(cls._backend_dir())
|
||||
|
||||
@classmethod
|
||||
def _resolve_project_path(cls, path_value: str) -> str:
|
||||
normalized = os.path.normpath(path_value)
|
||||
if os.path.isabs(normalized):
|
||||
return normalized
|
||||
return os.path.normpath(os.path.join(cls._project_root(), normalized))
|
||||
|
||||
@classmethod
|
||||
def _find_oracle_client_dir(cls) -> str | None:
|
||||
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
|
||||
candidate_roots = []
|
||||
if env_dir:
|
||||
candidate_roots.append(cls._resolve_project_path(env_dir))
|
||||
candidate_roots.extend([
|
||||
os.path.join(cls._backend_dir(), 'oracle_client'),
|
||||
os.path.join(cls._project_root(), 'oracle_client'),
|
||||
os.path.join(os.getcwd(), 'oracle_client'),
|
||||
'/app/oracle_client',
|
||||
'/opt/oracle',
|
||||
])
|
||||
library_markers = {'oci.dll', 'libclntsh.so', 'libclntsh.dylib'}
|
||||
for oracle_client_dir in candidate_roots:
|
||||
if not oracle_client_dir or not os.path.exists(oracle_client_dir):
|
||||
continue
|
||||
try:
|
||||
entries = os.listdir(oracle_client_dir)
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
entry_names = {name.lower() for name in entries}
|
||||
if library_markers & entry_names:
|
||||
return oracle_client_dir
|
||||
|
||||
client_dirs = [
|
||||
os.path.join(oracle_client_dir, d)
|
||||
for d in entries
|
||||
if d.startswith('instantclient_') and os.path.isdir(os.path.join(oracle_client_dir, d))
|
||||
]
|
||||
if client_dirs:
|
||||
return client_dirs[0]
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _log(level: str, message: str):
|
||||
if has_app_context():
|
||||
getattr(current_app.logger, level, current_app.logger.info)(message)
|
||||
|
||||
@staticmethod
|
||||
def _prepend_env_path(var_name: str, path_value: str):
|
||||
if not path_value:
|
||||
return
|
||||
current = os.getenv(var_name, "")
|
||||
parts = [p for p in current.split(os.pathsep) if p]
|
||||
if path_value in parts:
|
||||
return
|
||||
os.environ[var_name] = path_value + (os.pathsep + current if current else "")
|
||||
|
||||
@classmethod
|
||||
def _prepare_oracle_runtime_env(cls, target_lib_dir: str | None):
|
||||
if not target_lib_dir:
|
||||
return
|
||||
try:
|
||||
import platform
|
||||
system_name = platform.system()
|
||||
if system_name == "Linux":
|
||||
cls._prepend_env_path("LD_LIBRARY_PATH", target_lib_dir)
|
||||
elif system_name == "Darwin":
|
||||
cls._prepend_env_path("DYLD_LIBRARY_PATH", target_lib_dir)
|
||||
elif system_name == "Windows":
|
||||
cls._prepend_env_path("PATH", target_lib_dir)
|
||||
if hasattr(os, "add_dll_directory"):
|
||||
handle = os.add_dll_directory(target_lib_dir)
|
||||
cls._oracle_dll_handles.append(handle)
|
||||
except Exception as exc:
|
||||
cls._log("warning", f"Failed to prepare Oracle runtime env: {exc}")
|
||||
|
||||
@classmethod
|
||||
def _ensure_oracle_client_initialized(cls, oracledb):
|
||||
if cls._oracle_client_init_attempted:
|
||||
return cls._oracle_client_mode == "thick"
|
||||
|
||||
cls._oracle_client_init_attempted = True
|
||||
try:
|
||||
if not getattr(oracledb, "is_thin_mode", lambda: True)():
|
||||
cls._oracle_client_mode = "thick"
|
||||
return True
|
||||
|
||||
import platform
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
target_lib_dir = cls._find_oracle_client_dir()
|
||||
if platform.system() == 'Windows' and target_lib_dir and not target_lib_dir.isascii():
|
||||
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
|
||||
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
|
||||
if os.path.exists(target_lib_dir):
|
||||
os.makedirs(temp_dir, exist_ok=True)
|
||||
shutil.copytree(target_lib_dir, safe_lib_dir, dirs_exist_ok=True)
|
||||
target_lib_dir = safe_lib_dir
|
||||
|
||||
cls._prepare_oracle_runtime_env(target_lib_dir)
|
||||
|
||||
if target_lib_dir:
|
||||
oracledb.init_oracle_client(lib_dir=target_lib_dir)
|
||||
else:
|
||||
oracledb.init_oracle_client()
|
||||
|
||||
cls._oracle_client_mode = "thin" if getattr(oracledb, "is_thin_mode", lambda: True)() else "thick"
|
||||
if cls._oracle_client_mode == "thick":
|
||||
cls._log("info", f"Oracle thick mode initialized successfully. lib_dir={target_lib_dir or 'system-default'}")
|
||||
return True
|
||||
|
||||
cls._oracle_client_init_error = "Oracle client initialized but driver is still in thin mode"
|
||||
except Exception as exc:
|
||||
cls._oracle_client_init_error = str(exc)
|
||||
cls._oracle_client_mode = "thin"
|
||||
cls._log("warning", f"Failed to init Oracle thick mode: {exc}")
|
||||
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def _format_connection_error(cls, error_message: str) -> str:
|
||||
message = (error_message or "").strip()
|
||||
if "DPY-3010" in message or "DPY-6005" in message:
|
||||
init_error = cls._oracle_client_init_error or "未找到可用的 Oracle Instant Client"
|
||||
return (
|
||||
"Oracle 连接失败:当前驱动仍在 thin mode,而该 ERP Oracle 版本需要 thick mode。"
|
||||
"请在部署环境提供 Oracle Instant Client,并将项目根目录的 oracle_client 挂载到 /app/oracle_client "
|
||||
"或设置 ORACLE_CLIENT_LIB_DIR。"
|
||||
f"当前 thick mode 初始化错误:{init_error}"
|
||||
)
|
||||
return message or "未知数据库错误"
|
||||
|
||||
@staticmethod
|
||||
def _extract_invalid_identifier(error_message: str) -> str:
|
||||
match = re.search(r'ORA-00904:\s*"?(?P<name>[A-Za-z0-9_#$]+)"?\s*:\s*invalid identifier', error_message or "", re.IGNORECASE)
|
||||
return (match.group("name") if match else "").upper()
|
||||
|
||||
@staticmethod
|
||||
def _is_repairable_sql_error(error_message: str) -> bool:
|
||||
text = (error_message or "").upper()
|
||||
return any(code in text for code in ("ORA-00904", "ORA-00942", "INVALID IDENTIFIER", "TABLE OR VIEW DOES NOT EXIST"))
|
||||
|
||||
@classmethod
|
||||
def _get_oracle_client_dir(cls) -> str | None:
|
||||
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
|
||||
if env_dir:
|
||||
resolved_env_dir = cls._resolve_project_path(env_dir)
|
||||
if os.path.exists(resolved_env_dir):
|
||||
return resolved_env_dir
|
||||
|
||||
linux_candidates = [
|
||||
"/opt/oracle/instantclient",
|
||||
"/opt/oracle/instantclient_19_28",
|
||||
"/opt/oracle/instantclient_19_27",
|
||||
]
|
||||
for path in linux_candidates:
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
|
||||
return cls._find_oracle_client_dir()
|
||||
|
||||
@classmethod
|
||||
def _init_oracle_client(cls, oracledb) -> None:
|
||||
if cls._oracle_client_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)():
|
||||
return
|
||||
|
||||
import platform
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
target_lib_dir = cls._get_oracle_client_dir()
|
||||
cls._prepare_oracle_runtime_env(target_lib_dir)
|
||||
|
||||
if platform.system() == 'Windows' and target_lib_dir:
|
||||
# OCI C-library fails to load if path contains non-ASCII.
|
||||
if not target_lib_dir.isascii():
|
||||
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
|
||||
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
|
||||
if os.path.exists(target_lib_dir):
|
||||
os.makedirs(temp_dir, exist_ok=True)
|
||||
shutil.copytree(target_lib_dir, safe_lib_dir, dirs_exist_ok=True)
|
||||
target_lib_dir = safe_lib_dir
|
||||
cls._prepare_oracle_runtime_env(target_lib_dir)
|
||||
|
||||
if target_lib_dir:
|
||||
oracledb.init_oracle_client(lib_dir=target_lib_dir)
|
||||
else:
|
||||
oracledb.init_oracle_client()
|
||||
cls._oracle_client_initialized = True
|
||||
|
||||
@classmethod
|
||||
def get_schema(cls):
|
||||
if cls._schema_text is None:
|
||||
schema_filename = '(表+字段).md'
|
||||
env_path = (os.getenv("TEXT2SQL_SCHEMA_PATH") or "").strip()
|
||||
candidate_paths = []
|
||||
if env_path:
|
||||
candidate_paths.append(env_path)
|
||||
|
||||
candidate_paths.extend([
|
||||
os.path.join(cls._backend_dir(), 'docs', schema_filename),
|
||||
os.path.join(cls._project_root(), 'docs', schema_filename),
|
||||
os.path.join(os.getcwd(), 'docs', schema_filename),
|
||||
])
|
||||
|
||||
unique_paths = []
|
||||
seen = set()
|
||||
for path in candidate_paths:
|
||||
normalized = os.path.normpath(path)
|
||||
if normalized not in seen:
|
||||
seen.add(normalized)
|
||||
unique_paths.append(path)
|
||||
|
||||
for doc_path in unique_paths:
|
||||
try:
|
||||
if not os.path.exists(doc_path):
|
||||
continue
|
||||
with open(doc_path, 'r', encoding='utf-8') as f:
|
||||
cls._schema_text = f.read()
|
||||
cls._log("info", f"Loaded Text2SQL schema from {doc_path}")
|
||||
break
|
||||
except Exception as exc:
|
||||
cls._log("warning", f"Failed to load Text2SQL schema from {doc_path}: {exc}")
|
||||
|
||||
if cls._schema_text is None:
|
||||
tried = ", ".join(unique_paths)
|
||||
cls._schema_text = f"Failed to load schema: schema file not found. Tried: {tried}"
|
||||
cls._log("warning", cls._schema_text)
|
||||
return cls._schema_text
|
||||
|
||||
@staticmethod
|
||||
def _clean_llm_output(content: str) -> str:
|
||||
cleaned = (content or "").strip()
|
||||
cleaned = re.sub(r"^```(?:sql|json)?\s*", "", cleaned, flags=re.IGNORECASE)
|
||||
cleaned = re.sub(r"\s*```$", "", cleaned)
|
||||
return cleaned.strip()
|
||||
|
||||
@classmethod
|
||||
def _get_llm_client(cls):
|
||||
try:
|
||||
from openai import OpenAI
|
||||
except ImportError:
|
||||
return None, "OpenAI SDK not installed"
|
||||
|
||||
api_key = os.getenv("GJL_API_KEY", "")
|
||||
base_url = os.getenv("GJL_API_BASE", "https://api.siliconflow.cn/v1")
|
||||
|
||||
if not api_key:
|
||||
return None, "Missing GJL_API_KEY. Please configure it in .env to enable Text-to-SQL"
|
||||
|
||||
return OpenAI(api_key=api_key, base_url=base_url), None
|
||||
|
||||
@classmethod
|
||||
def _chat_completion(cls, system_prompt: str, user_prompt: str, temperature: float = 0):
|
||||
client, error = cls._get_llm_client()
|
||||
if error:
|
||||
raise RuntimeError(error)
|
||||
|
||||
response = client.chat.completions.create(
|
||||
model=os.getenv("GJL_MODEL", "deepseek-ai/DeepSeek-V3"),
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=temperature,
|
||||
)
|
||||
content = response.choices[0].message.content or ""
|
||||
return cls._clean_llm_output(content)
|
||||
|
||||
@staticmethod
|
||||
def _escape_sql_message(message: str) -> str:
|
||||
safe = (message or "").replace("'", "''").replace("\n", " ").strip()
|
||||
return safe or "Unknown error"
|
||||
|
||||
@staticmethod
|
||||
def _is_safe_query(sql: str) -> bool:
|
||||
sql = (sql or "").strip()
|
||||
if not re.match(r"(?is)^(select|with)\b", sql):
|
||||
return False
|
||||
return not re.search(r"(?is)\b(insert|update|delete|merge|alter|drop|truncate|create|grant|revoke)\b", sql)
|
||||
|
||||
@staticmethod
|
||||
def _stringify_value(value):
|
||||
if value is None:
|
||||
return "NULL"
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _serialize_results_for_llm(cls, columns, rows, max_rows: int = 30) -> str:
|
||||
preview_rows = rows[:max_rows]
|
||||
preview = []
|
||||
for row in preview_rows:
|
||||
preview.append({columns[idx]: cls._stringify_value(value) for idx, value in enumerate(row)})
|
||||
payload = {
|
||||
"columns": columns,
|
||||
"row_count": len(rows),
|
||||
"preview_row_count": len(preview_rows),
|
||||
"truncated": len(rows) > max_rows,
|
||||
"rows": preview,
|
||||
}
|
||||
return json.dumps(payload, ensure_ascii=False)
|
||||
|
||||
@classmethod
|
||||
def summarize_result(cls, query: str, columns, rows) -> str:
|
||||
if columns == ["Error"]:
|
||||
error_message = rows[0][0] if rows and rows[0] else "未知错误"
|
||||
return f"- 直击答案:查询执行失败,当前无法返回结果。\n- 异常提醒:数据库返回错误 `{error_message}`,请检查筛选条件、表名或字段名。"
|
||||
|
||||
if not rows:
|
||||
return "- 直击答案:当前未查询到符合条件的数据。\n- 趋势发现:当前结果未体现明显趋势。\n- 异常提醒:当前结果未体现明显异常,建议调整筛选条件后重试。"
|
||||
|
||||
system_prompt = f"""你是一位资深的业务分析师。
|
||||
任务:根据下方的数据库查询结果,为用户提供一份简洁、直观的分析汇总。
|
||||
|
||||
汇总要求:
|
||||
- 直击答案:第一句话直接回答用户的核心问题。
|
||||
- 趋势发现:如果有时间维度,请指出增长或下降趋势。
|
||||
- 异常提醒:如果数据中有显著的极值或异常,请标注。
|
||||
- 语言风格:专业且易懂,避免直接念数字,要讲出数字背后的业务含义。
|
||||
- 格式:使用 Markdown 列表。
|
||||
- 如果查询结果没有体现明显趋势或异常,请明确写出“当前结果未体现明显趋势”或“当前结果未体现明显异常”,不要编造。
|
||||
- 结合用户原始问题组织语言,不要重复输出 SQL,也不要复述字段名清单。"""
|
||||
|
||||
user_prompt = f"""原始问题:{query}
|
||||
查询数据:{cls._serialize_results_for_llm(columns, rows)}"""
|
||||
|
||||
try:
|
||||
summary = cls._chat_completion(system_prompt, user_prompt, temperature=0.2)
|
||||
return summary or cls._fallback_summary(columns, rows)
|
||||
except Exception:
|
||||
return cls._fallback_summary(columns, rows)
|
||||
|
||||
@classmethod
|
||||
def _fallback_summary(cls, columns, rows) -> str:
|
||||
if not rows:
|
||||
return "- 直击答案:当前未查询到符合条件的数据。\n- 趋势发现:当前结果未体现明显趋势。\n- 异常提醒:当前结果未体现明显异常。"
|
||||
|
||||
if len(rows) == 1 and len(columns) == 1:
|
||||
return (
|
||||
f"- 直击答案:{columns[0]} 为 {cls._stringify_value(rows[0][0])}。\n"
|
||||
"- 趋势发现:当前结果未体现明显趋势。\n"
|
||||
"- 异常提醒:当前结果未体现明显异常。"
|
||||
)
|
||||
|
||||
return (
|
||||
f"- 直击答案:本次共返回 {len(rows)} 条记录,可结合下方明细进一步查看。\n"
|
||||
"- 趋势发现:当前结果未体现明显趋势。\n"
|
||||
"- 异常提醒:当前结果未体现明显异常。"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def generate_sql(cls, query: str) -> str:
|
||||
schema = cls.get_schema()
|
||||
|
||||
try:
|
||||
system_prompt = f"""你是一个专业的 Oracle SQL 专家和数据分析助手。你的任务是将用户的自然语言转换为准确的 Oracle 查询语句。
|
||||
|
||||
数据库结构 (Schema):
|
||||
{schema}
|
||||
|
||||
约束要求:
|
||||
- 只输出 SQL,不要解释。
|
||||
- 日期查询请优先使用 CURRENT_DATE 进行计算。
|
||||
- 如果用户问题模糊,请选择最合理的关联方式,优先使用 LEFT JOIN 补充维度信息。
|
||||
- 严禁生成任何 INSERT、UPDATE、DELETE、MERGE、ALTER、DROP、TRUNCATE、CREATE 语句。
|
||||
- 仅允许输出单条 SELECT 或 WITH 开头的查询。
|
||||
- 必须使用 Schema 中出现的精确表名,包含完整前缀,如 ERP_VIEW_USER.ERP_FAJ_FILE_V。
|
||||
- 必须只使用 Schema 中明确出现过的字段名,禁止臆造通用字段名,例如 FILE_TYPE、STATUS_NAME、AMOUNT 等。
|
||||
- 优先选择最相关字段,避免 SELECT *。
|
||||
- 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。
|
||||
- 如果问题无法仅依据当前 Schema 回答,请输出安全的 SELECT 语句说明原因,例如 SELECT '无法根据当前表结构回答该问题' AS message FROM DUAL。"""
|
||||
|
||||
user_prompt = f"用户问题:{query}"
|
||||
sql = cls._chat_completion(system_prompt, user_prompt, temperature=0)
|
||||
sql = sql.rstrip(";")
|
||||
|
||||
if not cls._is_safe_query(sql):
|
||||
return "SELECT 'Generated SQL was blocked because it is not a safe read-only SELECT query' AS error FROM DUAL"
|
||||
|
||||
return sql
|
||||
except Exception as e:
|
||||
return f"SELECT '{cls._escape_sql_message(f'LLM Error: {e}')}' AS error FROM DUAL"
|
||||
|
||||
@classmethod
|
||||
def repair_sql(cls, query: str, failed_sql: str, error_message: str) -> str:
|
||||
schema = cls.get_schema()
|
||||
invalid_identifier = cls._extract_invalid_identifier(error_message)
|
||||
invalid_hint = f"本次报错的非法字段/标识符是:{invalid_identifier}。" if invalid_identifier else ""
|
||||
|
||||
system_prompt = f"""你是一个专业的 Oracle SQL 修复助手。你的任务是根据执行失败的 SQL、数据库报错和当前 Schema,修复成一条可执行的 Oracle 查询语句。
|
||||
|
||||
数据库结构 (Schema):
|
||||
{schema}
|
||||
|
||||
修复要求:
|
||||
- 只输出 SQL,不要解释。
|
||||
- 必须保留用户问题的原始意图。
|
||||
- 必须只使用 Schema 中真实存在的表名和字段名。
|
||||
- 严禁创造 FILE_TYPE、STATUS_NAME 这类 Schema 中不存在的字段。
|
||||
- 如果当前 Schema 无法支持该问题,请输出:SELECT '无法根据当前表结构回答该问题' AS message FROM DUAL
|
||||
- 严禁输出任何非 SELECT / WITH 语句。"""
|
||||
|
||||
user_prompt = f"""用户问题:{query}
|
||||
执行失败的 SQL:
|
||||
```sql
|
||||
{failed_sql}
|
||||
```
|
||||
|
||||
数据库错误:{error_message}
|
||||
{invalid_hint}
|
||||
|
||||
请根据上述错误修复 SQL,并确保只使用当前 Schema 中真实存在的表和字段。"""
|
||||
|
||||
try:
|
||||
sql = cls._chat_completion(system_prompt, user_prompt, temperature=0)
|
||||
sql = sql.rstrip(";")
|
||||
if not cls._is_safe_query(sql):
|
||||
return "SELECT 'Generated SQL was blocked because it is not a safe read-only SELECT query' AS error FROM DUAL"
|
||||
return sql
|
||||
except Exception as e:
|
||||
return f"SELECT '{cls._escape_sql_message(f'SQL Repair Error: {e}')}' AS error FROM DUAL"
|
||||
|
||||
@classmethod
|
||||
def execute_sql(cls, sql: str):
|
||||
try:
|
||||
import oracledb
|
||||
except ImportError:
|
||||
return ["Error"], [["oracledb is not installed"]]
|
||||
|
||||
user = "EXT_VIEW_USER"
|
||||
password = "extviewuser"
|
||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||
|
||||
try:
|
||||
# Old ERP Oracle versions require python-oracledb thick mode.
|
||||
cls._init_oracle_client(oracledb)
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.warning(f"Failed to init thick mode: {e}")
|
||||
|
||||
try:
|
||||
connection = oracledb.connect(user=user, password=password, dsn=dsn)
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(sql)
|
||||
|
||||
columns = [col[0] for col in cursor.description]
|
||||
# Use fetchmany(50) instead of LLM-generated FETCH FIRST to support older Oracle versions
|
||||
rows = cursor.fetchmany(50)
|
||||
|
||||
cursor.close()
|
||||
connection.close()
|
||||
|
||||
return columns, rows
|
||||
except Exception as e:
|
||||
error_text = str(e)
|
||||
if current_app:
|
||||
current_app.logger.warning(f"Oracle direct query failed: {error_text}")
|
||||
return ["Error"], [[error_text]]
|
||||
|
||||
@classmethod
|
||||
def format_result(cls, columns, rows, sql, original_query):
|
||||
summary_text = cls.summarize_result(original_query, columns, rows)
|
||||
sql_details = f"<details>\n<summary class=\"cursor-pointer text-xs font-semibold uppercase tracking-wide text-slate-600 dark:text-slate-300 mb-2\">执行的SQL</summary>\n\n```sql\n{sql}\n```\n</details>"
|
||||
|
||||
if columns == ["Error"]:
|
||||
error_message = rows[0][0] if rows and rows[0] else "未知错误"
|
||||
return f"{summary_text}\n\n**错误详情**\n\n`{error_message}`\n\n{sql_details}"
|
||||
|
||||
if not columns or not rows:
|
||||
return f"{summary_text}\n\n{sql_details}"
|
||||
|
||||
header = "| " + " | ".join(columns) + " |"
|
||||
separator = "| " + " | ".join(["---"] * len(columns)) + " |"
|
||||
|
||||
body = []
|
||||
for row in rows:
|
||||
body.append("| " + " | ".join([cls._stringify_value(val) for val in row]) + " |")
|
||||
|
||||
table_str = "\n".join([header, separator] + body)
|
||||
|
||||
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
|
||||
|
||||
@staticmethod
|
||||
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, session_id: str | None = None):
|
||||
"""Yields SSE events to frontend just like DifyService"""
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"erp_{int(time.time())}"
|
||||
try:
|
||||
# 1. Generate SQL
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '🧠 正在理解您的问题并生成底层查询代码 (SQL)...\n'})}\n\n"
|
||||
stage_start = time.time()
|
||||
sql = Text2SQLService.generate_sql(query)
|
||||
generate_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] generate_sql done conversation_id=%s elapsed_ms=%s sql_preview=%s",
|
||||
final_conversation_id,
|
||||
generate_sql_ms,
|
||||
(sql or "")[:300],
|
||||
)
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '🔍 已完成查询口径分析,正在数据库中检索海量数据,请稍候...\n'})}\n\n"
|
||||
|
||||
# 2. Execute SQL
|
||||
stage_start = time.time()
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
execute_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] execute_sql done conversation_id=%s elapsed_ms=%s columns=%s row_count=%s",
|
||||
final_conversation_id,
|
||||
execute_sql_ms,
|
||||
len(columns or []),
|
||||
len(rows or []),
|
||||
)
|
||||
if columns == ["Error"] and rows and rows[0]:
|
||||
error_message = str(rows[0][0] or "")
|
||||
if Text2SQLService._is_repairable_sql_error(error_message):
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '检测到字段或表结构不匹配,正在依据现有 Schema 自动修正 SQL...\n'})}\n\n"
|
||||
repair_stage_start = time.time()
|
||||
repaired_sql = Text2SQLService.repair_sql(query, sql, error_message)
|
||||
repair_sql_ms = int((time.time() - repair_stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] repair_sql done conversation_id=%s elapsed_ms=%s sql_changed=%s",
|
||||
final_conversation_id,
|
||||
repair_sql_ms,
|
||||
bool(repaired_sql and repaired_sql != sql),
|
||||
)
|
||||
if repaired_sql and repaired_sql != sql:
|
||||
sql = repaired_sql
|
||||
stage_start = time.time()
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
execute_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] execute_sql retry done conversation_id=%s elapsed_ms=%s columns=%s row_count=%s",
|
||||
final_conversation_id,
|
||||
execute_sql_ms,
|
||||
len(columns or []),
|
||||
len(rows or []),
|
||||
)
|
||||
|
||||
# 3. Format result
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '📝 数据检索完成,正在生成最终业务报告...\n'})}\n\n"
|
||||
stage_start = time.time()
|
||||
result_text = Text2SQLService.format_result(columns, rows, sql, query)
|
||||
format_result_ms = int((time.time() - stage_start) * 1000)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] format_result done conversation_id=%s elapsed_ms=%s total_ms=%s",
|
||||
final_conversation_id,
|
||||
format_result_ms,
|
||||
latency,
|
||||
)
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
"[text2sql] stream_chat failed conversation_id=%s query=%s",
|
||||
final_conversation_id,
|
||||
query,
|
||||
)
|
||||
error_data = {
|
||||
'event': 'error',
|
||||
'message': str(exc) or 'ERP 问数执行失败',
|
||||
'conversation_id': final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
return
|
||||
|
||||
# Create ChatLog
|
||||
from app.models import ChatLog, db
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=final_conversation_id,
|
||||
session_id=session_id,
|
||||
query=query,
|
||||
answer=result_text,
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.error(f'Failed to log text2sql chat: {e}')
|
||||
db.session.rollback()
|
||||
|
||||
end_data = {
|
||||
'event': 'message_end',
|
||||
'answer': result_text,
|
||||
'replace_answer': True,
|
||||
'chat_log_id': chat_log_id,
|
||||
'conversation_id': final_conversation_id
|
||||
}
|
||||
yield f"data: {json.dumps(end_data)}\n\n"
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
WeCom (企业微信) callback crypto helpers — compatible with WXBizMsgCrypt layout.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import random
|
||||
import struct
|
||||
from typing import Optional
|
||||
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
|
||||
def sha1_hex(parts: list[str]) -> str:
|
||||
merged = ''.join(sorted([str(p) for p in parts if p is not None]))
|
||||
return hashlib.sha1(merged.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes:
|
||||
pad_len = block_size - (len(data) % block_size)
|
||||
return data + bytes([pad_len] * pad_len)
|
||||
|
||||
|
||||
def _pkcs7_unpad(data: bytes) -> bytes:
|
||||
if not data:
|
||||
return data
|
||||
pad_len = data[-1]
|
||||
if pad_len < 1 or pad_len > 32:
|
||||
raise ValueError('invalid pkcs7 padding')
|
||||
if data[-pad_len:] != bytes([pad_len] * pad_len):
|
||||
raise ValueError('invalid pkcs7 padding tail')
|
||||
return data[:-pad_len]
|
||||
|
||||
|
||||
def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes:
|
||||
raw = (encoding_aes_key_b64 or '').strip()
|
||||
key = base64.b64decode(raw + '=')
|
||||
if len(key) != 32:
|
||||
raise ValueError('EncodingAESKey must decode to 32 bytes')
|
||||
return key
|
||||
|
||||
|
||||
def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
"""
|
||||
Encrypt plain text to base64 ciphertext (for tests / optional outbound use).
|
||||
"""
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
random_bytes = bytes(random.randint(0, 255) for _ in range(16))
|
||||
msg_bytes = plain_text.encode('utf-8')
|
||||
pack = (
|
||||
random_bytes
|
||||
+ struct.pack('>I', len(msg_bytes))
|
||||
+ msg_bytes
|
||||
+ corp_id.encode('utf-8')
|
||||
)
|
||||
padded = _pkcs7_pad(pack, 32)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
encrypted = cipher.encrypt(padded)
|
||||
return base64.b64encode(encrypted).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str:
|
||||
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
|
||||
iv = aes_key[:16]
|
||||
cipher_bytes = base64.b64decode(cipher_b64)
|
||||
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
|
||||
plain_padded = cipher.decrypt(cipher_bytes)
|
||||
plain = _pkcs7_unpad(plain_padded)
|
||||
content = plain[16:]
|
||||
if len(content) < 4:
|
||||
raise ValueError('decrypted payload too short')
|
||||
xml_len = struct.unpack('>I', content[:4])[0]
|
||||
xml_bytes = content[4:4 + xml_len]
|
||||
tail = content[4 + xml_len:]
|
||||
if tail.decode('utf-8', errors='strict') != corp_id:
|
||||
raise ValueError('corp_id mismatch after decrypt')
|
||||
return xml_bytes.decode('utf-8')
|
||||
|
||||
|
||||
def extract_encrypt_field(xml_body: str) -> Optional[str]:
|
||||
if not xml_body:
|
||||
return None
|
||||
import re
|
||||
|
||||
m = re.search(r'<Encrypt><!\[CDATA\[(.*?)\]\]></Encrypt>', xml_body, re.DOTALL)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
m2 = re.search(r'<Encrypt>(.*?)</Encrypt>', xml_body, re.DOTALL)
|
||||
if m2:
|
||||
return m2.group(1).strip()
|
||||
return None
|
||||
@@ -0,0 +1,202 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from io import BytesIO
|
||||
from urllib.parse import urlencode
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import User, WecomNotifyAudit
|
||||
|
||||
|
||||
_TOKEN_CACHE = {
|
||||
'token': None,
|
||||
'expires_at': None,
|
||||
}
|
||||
|
||||
|
||||
def _get_enabled_events() -> set[str]:
|
||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||
if isinstance(raw, str):
|
||||
return {x.strip() for x in raw.split(',') if x.strip()}
|
||||
if isinstance(raw, (list, tuple, set)):
|
||||
return {str(x).strip() for x in raw if str(x).strip()}
|
||||
return set()
|
||||
|
||||
|
||||
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
|
||||
base = current_app.config.get('WECOM_NOTIFY_BASE_URL') or ''
|
||||
if not base:
|
||||
return ''
|
||||
base = base.rstrip('/')
|
||||
if not path.startswith('/'):
|
||||
path = f'/{path}'
|
||||
merged = {'wecom_trace': trace_id}
|
||||
if params:
|
||||
merged.update({k: v for k, v in params.items() if v is not None})
|
||||
return f'{base}{path}?{urlencode(merged)}'
|
||||
|
||||
|
||||
def _get_access_token() -> str:
|
||||
now = datetime.utcnow()
|
||||
token = _TOKEN_CACHE.get('token')
|
||||
expires_at = _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')
|
||||
resp = requests.get(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
|
||||
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}")
|
||||
|
||||
_TOKEN_CACHE['token'] = data['access_token']
|
||||
_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
|
||||
return data['access_token']
|
||||
|
||||
|
||||
def _create_audit(
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
trace_id: str,
|
||||
) -> WecomNotifyAudit:
|
||||
audit = WecomNotifyAudit(
|
||||
event_type=event_type,
|
||||
status='failed',
|
||||
trace_id=trace_id,
|
||||
user_id=user.id if user else None,
|
||||
username=user.username if user else None,
|
||||
wecom_userid=user.wecom_userid if user else None,
|
||||
title=title,
|
||||
content=content,
|
||||
)
|
||||
db.session.add(audit)
|
||||
return audit
|
||||
|
||||
|
||||
def upload_wecom_temp_media(file_data: bytes, filename: str) -> str:
|
||||
token = _get_access_token()
|
||||
url = (
|
||||
f'https://qyapi.weixin.qq.com/cgi-bin/media/upload'
|
||||
f'?access_token={token}&type=file'
|
||||
)
|
||||
resp = requests.post(
|
||||
url,
|
||||
files={'media': (filename, BytesIO(file_data), 'application/octet-stream')},
|
||||
timeout=30,
|
||||
)
|
||||
data = resp.json()
|
||||
if data.get('errcode', 0) != 0 or not data.get('media_id'):
|
||||
raise RuntimeError(f"WeCom media upload failed: {data}")
|
||||
return data['media_id']
|
||||
|
||||
|
||||
def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'file',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'file': {'media_id': media_id},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
def send_wecom_textcard_message(
|
||||
wecom_userid: str,
|
||||
title: str,
|
||||
description: str,
|
||||
jump_url: str,
|
||||
) -> dict:
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or (current_app.config.get('WECOM_NOTIFY_BASE_URL') or 'https://work.weixin.qq.com'),
|
||||
'btntxt': '查看详情',
|
||||
},
|
||||
'safe': 0,
|
||||
}
|
||||
resp = requests.post(
|
||||
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
|
||||
params={'access_token': token},
|
||||
json=payload,
|
||||
timeout=8,
|
||||
)
|
||||
return resp.json()
|
||||
|
||||
|
||||
def send_wecom_event_message(
|
||||
*,
|
||||
event_type: str,
|
||||
user: User,
|
||||
title: str,
|
||||
content: str,
|
||||
jump_path: str = '/workspace',
|
||||
jump_params: dict | None = None,
|
||||
) -> dict:
|
||||
trace_id = uuid.uuid4().hex
|
||||
audit = _create_audit(event_type, user, title, content, trace_id)
|
||||
|
||||
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
||||
audit.error_code = 'NOTIFY_DISABLED'
|
||||
audit.error_message = 'WECOM_NOTIFY_ENABLED=false'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'notify_disabled'}
|
||||
|
||||
if event_type not in _get_enabled_events():
|
||||
audit.error_code = 'EVENT_DISABLED'
|
||||
audit.error_message = f'event {event_type} disabled'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'}
|
||||
|
||||
if not user or not user.wecom_userid:
|
||||
audit.error_code = 'WECOM_USER_UNBOUND'
|
||||
audit.error_message = 'user has no wecom_userid'
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
|
||||
|
||||
try:
|
||||
jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = jump_url
|
||||
data = send_wecom_textcard_message(user.wecom_userid, title, content, jump_url)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
audit.error_code = str(data.get('errcode'))
|
||||
audit.error_message = str(data.get('errmsg', 'unknown error'))[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'send_failed', 'raw': data}
|
||||
except Exception as exc:
|
||||
audit.error_code = 'EXCEPTION'
|
||||
audit.error_message = str(exc)[:255]
|
||||
return {'ok': False, 'trace_id': trace_id, 'reason': 'exception'}
|
||||
|
||||
|
||||
def mark_wecom_message_opened(trace_id: str) -> bool:
|
||||
if not trace_id:
|
||||
return False
|
||||
row = db.session.query(WecomNotifyAudit).filter_by(trace_id=trace_id).first()
|
||||
if not row:
|
||||
return False
|
||||
if not row.opened_at:
|
||||
row.opened_at = datetime.utcnow()
|
||||
return True
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
Loaded 100 of 415 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user