Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
639df1b8c5 | ||
|
|
1bd9f278fe | ||
|
|
1cdc365955 | ||
|
|
b89d93d738 | ||
|
|
6adea87a5f | ||
|
|
4474ef7e3f | ||
|
|
0d3a812e16 | ||
|
|
acbf7d5921 | ||
|
|
a89491f4b1 | ||
|
|
8efc526ca8 | ||
|
|
f9b04eddc8 | ||
|
|
873331dd20 | ||
|
|
2aa8609c17 | ||
|
|
1bc938155a | ||
|
|
0c5ee4aec1 | ||
|
|
d5928b42f3 | ||
|
|
08360a4142 | ||
|
|
0a7e68a58a | ||
|
|
8246c09ab0 | ||
|
|
ddb704f574 | ||
|
|
7300098ff9 | ||
|
|
82ad4323f8 | ||
|
|
70e8f700ff | ||
|
|
cdd227d550 | ||
|
|
0f499b47f7 | ||
|
|
0d59b23e0c | ||
|
|
757231e3d5 | ||
|
|
c38a56536e | ||
|
|
10b6f9b692 | ||
|
|
6757ad869f | ||
|
|
d46d61bfa1 | ||
|
|
f224217fb0 | ||
|
|
97a5a1f106 | ||
|
|
55cf7ff734 | ||
|
|
634dee4b81 | ||
|
|
93f4ea5537 | ||
|
|
66410c9a27 | ||
|
|
cf7cc11ffc | ||
|
|
98481c7ea7 | ||
|
|
457f0f4e5e | ||
|
|
a523ec0454 | ||
|
|
21b8c24815 | ||
|
|
b69d549b2c | ||
|
|
6f9c25bb34 | ||
|
|
950d661b4f | ||
|
|
3264ed1e07 | ||
|
|
9b36ced288 | ||
|
|
b079524b4f | ||
|
|
d3cfd24d6f | ||
|
|
0ac165049d | ||
|
|
1eb6bf4aad | ||
|
|
7544361c05 | ||
|
|
f6fe56f205 | ||
|
|
638fdcb7fd | ||
|
|
29a7704d46 | ||
|
|
24310b63b3 | ||
|
|
6baeffba64 | ||
|
|
fa0cdee8df | ||
|
|
9cba517bff | ||
|
|
f5aac9c893 | ||
|
|
9bc4d1dd18 | ||
|
|
ec97ea8787 | ||
|
|
587a215d88 | ||
|
|
8d8b40812d | ||
|
|
3f61e92549 | ||
|
|
c1c4efe4f1 | ||
|
|
6d0e78be81 | ||
|
|
d4f629106f | ||
|
|
ced7fbe085 | ||
|
|
ae6a5e7c55 | ||
|
|
9d7dad6a4b | ||
|
|
dc141d19a2 | ||
|
|
e827c5dc38 | ||
|
|
599d492895 | ||
|
|
bf32f8b954 | ||
|
|
4b562cfa82 | ||
|
|
ee39270069 | ||
|
|
b82f31af8f | ||
|
|
67d08924a4 | ||
|
|
487b4e6090 | ||
|
|
a18a07ef1a | ||
|
|
fee33f69d9 | ||
|
|
3068e3abb4 | ||
|
|
25cc87fdb3 | ||
|
|
2631f78b00 | ||
|
|
1f1f7236b0 | ||
|
|
54edba8b39 | ||
|
|
24551e9a9a | ||
|
|
8a541211b7 | ||
|
|
33d505cd53 | ||
|
|
5d5127f5e8 | ||
|
|
89616179db | ||
|
|
c01ddb8b23 | ||
|
|
8a0a7fd6ed | ||
|
|
a88b60e505 | ||
|
|
6d40d504c5 | ||
|
|
d9b414b07b | ||
|
|
96cc3913fc | ||
|
|
a6df97f731 | ||
|
|
0a647a0b79 | ||
|
|
c98754e634 | ||
|
|
6b06e74946 | ||
|
|
d4db6876ad | ||
|
|
4fc85be607 | ||
|
|
ff7c227cc2 | ||
|
|
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 | ||
|
|
137d9508ae | ||
|
|
888e8f3054 | ||
|
|
c7871c94b5 | ||
|
|
efae286f5c | ||
|
|
fafcdfe742 | ||
|
|
7475828c63 | ||
|
|
29bd60a24b | ||
|
|
f6a23c9534 | ||
|
|
514c3d01be | ||
|
|
20271ada61 | ||
|
|
42e29fd747 | ||
|
|
35f650720f | ||
|
|
e06d5f7e01 | ||
|
|
5e8ea03b6c | ||
|
|
605317c2b2 | ||
|
|
639b0944db | ||
|
|
4d5a9942c2 | ||
|
|
df7beb2189 | ||
|
|
24da604727 | ||
|
|
a0c8721fbb | ||
|
|
b48f1e592a | ||
|
|
3a6e82bb03 | ||
|
|
9ccfb97fa9 | ||
|
|
b3e233bf76 | ||
|
|
f18b6ce2df | ||
|
|
2b8a0010ef | ||
|
|
2ece8a2ca0 | ||
|
|
abb3efe114 |
No files matched your search
@@ -0,0 +1,70 @@
|
||||
---
|
||||
description: 文件层与函数层注释强制规范(撰写与调整代码时均适用)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 代码注释(强制)
|
||||
|
||||
撰写或**修改**代码时,必须补齐或更新两层注释。完整说明见 `AGENTS.md` §5。
|
||||
|
||||
## 文件层(文件顶部)
|
||||
|
||||
块注释须包含:**用途**、**主要 import/依赖**、**与上下游文件的逻辑关系**。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* features/kb/composables/useKbWorkspace.ts
|
||||
* 用途:知识库作业面编排入口,组合 state / computed / data 等子模块。
|
||||
* 依赖:kb-workspace/* composables、kb.api、kb-display.utils。
|
||||
* 逻辑:KbWorkspaceView 调用本 composable;本文件再分发至 useKbWorkspaceData 等子模块。
|
||||
*/
|
||||
```
|
||||
|
||||
```python
|
||||
"""
|
||||
services/kb_sync.py
|
||||
|
||||
用途:知识库文档与 Dify 之间的同步编排。
|
||||
依赖:dify_service、models.KbDocument、minio_service。
|
||||
逻辑:由 api/knowledge_base 路由调用;内部委托 chunking 与 job 状态机。
|
||||
"""
|
||||
```
|
||||
|
||||
## 函数层(每个函数定义上方)
|
||||
|
||||
须说明:**用途**、**核心逻辑与实现方式**、**参数**与**返回值**(及异常)。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* 加载当前分组下的文档列表,并在静默刷新时合并 stable 项避免闪烁。
|
||||
* 核心逻辑:调用 getKbGroupFilesSafe,按 mergeStableItems 策略合并新旧列表。
|
||||
* @param options.silent - 为 true 时不切换 loading,用于轮询刷新
|
||||
* @returns 是否成功拉取到数据
|
||||
*/
|
||||
async function loadDocuments(options?: LoadListOptions): Promise<boolean> { ... }
|
||||
```
|
||||
|
||||
```python
|
||||
def sync_document_to_dify(document_id: int, *, force: bool = False) -> SyncResult:
|
||||
"""
|
||||
将指定文档切片同步至 Dify 知识库。
|
||||
|
||||
核心逻辑:读 MinIO 原文 → 切块 → 调 Dify API upsert;失败写入 KbJob 供重试。
|
||||
|
||||
Args:
|
||||
document_id: 本地 KbDocument 主键。
|
||||
force: 为 True 时忽略已完成状态强制重同步。
|
||||
|
||||
Returns:
|
||||
SyncResult: 含 dify_document_id 与分段数。
|
||||
|
||||
Raises:
|
||||
KbNotFoundError: 文档不存在或无权限。
|
||||
"""
|
||||
```
|
||||
|
||||
## 修改既有文件时
|
||||
|
||||
- 改函数逻辑/签名 → 同步改该函数注释。
|
||||
- 改 import 或模块协作关系 → 同步改文件头注释。
|
||||
- Vue SFC:`<script setup>` 内每个函数同样要求函数层注释。
|
||||
@@ -0,0 +1,112 @@
|
||||
---
|
||||
description: 文件层、函数层与代码逻辑层注释强制规范(撰写与调整代码时均适用)
|
||||
alwaysApply: true
|
||||
---
|
||||
|
||||
# 📝 代码与 Agent 注释规范(强制)
|
||||
|
||||
**【核心思想】**
|
||||
本规范适用于我们的敏捷开发团队。代码中的注释不仅是为了让人类团队成员(包括非科班背景的同事)看懂,**更是为了让 AI(如大模型调用、代码补全工具)准确理解上下文。**
|
||||
|
||||
撰写或**修改**代码时,必须补齐或更新以下**三层注释**。
|
||||
|
||||
---
|
||||
|
||||
## 1. 文件层(文件顶部)
|
||||
|
||||
块注释须包含:**文件路径/名称**、**用途**、**主要 import/依赖**、**与上下游文件的逻辑关系**。
|
||||
|
||||
```typescript
|
||||
/**
|
||||
* features/kb/composables/useKbWorkspace.ts
|
||||
* 用途:知识库作业面编排入口,组合 state / computed / data 等子模块。
|
||||
* 依赖:kb-workspace/* composables、kb.api、kb-display.utils。
|
||||
* 逻辑:KbWorkspaceView 调用本 composable;本文件再分发至 useKbWorkspaceData 等子模块。
|
||||
*/
|
||||
```
|
||||
|
||||
```python
|
||||
"""
|
||||
services/kb_sync.py
|
||||
|
||||
用途:知识库文档与 Dify 之间的同步编排。
|
||||
依赖:dify_service、models.KbDocument、minio_service。
|
||||
逻辑:由 api/knowledge_base 路由调用;内部委托 chunking 与 job 状态机。
|
||||
"""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. 函数/工具层(每个函数定义上方)
|
||||
|
||||
须说明:**用途(如果是给大模型调用的Tool,必须写明触发时机)**、**核心逻辑与实现方式**、**参数**与**返回值**(及异常)。
|
||||
|
||||
**普通业务函数示例 (TypeScript):**
|
||||
```typescript
|
||||
/**
|
||||
* 加载当前分组下的文档列表,并在静默刷新时合并 stable 项避免闪烁。
|
||||
* 核心逻辑:调用 getKbGroupFilesSafe,按 mergeStableItems 策略合并新旧列表。
|
||||
* @param options.silent - 为 true 时不切换 loading,用于轮询刷新
|
||||
* @returns 是否成功拉取到数据
|
||||
*/
|
||||
async function loadDocuments(options?: LoadListOptions): Promise<boolean> { ... }
|
||||
```
|
||||
|
||||
**Agent 工具函数示例 (Python,给大模型看的):**
|
||||
```python
|
||||
def sync_document_to_dify(document_id: int, *, force: bool = False) -> SyncResult:
|
||||
"""
|
||||
将指定文档切片同步至 Dify 知识库。
|
||||
【AI 触发时机】:当用户要求“更新知识库”、“同步最新文档资料”时调用此工具。
|
||||
|
||||
核心逻辑:读 MinIO 原文 → 切块 → 调 Dify API upsert;失败写入 KbJob 供重试。
|
||||
|
||||
Args:
|
||||
document_id: 本地 KbDocument 主键。禁止传入非整数的 ID。
|
||||
force: 为 True 时忽略已完成状态强制重同步。默认为 False。
|
||||
|
||||
Returns:
|
||||
SyncResult: 包含 dify_document_id (str) 与分段数 (int) 的对象。
|
||||
|
||||
Raises:
|
||||
KbNotFoundError: 文档不存在或无权限。
|
||||
"""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 代码逻辑层(函数内部)
|
||||
|
||||
**严禁逐行翻译代码**(如 `i = i + 1` 不用注释)。只针对**复杂业务逻辑块**和**AI特定组件**进行标准化标记。
|
||||
|
||||
* **逻辑分块**:使用 `[STEP 1]`, `[STEP 2]` 来拆解长函数的执行步骤。解释“为什么这么做”。
|
||||
* **Prompt 标记**:使用 `[PROMPT_UPDATE]` 记录提示词的修改时间和原因。
|
||||
* **参数标记**:使用 `[PARAM_TUNING]` 说明大模型参数(如 Temperature)为何这么设置。
|
||||
|
||||
```python
|
||||
def generate_article_summary(topic: str):
|
||||
# [STEP 1] 构建并校验基础参数
|
||||
if not topic:
|
||||
return {"error": "主题不能为空"}
|
||||
|
||||
# [STEP 2] 组装 LLM 提示词
|
||||
# [PROMPT_UPDATE] 2024-05-20: 增加"禁止道歉"指令,防止模型遇到敏感词时输出无用废话。
|
||||
system_prompt = f"You are an expert. Topic: {topic}. Rule: Do not apologize."
|
||||
|
||||
# [STEP 3] 调用模型
|
||||
response = llm_client.chat(
|
||||
prompt=system_prompt,
|
||||
# [PARAM_TUNING] Temperature 设为 0.2,因为此处需要严格提取摘要,不需要发散性创意。
|
||||
temperature=0.2
|
||||
)
|
||||
return response
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 修改既有文件时的纪律
|
||||
|
||||
- **改函数逻辑/签名** → 强制同步改该函数的上方注释。
|
||||
- **改 import 或模块协作关系** → 强制同步改文件头部的依赖与逻辑注释。
|
||||
- **改了 Prompt 或模型参数** → 强制追加 `[PROMPT_UPDATE]` 或 `[PARAM_TUNING]` 记录。
|
||||
- **Vue SFC**:`<script setup>` 内的每个核心函数同样要求遵循上述“函数层”注释规范。
|
||||
@@ -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 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
# 文件存储(相对 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=
|
||||
@@ -1,16 +0,0 @@
|
||||
JWT_SECRET=change-me
|
||||
DATABASE_BACKEND=postgres
|
||||
DATABASE_URL=
|
||||
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
|
||||
POSTGRES_DATABASE_URL=postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning
|
||||
PUBLIC_BASE_URL=http://127.0.0.1:8891
|
||||
DIFY_BASE_URL=https://api.dify.ai/v1
|
||||
DIFY_API_KEY=
|
||||
INTEGRATION_API_KEY=change-me-internal
|
||||
INTEGRATION_DOWNLOAD_SECRET=change-me-download-signing-secret
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
DIFY_SYNC_MAX_RETRIES=4
|
||||
DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300
|
||||
DIFY_SYNC_COOLDOWN_SECONDS=60
|
||||
@@ -0,0 +1,62 @@
|
||||
# =============================================================================
|
||||
# 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
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
MINIO_ENDPOINT=host.docker.internal:9000
|
||||
MINIO_ACCESS_KEY=admin
|
||||
MINIO_SECRET_KEY=difyai123456
|
||||
MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
# Shared environment variables for all environments (dev/test/prod)
|
||||
# Keep only values that are truly identical across all environments.
|
||||
|
||||
# Runtime selector fallback (actual deployment still sets ENV_NAME explicitly)
|
||||
ENV_NAME=dev
|
||||
# Common runtime defaults
|
||||
FLASK_APP=run.py
|
||||
|
||||
# 知识库管理(后续需要修改此地址)
|
||||
# 查「Dify 文档对应原始源文件下载地址」时,要连的那台 Integration API 的根 URL
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
# 连接文档清洗系统的API KEY
|
||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# 文件检核 Tool API Key;未单独配置时建议与 INTEGRATION_API_KEY 保持一致
|
||||
FILE_CHECK_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
SECRET_KEY=hxops-dify
|
||||
|
||||
# Knowledge base runtime
|
||||
# KB_STORAGE_ROOT=backend/data/kb
|
||||
KB_TASK_EXECUTION_MODE=worker
|
||||
KB_WORKER_POLL_SECONDS=2
|
||||
KB_WORKER_CONCURRENCY=3
|
||||
# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径)
|
||||
EDKB_SOFFICE=/usr/bin/soffice
|
||||
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
|
||||
EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
|
||||
EDKB_WORD_TIMEOUT_SEC=300
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||
EDKB_FILE_TIMEOUT_SEC=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=true
|
||||
WECOM_CORP_ID=ww1ada6c11b684783e
|
||||
WECOM_AGENT_ID=1000065
|
||||
WECOM_SECRET=N9a1EE6pDj_6wTpRrXmg9Vn4BdK54jb7yFmSQ0-FSwU
|
||||
WECOM_REDIRECT_URI=
|
||||
WECOM_AUTO_CREATE_USER=true
|
||||
WECOM_MATCH_RULES=employee_id,mobile
|
||||
WECOM_MATCH_OPERATOR=AND
|
||||
WECOM_FIRST_LOGIN_BIND_MODE=match_rules
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS=employee_id,mobile,email
|
||||
WECOM_EMPLOYEE_ID_SOURCE=userid
|
||||
WECOM_MOBILE_NORMALIZE=true
|
||||
WECOM_CALLBACK_TOKEN=
|
||||
WECOM_ENCODING_AES_KEY=
|
||||
WECOM_CALLBACK_URL=
|
||||
WECOM_HOMEPAGE_URL=
|
||||
WECOM_TRUSTED_DOMAIN=
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host)
|
||||
WECOM_PUBLIC_BASE_URL=
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_BASE_URL=
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bdb65cf6-e537-44b2-a10b-d826b15f4498
|
||||
|
||||
|
||||
# Common integration defaults
|
||||
INTEGRATION_API_MODE=local
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow、OpenAPI、签名下载链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_TOOLS_API_BASE=
|
||||
|
||||
# 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=
|
||||
|
||||
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
|
||||
# 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置
|
||||
FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过)
|
||||
FAQ_HOT_WINDOW_DAYS=7 # 统计时间窗口(天),仅扫描近 N 天 ChatLog
|
||||
FAQ_HOT_MIN_COUNT=5 # 同一应用+问句最少提问次数,低于此不进入候选
|
||||
FAQ_HOT_MIN_USERS=3 # 最少独立用户数,防止单人刷榜
|
||||
FAQ_HOT_MIN_AVG_TOKENS=0 # 组内平均 token 下限(0=不限制;须 tokens_used>0 才纳入)
|
||||
FAQ_HOT_MAX_QUERY_LEN=200 # 问句最大字符数,过长跳过
|
||||
FAQ_HOT_MIN_QUERY_LEN=4 # 问句最短字符数,过短跳过
|
||||
FAQ_HOT_MIN_ANSWER_LEN=8 # 答案最短字符数,过短跳过
|
||||
FAQ_HOT_TTL_SECONDS=604800 # 候选/忽略黑名单有效期(秒),默认 7 天
|
||||
FAQ_HOT_ANSWER_SIMILARITY=0.95 # (聚类已关闭)答案聚类相似度阈值,恢复聚类时生效
|
||||
FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇占比下限,恢复聚类时生效
|
||||
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
|
||||
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||
@@ -0,0 +1,115 @@
|
||||
# =============================================================================
|
||||
# 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
|
||||
|
||||
# 货代发货通知 Agent(见 docs/shipping_notice.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
# 文件存储(相对 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,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
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
cd "${ROOT_DIR}"
|
||||
# shellcheck source=_common.sh
|
||||
source "${ROOT_DIR}/.githooks/_common.sh"
|
||||
|
||||
STAGED_FILES="$(git diff --cached --name-only --diff-filter=ACMR || true)"
|
||||
if [[ -z "${STAGED_FILES}" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
MODELS_CHANGED=0
|
||||
MIGRATION_CHANGED=0
|
||||
|
||||
if echo "${STAGED_FILES}" | grep -Eq '^backend/app/models\.py$'; then
|
||||
MODELS_CHANGED=1
|
||||
fi
|
||||
|
||||
if echo "${STAGED_FILES}" | grep -Eq '^backend/migrations/versions/.*\.py$'; then
|
||||
MIGRATION_CHANGED=1
|
||||
fi
|
||||
|
||||
if [[ "${MODELS_CHANGED}" -eq 1 && "${MIGRATION_CHANGED}" -eq 0 ]]; then
|
||||
echo "[pre-commit] 检测到 backend/app/models.py 已暂存,但未检测到 migration 文件暂存。"
|
||||
echo "[pre-commit] 请先执行:"
|
||||
echo " cd backend"
|
||||
echo " venv/bin/flask --app manage.py db migrate -m \"your_change\""
|
||||
echo " venv/bin/flask --app manage.py db upgrade"
|
||||
echo " git add backend/migrations/versions/*.py"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# migration 链校验:防止多人并行 migration 合并后出现多 head,部署时 db upgrade 失败
|
||||
# 实现见 scripts/check_migration_heads.py(离线读文件,无需数据库)
|
||||
if [[ "${MIGRATION_CHANGED}" -eq 1 ]]; then
|
||||
STAGED_NEW_MIGRATIONS="$(git diff --cached --name-only --diff-filter=A -- 'backend/migrations/versions/*.py' || true)"
|
||||
if ! run_migration_heads_check "${ROOT_DIR}" "${STAGED_NEW_MIGRATIONS}"; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if hook_should_skip; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if frontend_paths_in "${STAGED_FILES}"; then
|
||||
if ! run_frontend_typecheck "${ROOT_DIR}"; then
|
||||
echo "[pre-commit] vue-tsc 失败,已阻止提交。"
|
||||
echo "[pre-commit] 跳过前端检查: SKIP_FRONTEND_HOOKS=1 git commit"
|
||||
echo "[pre-commit] 或跳过全部 hook: git commit --no-verify"
|
||||
exit 1
|
||||
fi
|
||||
echo "[pre-commit] frontend 类型检查通过。"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
# shellcheck source=_common.sh
|
||||
source "${ROOT_DIR}/.githooks/_common.sh"
|
||||
|
||||
if [[ "${SKIP_GIT_HOOKS:-}" == "1" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
zero="0000000000000000000000000000000000000000"
|
||||
need_migration_check=0
|
||||
need_frontend_build=0
|
||||
|
||||
while read -r local_ref local_sha remote_ref remote_sha; do
|
||||
[[ "${local_sha}" == "${zero}" ]] && continue
|
||||
|
||||
changed_files=""
|
||||
if [[ "${remote_sha}" == "${zero}" ]]; then
|
||||
upstream_ref="$(git rev-parse --abbrev-ref --symbolic-full-name '@{u}' 2>/dev/null || true)"
|
||||
if [[ -n "${upstream_ref}" ]]; then
|
||||
remote_branch="${upstream_ref#*/}"
|
||||
remote_name="${upstream_ref%%/*}"
|
||||
merge_base="$(git merge-base "${local_sha}" "${remote_name}/${remote_branch}" 2>/dev/null || true)"
|
||||
if [[ -n "${merge_base}" ]]; then
|
||||
changed_files="$(git diff --name-only --diff-filter=ACMR "${merge_base}" "${local_sha}" || true)"
|
||||
fi
|
||||
fi
|
||||
if [[ -z "${changed_files}" ]]; then
|
||||
changed_files="$(git diff-tree --no-commit-id --name-only --diff-filter=ACMR -r "${local_sha}" || true)"
|
||||
fi
|
||||
else
|
||||
changed_files="$(git diff --name-only --diff-filter=ACMR "${remote_sha}" "${local_sha}" || true)"
|
||||
fi
|
||||
|
||||
if echo "${changed_files}" | grep -qE '^backend/migrations/versions/.*\.py$'; then
|
||||
need_migration_check=1
|
||||
fi
|
||||
|
||||
if frontend_paths_in "${changed_files}"; then
|
||||
need_frontend_build=1
|
||||
fi
|
||||
done
|
||||
|
||||
if [[ "${need_migration_check}" -eq 1 ]]; then
|
||||
if ! run_migration_heads_check "${ROOT_DIR}"; then
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ "${need_frontend_build}" -eq 0 ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! run_frontend_build "${ROOT_DIR}"; then
|
||||
echo "[pre-push] 前端 build 失败,已阻止 push。"
|
||||
echo "[pre-push] 跳过检查可设置: SKIP_FRONTEND_HOOKS=1 git push"
|
||||
echo "[pre-push] 或跳过全部 hook: git push --no-verify"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[pre-push] 前端 build 通过。"
|
||||
exit 0
|
||||
+76
-70
@@ -1,75 +1,81 @@
|
||||
# =========================
|
||||
# Secrets / env
|
||||
# =========================
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
backend.env
|
||||
backend.env.*
|
||||
!backend.env.example
|
||||
*.key
|
||||
*.pem
|
||||
*secret*
|
||||
*token*
|
||||
# Environments
|
||||
#docs/
|
||||
venv/
|
||||
backend/venv/
|
||||
backend/instance/
|
||||
tmpwork/
|
||||
env/
|
||||
|
||||
# =========================
|
||||
# OS / IDE
|
||||
# =========================
|
||||
# .env
|
||||
.venv
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# Root tooling (commitlint)
|
||||
/node_modules/
|
||||
package-lock.json
|
||||
|
||||
# Frontend
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
frontend/.DS_Store
|
||||
frontend/.env.local
|
||||
frontend/.env.*.local
|
||||
frontend/.npm-cache
|
||||
frontend/public/WW_verify_46MjWA55y3PBRLid.txt
|
||||
frontend/package-lock.json
|
||||
|
||||
# IDEs
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/extensions.json
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Runtime files
|
||||
.run/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# =========================
|
||||
# Python
|
||||
# =========================
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
# Runtime files
|
||||
.run/
|
||||
# tmp
|
||||
.tmp/
|
||||
.tmp2/
|
||||
|
||||
.npm-cache
|
||||
.npm-cache2
|
||||
.pip-cache
|
||||
|
||||
|
||||
# 忽略Oracle Instant Client本地目录
|
||||
oracle_client/
|
||||
|
||||
# local env override
|
||||
.env.local
|
||||
backend/data/kb/
|
||||
.pytest_cache/
|
||||
.venv/
|
||||
venv/
|
||||
python/
|
||||
|
||||
# =========================
|
||||
# Node
|
||||
# =========================
|
||||
frontend/node_modules/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# =========================
|
||||
# Build outputs
|
||||
# =========================
|
||||
frontend/dist/
|
||||
dist/
|
||||
build/
|
||||
out/
|
||||
target/
|
||||
|
||||
# =========================
|
||||
# Runtime temp/logs
|
||||
# =========================
|
||||
tmp_run/
|
||||
*.log
|
||||
|
||||
# =========================
|
||||
# Databases (不要提交测试数据/本地库)
|
||||
# =========================
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# =========================
|
||||
# Archives / bundles (不要提交打包产物)
|
||||
# =========================
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
|
||||
# =========================
|
||||
# Optional: staging deploy output (如果是生成物就忽略)
|
||||
# =========================
|
||||
.deploy-stage/
|
||||
backend/data/fixed_assets/manifest.json
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["ms-python.python", "ms-python.vscode-pylance"]
|
||||
}
|
||||
Vendored
+34
@@ -0,0 +1,34 @@
|
||||
{
|
||||
// 后端 Python 虚拟环境
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
|
||||
"python.terminal.activateEnvironment": true,
|
||||
"python.venvPath": "${workspaceFolder}/backend",
|
||||
"python.venvFolders": [".venv"],
|
||||
|
||||
// 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv
|
||||
"terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)",
|
||||
"terminal.integrated.profiles.windows": {
|
||||
"PowerShell (HXOPS)": {
|
||||
"source": "PowerShell",
|
||||
"icon": "terminal-powershell",
|
||||
"args": [
|
||||
"-NoExit",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-File",
|
||||
"${workspaceFolder}/scripts/powershell-backend-auto-venv.ps1"
|
||||
]
|
||||
},
|
||||
"HXOPS Backend": {
|
||||
"source": "PowerShell",
|
||||
"icon": "server-environment",
|
||||
"args": [
|
||||
"-NoExit",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-Command",
|
||||
"Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
# AGENTS.md — HXOPS 协作与开发规范
|
||||
|
||||
> 本文件是 **AI 编程助手(Cursor / Codex 等)和团队成员的统一入口**。
|
||||
> 原则:**只写最关键的强约束、速览与索引,详细内容一律链接到 `docs/` 下的权威文档**,避免双份维护。
|
||||
> 修改本文件请走正常评审;规则若与 `docs/` 冲突,以 `docs/` 中的专项文档为准。
|
||||
|
||||
---
|
||||
|
||||
## 1. 项目速览
|
||||
|
||||
**Enterprise AI Gateway(HXOPS)**:企业级 AI 聚合网关,统一管理/分发 AI Agent(Dify 应用),提供统一对话入口、RBAC 权限、全链路审计与个性化工作台。
|
||||
|
||||
| 层 | 技术栈 |
|
||||
| --- | --- |
|
||||
| 前端 | Vue 3 (Composition API) + TypeScript + Vite + TailwindCSS + Pinia + Vue Router + Vue I18n |
|
||||
| 后端 | Flask (Python 3.12) + Gevent + SQLAlchemy 2.0 + Flask-Migrate(Alembic) + Gunicorn |
|
||||
| 数据/基建 | PostgreSQL + Redis + Nginx + Supervisor + Docker Compose |
|
||||
| 集成 | Dify、企业微信、OA/HR(SQLServer)、PLM(Oracle)、MinIO |
|
||||
| 研发协作 | Gitee 托管 + Jenkins CI/CD(dev/test/prod 多环境) |
|
||||
|
||||
完整背景见 **[docs/project_context.md](docs/project_context.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 技术架构统一(新功能选型)
|
||||
|
||||
> 仓库历史代码后端为 Flask,仍按原栈维护;**新功能/新模块**统一向以下技术栈收敛:
|
||||
|
||||
- **后端**:优先使用 **Python + FastAPI**(异步、Pydantic 校验、自动 OpenAPI 文档)。
|
||||
- **前端**:优先使用 **Vue 3 + TailwindCSS**(Composition API + TypeScript)。
|
||||
- 数据访问继续使用 **SQLAlchemy 2.0**;数据库迁移继续使用 **Alembic**(见 §8)。
|
||||
- 选型有特殊需要偏离上述约定时,须在评审/提交说明中给出理由。
|
||||
|
||||
---
|
||||
|
||||
## 3. 目录地图(改代码前先定位)
|
||||
|
||||
```text
|
||||
backend/app/
|
||||
api/ # Blueprint 路由(admin / chat / agents / knowledge_base / shipping_notice ...)
|
||||
services/ # 业务逻辑(dify、oa_*、plm_oracle、minio_service、wecom_* ...)
|
||||
models.py # SQLAlchemy 模型(改这里必须配套迁移,见 §8)
|
||||
response_utils.py / errors.py / decorators.py # 统一返回、异常、权限装饰器
|
||||
backend/migrations/ # Alembic 迁移文件
|
||||
frontend/src/
|
||||
features/ # 按业务域组织(admin / auth / chat)
|
||||
composables/# Hooks(如 useChat.ts)
|
||||
views/ components/ i18n.ts
|
||||
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
|
||||
docs/ # 权威文档(规范、上下文、流程、发布说明)
|
||||
```
|
||||
|
||||
**约定**:新逻辑优先放入对应 `services/`(后端)或 `features/composables/`(前端),复用既有 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
|
||||
|
||||
---
|
||||
|
||||
## 4. 常用命令
|
||||
|
||||
```bash
|
||||
# 后端
|
||||
cd backend && source venv/bin/activate
|
||||
python run.py # 启动开发服务器
|
||||
flask db migrate -m "msg" && flask db upgrade # 数据库迁移
|
||||
|
||||
# 前端
|
||||
cd frontend && npm run dev # 开发
|
||||
npm run build # 改动了 frontend/ 必须保证 build 通过
|
||||
|
||||
# 部署(与 Jenkins 一致,示例:prod)
|
||||
./scripts/deploy_compose.sh prod true true true
|
||||
docker compose logs -f hxops-backend
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. 代码规范与注释
|
||||
|
||||
> **适用范围**:**新建或调整**业务代码(人工与 AI Agent 均适用)。Agent 持久规则见 **[`.cursor/rules/code-comments.mdc`](.cursor/rules/code-comments.mdc)**。
|
||||
|
||||
### 5.1 文件层注释(必须)
|
||||
|
||||
每个源文件顶部须有块注释,说明:
|
||||
|
||||
1. **用途**:本文件在模块/业务流程中的职责。
|
||||
2. **引用关系**:主要 `import` / 依赖的上游模块或文件(不必列全量 import,列关键依赖即可)。
|
||||
3. **逻辑关系**:与同级或上下游文件如何协作(谁调用谁、数据/状态如何流转)。
|
||||
|
||||
| 语言/形态 | 写法 |
|
||||
| --- | --- |
|
||||
| 前端 TS/JS | 文件首行 `/** ... */`(JSDoc 块注释) |
|
||||
| Vue SFC | 写在 `<script>` / `<script setup>` 块内首行 |
|
||||
| 后端 Python | 模块级 docstring(文件首行三引号字符串) |
|
||||
|
||||
### 5.2 函数层注释(必须)
|
||||
|
||||
**每个函数**(含方法、composable、路由 handler、类方法;导出的工具函数、组件内 `<script setup>` 函数均包含在内)在定义**上方**须有注释,说明:
|
||||
|
||||
1. **用途**:该函数解决什么问题、在调用链中的位置。
|
||||
2. **核心逻辑与实现方式**:关键步骤、算法/策略、外部服务或副作用。
|
||||
3. **参数与输出**:每个入参含义、返回值含义;可能抛出的异常或错误码(如有)。
|
||||
|
||||
| 语言 | 写法 |
|
||||
| --- | --- |
|
||||
| 前端 | JSDoc:`@param` / `@returns` / `@throws`(TypeScript 类型无法表达的业务约束写在描述里) |
|
||||
| 后端 | docstring(Google 或 NumPy 风格均可,须含 Args/Returns/Raises 或等价段落) |
|
||||
|
||||
**调整既有代码时**:修改函数签名、逻辑或副作用,必须**同步更新**对应函数注释;协作关系变化时同步更新文件层注释。
|
||||
|
||||
### 5.3 其它约定
|
||||
|
||||
- **函数内**:不必逐行复述「是什么」;对非显而易见的分支、业务规则、兼容处理、外部协议/边界条件可补 brief 行内注释。
|
||||
- **复杂或临时方案**:临时方案用 `TODO:` / `FIXME:` 标注并附原因或关联任务号。
|
||||
- **注释与代码同步**:禁止留下与实现不符的过期注释。
|
||||
- **统一语言**:注释可用中文,术语/标识符保持与代码一致。
|
||||
- **禁止**用注释提交被注释掉的废弃代码(交给 Git 历史管理)。
|
||||
|
||||
### 5.4 测试代码
|
||||
|
||||
测试代码在 §5.1–§5.2 基础上,另须 **代码层注释**(函数内关键断言与分支意图),见 **[docs/test_plan_matrix.md](docs/test_plan_matrix.md) §1**。
|
||||
|
||||
---
|
||||
|
||||
## 6. Git 提交规范(强制 / 已自动校验)
|
||||
|
||||
- 提交信息必须符合 **Conventional Commits**,由 `commitlint.config.cjs` + `.githooks/commit-msg` **自动拦截**。
|
||||
- 首次拉取后需安装 hooks:`./scripts/install_git_hooks.sh`。
|
||||
- 格式:`<type>(<scope>): <subject>`;`type`/`scope` 英文(scope 为 kebab-case 模块名),`subject` 中文,祈使语气、不以句号结尾、≤100 字符。
|
||||
- 允许的 `type`:`feat` `fix` `docs` `style` `refactor` `perf` `test` `build` `ci` `chore` `revert`。
|
||||
- 禁止无语义提交(`update`、`fix bug`、`111`);一个提交只做一件事。
|
||||
- **Cursor IDE**:源代码管理 ✨「Generate commit message」仅读取根目录 **`.cursorrules`**(不读 `.cursor/rules/`、`AGENTS.md`);**Agent 写/改代码**读 `AGENTS.md` §5 与 **`.cursor/rules/`**(如 `code-comments.mdc`);Agent 代提交读 `.cursor/rules/`。
|
||||
|
||||
详见 **[docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md)** 与 **[docs/GIT_HOOKS.md](docs/GIT_HOOKS.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 7. 分支与发布流程
|
||||
|
||||
- 分支主线:`dev`(日常开发)→ `test`(自测/交叉/质检)→ `prod`(生产发布)。
|
||||
- 功能分支从 `dev` 切出(`feature/xxx`、`fix/xxx`),完成后合回 `dev`。
|
||||
- **禁止**直接在 `prod` / 公共分支上开发或直推;`prod` 必须经合并请求。
|
||||
- 生产 hotfix 合入 `prod` 后须**反向同步**回 `dev`(必要时 `test`),避免分支漂移。
|
||||
- 发布完成对版本打 tag,格式 `V26.6.1`(26 年 6 月第 1 次发布)。
|
||||
|
||||
完整流程(含自测/交叉测试/质检/Review 卡点)见 **[docs/release_workflow.md](docs/release_workflow.md)** 与 **[docs/convention/开发标准流程.md](docs/convention/开发标准流程.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 8. 红线与高风险约束(agent 必须遵守)
|
||||
|
||||
- 🔒 **严禁提交任何密钥/密码/生产地址等敏感信息**。`.env.local` / `.env.*` 不进仓库的部分不得硬编码进代码或提交。
|
||||
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。
|
||||
- 🌐 **环境变量分层**:`.env.shared` + `.env.<env>`(dev/test/prod),不要在代码里写死环境值。规则见 **[docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md)** 与 **[docs/convention/环境变量规则.md](docs/convention/环境变量规则.md)**。
|
||||
- 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en-US / th-TH`,禁止硬编码中文。
|
||||
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
|
||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||
- 📝 **注释两层标准(强制)**:新建或调整代码须满足 §5 文件层 + 函数层注释;AI 生成/重构代码同样适用,不得省略。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
|
||||
---
|
||||
|
||||
## 9. 需求与文档维护(开发前先查,开发后必更)
|
||||
|
||||
开发任何功能前,**优先查阅以下文档**了解背景与现状:
|
||||
|
||||
- **[docs/demand.md](docs/demand.md)** — 需求文档(要做什么、业务目标与范围)。
|
||||
- **[docs/tec.md](docs/tec.md)** — 技术架构文档(架构设计、技术选型与约束)。
|
||||
- **[docs/funclist.md](docs/funclist.md)** — 功能清单(已有/在建功能总览)。
|
||||
|
||||
**撰写或变更功能时,必须同步更新相关文档**:
|
||||
|
||||
- 新增/调整功能 → 更新 `funclist.md`(功能清单)。
|
||||
- 涉及需求变化 → 更新 `demand.md`。
|
||||
- 涉及架构/技术选型变化 → 更新 `tec.md`。
|
||||
- 文档更新与代码改动放在同一提交或同一 PR 中,保证「代码与文档一致」。
|
||||
|
||||
---
|
||||
|
||||
## 10. 文档索引(权威来源)
|
||||
|
||||
| 主题 | 文档 |
|
||||
| --- | --- |
|
||||
| 项目上下文 / 架构 / 数据模型 | [docs/project_context.md](docs/project_context.md) |
|
||||
| 需求文档 | [docs/demand.md](docs/demand.md) |
|
||||
| 技术架构文档 | [docs/tec.md](docs/tec.md) |
|
||||
| 功能清单 | [docs/funclist.md](docs/funclist.md) |
|
||||
| 新人环境搭建 / 分支原则 | [docs/新人环境搭建与配置文档.md](docs/新人环境搭建与配置文档.md) |
|
||||
| 发布流程(dev→test→prod) | [docs/release_workflow.md](docs/release_workflow.md) · [docs/convention/开发标准流程.md](docs/convention/开发标准流程.md) |
|
||||
| 提交规范 | [docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md) |
|
||||
| Git Hooks | [docs/GIT_HOOKS.md](docs/GIT_HOOKS.md) |
|
||||
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
|
||||
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
||||
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
@@ -0,0 +1,197 @@
|
||||
# AGENTS.md — HXOPS 协作与开发规范
|
||||
|
||||
> 本文件是 **AI 编程助手(Cursor / Codex 等)和团队成员的统一入口**。
|
||||
> 原则:**只写最关键的强约束、速览与索引,详细内容一律链接到 `docs/` 下的权威文档**,避免双份维护。
|
||||
> 修改本文件请走正常评审;规则若与 `docs/` 冲突,以 `docs/` 中的专项文档为准。
|
||||
|
||||
---
|
||||
|
||||
## 1. 项目速览
|
||||
|
||||
**Enterprise AI Gateway(HXOPS)**:企业级 AI 聚合网关,统一管理/分发 AI Agent(Dify 应用),提供统一对话入口、RBAC 权限、全链路审计与个性化工作台。
|
||||
|
||||
| 层 | 技术栈 |
|
||||
| --- | --- |
|
||||
| 前端 | Vue 3 (Composition API) + TypeScript + Vite + TailwindCSS + Pinia + Vue Router + Vue I18n |
|
||||
| 后端 | Flask (Python 3.12) + Gevent + SQLAlchemy 2.0 + Flask-Migrate(Alembic) + Gunicorn |
|
||||
| 数据/基建 | PostgreSQL + Redis + Nginx + Supervisor + Docker Compose |
|
||||
| 集成 | Dify、企业微信、OA/HR(SQLServer)、PLM(Oracle)、MinIO |
|
||||
| 研发协作 | Gitee 托管 + Jenkins CI/CD(dev/test/prod 多环境) |
|
||||
|
||||
完整背景见 **[docs/project_context.md](docs/project_context.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 2. 技术架构统一(新功能选型)
|
||||
|
||||
> 仓库历史代码后端为 Flask,仍按原栈维护;**新功能/新模块**统一向以下技术栈收敛:
|
||||
|
||||
- **后端**:优先使用 **Python + FastAPI**(异步、Pydantic 校验、自动 OpenAPI 文档)。
|
||||
- **前端**:优先使用 **Vue 3 + TailwindCSS**(Composition API + TypeScript)。
|
||||
- 数据访问继续使用 **SQLAlchemy 2.0**;数据库迁移继续使用 **Alembic**(见 §8)。
|
||||
- 选型有特殊需要偏离上述约定时,须在评审/提交说明中给出理由。
|
||||
|
||||
---
|
||||
|
||||
## 3. 目录地图(改代码前先定位)
|
||||
|
||||
```text
|
||||
backend/app/
|
||||
api/ # Blueprint 路由(admin / chat / agents / knowledge_base / shipping_notice ...)
|
||||
services/ # 业务逻辑(dify、oa_*、plm_oracle、minio_service、wecom_* ...)
|
||||
models.py # SQLAlchemy 模型(改这里必须配套迁移,见 §8)
|
||||
response_utils.py / errors.py / decorators.py # 统一返回、异常、权限装饰器
|
||||
backend/migrations/ # Alembic 迁移文件
|
||||
frontend/src/
|
||||
main.ts · App.vue · i18n.ts · config.ts # Vite 入口(保留 src 根)
|
||||
app/ # 应用基础设施:router/(routes/* · guards)、plugins/pinia
|
||||
shared/ # 跨域共享(无业务语义)
|
||||
# api/client · composables · components · layouts · utils · styles
|
||||
features/ # 业务域垂直切分(新代码主要落在这里)
|
||||
# auth · workspace · chat · admin · kb
|
||||
# 域内:api/ · composables/ · views/ · stores/ · components/
|
||||
# admin 子模块:modules/<name>/*Page.vue + use*Admin.ts
|
||||
locales/ # i18n 四语言 JSON(zh-CN / zh-TW / en / th),按域拆分
|
||||
scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...)
|
||||
docs/ # 权威文档(规范、上下文、流程、发布说明)
|
||||
```
|
||||
|
||||
**约定**:
|
||||
|
||||
- **后端**:新逻辑优先放入 `services/`,复用 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。
|
||||
- **前端**:Feature-Module + Composables + Pinia;新功能放入 `features/<domain>/`(`api/` · `composables/` · `views/` 等),跨域通用代码放 `shared/`;HTTP 统一 `@/shared/api/client`。**禁止**在已废弃的 `src/api/`、`src/views/`、`src/composables/` 等路径新增代码。完整规范见 **[docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 4. 常用命令
|
||||
|
||||
```bash
|
||||
# 后端
|
||||
cd backend && source venv/bin/activate
|
||||
python run.py # 启动开发服务器
|
||||
flask db migrate -m "msg" && flask db upgrade # 数据库迁移
|
||||
|
||||
# 前端
|
||||
cd frontend && npm run dev # 开发
|
||||
npm run build # 改动了 frontend/ 必须保证 build 通过
|
||||
|
||||
# 部署(与 Jenkins 一致,示例:prod)
|
||||
./scripts/deploy_compose.sh prod true true true
|
||||
docker compose logs -f hxops-backend
|
||||
```
|
||||
|
||||
---
|
||||
## 5. 代码规范与注释 (Code & Comments)
|
||||
|
||||
> **适用范围**:**新建或调整**业务代码(人工与 AI Agent 均适用)。
|
||||
> **核心理念**:我们的注释采用“三层结构”,**既是写给人类团队看的,更是写给 AI(大模型/代码助手)看的**。
|
||||
> 🚨 **详细规范与标准范例,请严格遵循:[`.cursor/rules/code-comments.mdc`](.cursor/rules/code-comments.mdc)**。
|
||||
|
||||
### 5.1 文件层注释(全局概览)
|
||||
|
||||
每个源文件顶部须有块注释,帮助新人与 AI 快速建立全局认知。核心包含三要素:
|
||||
1. **用途**:本文件在业务流程中的职责。
|
||||
2. **依赖关系**:主要引用的上游模块(列关键即可)。
|
||||
3. **逻辑关系**:与上下游文件如何协作(数据流转或调用关系)。
|
||||
*(前端写在文件/Script首行块注释,后端使用模块级 docstring)*
|
||||
|
||||
### 5.2 函数与工具层注释(面向 AI 调用)
|
||||
|
||||
**每个核心函数**定义上方必须有注释。**极其重要**:如果该函数是被大模型调用的 Agent Tool,其注释将直接影响 AI 的判断。
|
||||
1. **用途与触发时机**:解决什么问题。**作为 AI 工具时,必须用大白话写明【AI 触发时机】**。
|
||||
2. **核心逻辑**:关键步骤与外部通讯流。
|
||||
3. **参数与输出约束**:除常规类型外,必须说明业务约束(如“禁止传入省份”、“必须返回 JSON”),以防 AI 乱传参。
|
||||
*(前端使用 JSDoc,后端使用含 Args/Returns 的 docstring)*
|
||||
|
||||
### 5.3 代码逻辑与 AI 专项标记
|
||||
|
||||
函数内部**严禁逐行翻译代码**(如说明 `i=i+1`)。应聚焦于“为什么这么做”以及 AI 的调优溯源:
|
||||
- **逻辑分块**:对非显而易见的长流程,使用 `[STEP 1]`, `[STEP 2]` 标注业务步骤。
|
||||
- **AI 调优溯源**:修改 Prompt 或大模型参数(如 Temperature)时,**强制使用 `[PROMPT_UPDATE]` 或 `[PARAM_TUNING]` 标注原因**。
|
||||
- **临时方案**:用 `TODO:` / `FIXME:` 标注并附原因或任务号。
|
||||
- **一致性纪律**:修改代码逻辑、修改协作关系,必须**同步更新**对应注释!禁止留下过期注释误导 AI。
|
||||
- **整洁度**:禁止用注释提交废弃代码(请交给 Git 历史管理)。
|
||||
|
||||
### 5.4 测试代码注释
|
||||
|
||||
测试代码在遵循上述基础之上,另须具备**代码层面的断言注释**(说明关键断言与分支测试意图),详见 **[docs/test_plan_matrix.md](docs/test_plan_matrix.md) §1**。
|
||||
---
|
||||
|
||||
## 6. Git 提交规范(强制 / 已自动校验)
|
||||
|
||||
- 提交信息必须符合 **Conventional Commits**,由 `commitlint.config.cjs` + `.githooks/commit-msg` **自动拦截**。
|
||||
- 首次拉取后需安装 hooks:`./scripts/install_git_hooks.sh`。
|
||||
- 格式:`<type>(<scope>): <subject>`;`type`/`scope` 英文(scope 为 kebab-case 模块名),`subject` 中文,祈使语气、不以句号结尾、≤100 字符。
|
||||
- 允许的 `type`:`feat` `fix` `docs` `style` `refactor` `perf` `test` `build` `ci` `chore` `revert`。
|
||||
- 禁止无语义提交(`update`、`fix bug`、`111`);一个提交只做一件事。
|
||||
- **Cursor IDE**:源代码管理 ✨「Generate commit message」仅读取根目录 **`.cursorrules`**(不读 `.cursor/rules/`、`AGENTS.md`);**Agent 写/改代码**读 `AGENTS.md` §5 与 **`.cursor/rules/`**(如 `code-comments.mdc`);Agent 代提交读 `.cursor/rules/`。
|
||||
|
||||
详见 **[docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md)** 与 **[docs/GIT_HOOKS.md](docs/GIT_HOOKS.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 7. 分支与发布流程
|
||||
|
||||
- 分支主线:`dev`(日常开发)→ `test`(自测/交叉/质检)→ `prod`(生产发布)。
|
||||
- 功能分支从 `dev` 切出(`feature/xxx`、`fix/xxx`),完成后合回 `dev`。
|
||||
- **禁止**直接在 `prod` / 公共分支上开发或直推;`prod` 必须经合并请求。
|
||||
- 生产 hotfix 合入 `prod` 后须**反向同步**回 `dev`(必要时 `test`),避免分支漂移。
|
||||
- 发布完成对版本打 tag,格式 `V26.6.1`(26 年 6 月第 1 次发布)。
|
||||
|
||||
完整流程(含自测/交叉测试/质检/Review 卡点)见 **[docs/release_workflow.md](docs/release_workflow.md)** 与 **[docs/convention/开发标准流程.md](docs/convention/开发标准流程.md)**。
|
||||
|
||||
---
|
||||
|
||||
## 8. 红线与高风险约束(agent 必须遵守)
|
||||
|
||||
- 🔒 **严禁提交任何密钥/密码/生产地址等敏感信息**。`.env.local` / `.env.*` 不进仓库的部分不得硬编码进代码或提交。
|
||||
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。
|
||||
- 🌐 **环境变量分层**:`.env.shared` + `.env.<env>`(dev/test/prod),不要在代码里写死环境值。规则见 **[docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md)** 与 **[docs/convention/环境变量规则.md](docs/convention/环境变量规则.md)**。
|
||||
- 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en-US / th-TH`,禁止硬编码中文。
|
||||
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
|
||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||
- 📝 **注释两层标准(强制)**:新建或调整代码须满足 §5 文件层 + 函数层注释;AI 生成/重构代码同样适用,不得省略。
|
||||
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
|
||||
---
|
||||
|
||||
## 9. 需求与文档维护(开发前先查,开发后必更)
|
||||
|
||||
开发任何功能前,**优先查阅以下文档**了解背景与现状:
|
||||
|
||||
- **[docs/demand.md](docs/demand.md)** — 需求文档(要做什么、业务目标与范围)。
|
||||
- **[docs/tec.md](docs/tec.md)** — 技术架构文档(架构设计、技术选型与约束)。
|
||||
- **[docs/funclist.md](docs/funclist.md)** — 功能清单(已有/在建功能总览)。
|
||||
|
||||
**撰写或变更功能时,必须同步更新相关文档**:
|
||||
|
||||
- 新增/调整功能 → 更新 `funclist.md`(功能清单)。
|
||||
- 涉及需求变化 → 更新 `demand.md`。
|
||||
- 涉及架构/技术选型变化 → 更新 `tec.md`。
|
||||
- 文档更新与代码改动放在同一提交或同一 PR 中,保证「代码与文档一致」。
|
||||
|
||||
---
|
||||
|
||||
## 10. 文档索引(权威来源)
|
||||
|
||||
| 主题 | 文档 |
|
||||
| --- | --- |
|
||||
| 项目上下文 / 架构 / 数据模型 | [docs/project_context.md](docs/project_context.md) |
|
||||
| 需求文档 | [docs/demand.md](docs/demand.md) |
|
||||
| 技术架构文档 | [docs/tec.md](docs/tec.md) |
|
||||
| 功能清单 | [docs/funclist.md](docs/funclist.md) |
|
||||
| 新人环境搭建 / 分支原则 | [docs/新人环境搭建与配置文档.md](docs/新人环境搭建与配置文档.md) |
|
||||
| 发布流程(dev→test→prod) | [docs/release_workflow.md](docs/release_workflow.md) · [docs/convention/开发标准流程.md](docs/convention/开发标准流程.md) |
|
||||
| 提交规范 | [docs/convention/COMMIT_CONVENTION.md](docs/convention/COMMIT_CONVENTION.md) |
|
||||
| Git Hooks | [docs/GIT_HOOKS.md](docs/GIT_HOOKS.md) |
|
||||
| 环境变量 | [docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md) · [docs/convention/环境变量规则.md](docs/convention/环境变量规则.md) |
|
||||
| 知识库部署 | [docs/knowledge_base_runtime_deploy.md](docs/knowledge_base_runtime_deploy.md) |
|
||||
| Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) |
|
||||
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
|
||||
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
|
||||
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
|
||||
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
|
||||
@@ -1,423 +0,0 @@
|
||||
# 文档清洗系统对外接口文档
|
||||
|
||||
版本:`v1`
|
||||
|
||||
适用对象:需要根据 Dify 文档信息反查文档清洗系统中的本地原文件,并获取原文件下载地址的外部系统。
|
||||
|
||||
## 1. 接入目标
|
||||
|
||||
外部系统通常已经从 Dify 拿到了某条知识库文档的以下信息:
|
||||
|
||||
- `dataset_id`
|
||||
- `remote_document_id`
|
||||
|
||||
其中:
|
||||
|
||||
- `dataset_id` = Dify 知识库 id
|
||||
- `remote_document_id` = Dify 文档 id
|
||||
- `remote_document_id` 应从 Dify 文档接口返回的 `id` 获取,不是 batch id
|
||||
|
||||
外部系统可使用本文档提供的接口,反查这条 Dify 文档在文档清洗系统中的本地映射关系,并获取原文件下载地址。
|
||||
|
||||
## 2. 接入原则
|
||||
|
||||
- 外部系统应由服务端调用查询接口,不要在前端浏览器中保存 `INTEGRATION_API_KEY`。
|
||||
- 查询接口需要鉴权。
|
||||
- 文件下载地址为短期签名链接,前端可直接打开,不需要再附带鉴权 key。
|
||||
- 下载链接过期后,应重新调用查询接口获取新的下载链接。
|
||||
|
||||
## 3. 基础信息
|
||||
|
||||
- Base URL:`http://192.168.100.230:8891`
|
||||
- 鉴权方式:HTTP Header
|
||||
- Header 名称:`X-Integration-Key`
|
||||
|
||||
请求示例:
|
||||
|
||||
```http
|
||||
X-Integration-Key: <平台分配的对接密钥>
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- 该 key 由文档清洗系统平台方提供。
|
||||
- 外部系统请将该 key 保存在自身服务端配置中,不要下发到前端页面。
|
||||
|
||||
## 4. 推荐对接流程
|
||||
|
||||
### 4.1 外部系统后端流程
|
||||
|
||||
1. 从 Dify 获取目标文档的:
|
||||
- `dataset_id`
|
||||
- `remote_document_id`
|
||||
2. 调用文档清洗系统查询接口:
|
||||
- `GET /api/integration/dify-file`
|
||||
3. 解析返回结果,读取:
|
||||
- 文件名
|
||||
- 所属知识库
|
||||
- 所属部门
|
||||
- 原文件下载地址
|
||||
4. 将需要展示的字段返回给自身前端页面。
|
||||
5. 前端用户点击下载时,直接打开 `source_download_url`。
|
||||
|
||||
### 4.2 外部系统前端流程
|
||||
|
||||
1. 调用外部系统自己的后端接口。
|
||||
2. 展示外部系统后端返回的文件信息。
|
||||
3. 用户点击“下载原文件”时,直接访问 `source_download_url`。
|
||||
4. 如果下载失败且提示链接失效,由外部系统后端重新查询一次并返回新链接。
|
||||
|
||||
## 5. 核心接口:按 Dify 文档反查本地文件
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/dify-file`
|
||||
|
||||
### 5.1 请求参数
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `dataset_id` | `string` | 是 | Dify 知识库 id |
|
||||
| `remote_document_id` | `string` | 是 | Dify 文档 id,应取自 Dify 文档接口返回的 `id` |
|
||||
|
||||
### 5.2 请求头
|
||||
|
||||
```http
|
||||
X-Integration-Key: <平台分配的对接密钥>
|
||||
```
|
||||
|
||||
### 5.3 请求示例
|
||||
|
||||
```bash
|
||||
curl -H "X-Integration-Key: YOUR_KEY" \
|
||||
"http://192.168.100.230:8891/api/integration/dify-file?dataset_id=7a9f158c-90f5-478a-8956-2732c72a7546&remote_document_id=abcd1234"
|
||||
```
|
||||
|
||||
### 5.4 成功响应示例
|
||||
|
||||
```json
|
||||
{
|
||||
"queried_at": "2026-04-01T12:00:00+08:00",
|
||||
"document_id": 14,
|
||||
"knowledge_base": {
|
||||
"id": 3,
|
||||
"name": "03 质量",
|
||||
"department_id": 2,
|
||||
"department_name": "质量部",
|
||||
"dify_dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546"
|
||||
},
|
||||
"title": "假期控制程序1",
|
||||
"source_filename": "假期控制程序1.doc",
|
||||
"source_ext": ".doc",
|
||||
"file_name": "假期控制程序1.doc",
|
||||
"version_id": 22,
|
||||
"version_no": 1,
|
||||
"convert_status": "success",
|
||||
"sync_status": "synced",
|
||||
"uploaded_at": "2026-04-01T11:32:10+08:00",
|
||||
"converted_at": "2026-04-01T11:33:05+08:00",
|
||||
"download_url_expires_at": "2026-04-01T12:15:00+08:00",
|
||||
"source_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx",
|
||||
"markdown_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=md&token=yyyyy",
|
||||
"markdown_download_url_expires_at": "2026-04-01T12:15:00+08:00",
|
||||
"markdown_public_url": "http://192.168.100.230:8891/storage/markdown/group_0003/document_000014/v001/document.md",
|
||||
"dify": {
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "abcd1234",
|
||||
"status": "synced",
|
||||
"last_indexing_status": "completed",
|
||||
"last_synced_at": "2026-04-01T11:34:20+08:00"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 6. 核心接口:批量按 Dify 文档反查本地文件
|
||||
|
||||
- 方法:`POST`
|
||||
- 路径:`/api/integration/dify-files/resolve`
|
||||
|
||||
### 6.1 请求头
|
||||
|
||||
```http
|
||||
X-Integration-Key: <平台分配的对接密钥>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
### 6.2 请求体
|
||||
|
||||
```json
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "abcd1234"
|
||||
},
|
||||
{
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "efgh5678"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `items` 为待查询列表。
|
||||
- 建议每次批量查询控制在 `100` 条以内。
|
||||
- 返回结果会按请求里的输入顺序返回。
|
||||
- `remote_document_id` 应取自 Dify 文档接口返回的 `id`,不是 batch id。
|
||||
|
||||
### 6.3 请求示例
|
||||
|
||||
```bash
|
||||
curl -X POST \
|
||||
-H "X-Integration-Key: YOUR_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"items\":[{\"dataset_id\":\"7a9f158c-90f5-478a-8956-2732c72a7546\",\"remote_document_id\":\"abcd1234\"},{\"dataset_id\":\"7a9f158c-90f5-478a-8956-2732c72a7546\",\"remote_document_id\":\"efgh5678\"}]}" \
|
||||
"http://192.168.100.230:8891/api/integration/dify-files/resolve"
|
||||
```
|
||||
|
||||
### 6.4 成功响应示例
|
||||
|
||||
```json
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"request": {
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "abcd1234"
|
||||
},
|
||||
"found": true,
|
||||
"document": {
|
||||
"document_id": 14,
|
||||
"source_filename": "假期控制程序1.doc",
|
||||
"source_download_url": "http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx",
|
||||
"knowledge_base": {
|
||||
"id": 3,
|
||||
"name": "03 质量",
|
||||
"department_id": 2,
|
||||
"department_name": "质量部",
|
||||
"dify_dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546"
|
||||
},
|
||||
"dify": {
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "abcd1234"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": {
|
||||
"dataset_id": "7a9f158c-90f5-478a-8956-2732c72a7546",
|
||||
"remote_document_id": "efgh5678"
|
||||
},
|
||||
"found": false,
|
||||
"document": null
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### 6.5 返回说明
|
||||
|
||||
- `request`
|
||||
- 原样回显本次输入的查询条件
|
||||
- `found`
|
||||
- 是否命中文档清洗系统中的本地映射
|
||||
- `document`
|
||||
- 命中时返回完整文档信息
|
||||
- 未命中时返回 `null`
|
||||
|
||||
## 6.6 版本映射说明
|
||||
|
||||
- 反查接口返回的是“命中的同步版本”,不是盲目返回当前最新版本。
|
||||
- 如果同一文档本地后来又上传了新版本,但新版本尚未同步到 Dify,接口仍会返回旧的已同步版本。
|
||||
- 如果某条文档从未同步到 Dify,则不会存在可用的 `remote_document_id` 映射。
|
||||
|
||||
## 7. 返回字段说明
|
||||
|
||||
### 7.1 顶层字段
|
||||
|
||||
| 字段名 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `queried_at` | `string` | 本次查询结果生成时间 |
|
||||
| `document_id` | `integer` | 文档清洗系统内部文档 id |
|
||||
| `title` | `string` | 文档清洗系统内部文档标题 |
|
||||
| `source_filename` | `string` | 原始上传文件名 |
|
||||
| `source_ext` | `string` | 原文件扩展名 |
|
||||
| `file_name` | `string` | 与 `source_filename` 相同,便于统一读取 |
|
||||
| `version_id` | `integer` | 当前版本 id |
|
||||
| `version_no` | `integer` | 当前版本号 |
|
||||
| `convert_status` | `string` | 转换状态,如 `queued` `running` `success` `failed` |
|
||||
| `sync_status` | `string` | 同步状态,如 `unsynced` `syncing` `synced` `sync_failed` |
|
||||
| `uploaded_at` | `string` | 原文件上传时间 |
|
||||
| `converted_at` | `string` | Markdown 转换完成时间 |
|
||||
| `download_url_expires_at` | `string` | 原文件下载链接过期时间 |
|
||||
| `source_download_url` | `string` | 原文件签名下载链接 |
|
||||
| `markdown_download_url` | `string` | Markdown 签名下载链接 |
|
||||
| `markdown_download_url_expires_at` | `string` | Markdown 下载链接过期时间 |
|
||||
| `markdown_public_url` | `string` | Markdown 在本系统内的访问地址 |
|
||||
| `knowledge_base` | `object` | 所属知识库信息 |
|
||||
| `dify` | `object` | Dify 映射信息 |
|
||||
|
||||
### 7.2 `knowledge_base` 字段说明
|
||||
|
||||
| 字段名 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `id` | `integer` | 文档清洗系统内部知识库 id |
|
||||
| `name` | `string` | 知识库名称 |
|
||||
| `department_id` | `integer` \| `null` | 所属部门 id |
|
||||
| `department_name` | `string` \| `null` | 所属部门名称 |
|
||||
| `dify_dataset_id` | `string` \| `null` | 该知识库在 Dify 对应的 dataset id |
|
||||
|
||||
### 7.3 `dify` 字段说明
|
||||
|
||||
| 字段名 | 类型 | 说明 |
|
||||
|---|---|---|
|
||||
| `dataset_id` | `string` | Dify 知识库 id |
|
||||
| `remote_document_id` | `string` | Dify 文档 id |
|
||||
| `status` | `string` | 本地记录的最近同步状态 |
|
||||
| `last_indexing_status` | `string` | Dify 最近索引状态 |
|
||||
| `last_synced_at` | `string` \| `null` | 最近同步完成时间 |
|
||||
|
||||
## 8. 下载说明
|
||||
|
||||
### 8.1 下载接口
|
||||
|
||||
外部系统通常不需要自己拼下载接口,直接使用查询结果中的:
|
||||
|
||||
- `source_download_url`
|
||||
- `markdown_download_url`
|
||||
|
||||
即可。
|
||||
|
||||
### 8.2 下载接口格式
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/download`
|
||||
|
||||
请求参数:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|---|---|---|---|
|
||||
| `version_id` | `integer` | 是 | 文档清洗系统内部版本 id |
|
||||
| `kind` | `string` | 是 | `source` 或 `md` |
|
||||
| `token` | `string` | 是 | 签名令牌 |
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
http://192.168.100.230:8891/api/integration/download?version_id=22&kind=source&token=xxxxx
|
||||
```
|
||||
|
||||
### 8.3 下载接口说明
|
||||
|
||||
- 下载接口不需要再附带 `X-Integration-Key`。
|
||||
- 这是一个短期签名链接,可直接在浏览器打开。
|
||||
- 链接过期后,请重新调用查询接口获取新的下载链接。
|
||||
|
||||
## 9. 可选查询接口
|
||||
|
||||
如果外部系统不是从 Dify 文档开始反查,也可使用以下接口。
|
||||
|
||||
### 9.1 获取知识库列表
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/knowledge-bases`
|
||||
|
||||
查询参数:
|
||||
|
||||
| 参数名 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `department_id` | 否 | 按部门筛选 |
|
||||
| `q` | 否 | 按知识库名称模糊搜索 |
|
||||
|
||||
请求示例:
|
||||
|
||||
```bash
|
||||
curl -H "X-Integration-Key: YOUR_KEY" \
|
||||
"http://192.168.100.230:8891/api/integration/knowledge-bases"
|
||||
```
|
||||
|
||||
### 9.2 获取文件列表
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/files`
|
||||
|
||||
查询参数:
|
||||
|
||||
| 参数名 | 必填 | 说明 |
|
||||
|---|---|---|
|
||||
| `knowledge_base_id` | 否 | 按知识库筛选 |
|
||||
| `department_id` | 否 | 按部门筛选 |
|
||||
| `file_name` | 否 | 按文件名或标题模糊搜索 |
|
||||
|
||||
请求示例:
|
||||
|
||||
```bash
|
||||
curl -H "X-Integration-Key: YOUR_KEY" \
|
||||
"http://192.168.100.230:8891/api/integration/files?knowledge_base_id=3"
|
||||
```
|
||||
|
||||
### 9.3 获取单个文件详情
|
||||
|
||||
- 方法:`GET`
|
||||
- 路径:`/api/integration/files/{file_id}`
|
||||
|
||||
请求示例:
|
||||
|
||||
```bash
|
||||
curl -H "X-Integration-Key: YOUR_KEY" \
|
||||
"http://192.168.100.230:8891/api/integration/files/14"
|
||||
```
|
||||
|
||||
## 10. 状态码说明
|
||||
|
||||
### 10.1 查询接口
|
||||
|
||||
| 状态码 | 说明 |
|
||||
|---|---|
|
||||
| `200` | 查询成功 |
|
||||
| `401` | 鉴权失败,`X-Integration-Key` 无效 |
|
||||
| `404` | 未找到对应的本地文件映射 |
|
||||
| `503` | 接口未配置完成,通常为平台未配置 `INTEGRATION_API_KEY` |
|
||||
|
||||
### 10.2 下载接口
|
||||
|
||||
| 状态码 | 说明 |
|
||||
|---|---|
|
||||
| `200` | 下载成功 |
|
||||
| `401` | 签名无效或已过期 |
|
||||
| `404` | 文件不存在 |
|
||||
| `409` | 请求 `md`,但 Markdown 尚未生成 |
|
||||
|
||||
## 11. 对接建议
|
||||
|
||||
- 外部系统前端不要直接调用查询接口。
|
||||
- 外部系统后端负责:
|
||||
- 保存 integration key
|
||||
- 调用查询接口
|
||||
- 将结果整理后返回给自身前端
|
||||
- 外部系统前端负责:
|
||||
- 展示文件信息
|
||||
- 使用 `source_download_url` 直接下载原文件
|
||||
|
||||
## 12. 最小接入流程
|
||||
|
||||
1. 外部系统从 Dify 获取:
|
||||
- `dataset_id`
|
||||
- `remote_document_id`
|
||||
2. 外部系统后端调用:
|
||||
- `GET /api/integration/dify-file?dataset_id=...&remote_document_id=...`
|
||||
3. 从返回结果中读取:
|
||||
- `source_filename`
|
||||
- `source_download_url`
|
||||
- `knowledge_base.name`
|
||||
- `knowledge_base.department_name`
|
||||
4. 将上述字段展示给用户。
|
||||
5. 用户点击下载时,直接打开 `source_download_url`。
|
||||
|
||||
## 13. 对接注意事项
|
||||
|
||||
- `source_download_url` 为短期签名链接,不是永久地址。
|
||||
- `source_download_url` 可直接用于下载,无需再次附加鉴权 key。
|
||||
- 若链接过期,外部系统应重新调用查询接口获取新链接。
|
||||
- 若返回 `404`,表示该 Dify 文档在文档清洗系统中没有本地文件映射。
|
||||
Vendored
+583
@@ -0,0 +1,583 @@
|
||||
import groovy.json.JsonOutput
|
||||
|
||||
// 企业微信群机器人部署通知(成功/失败/中止)。Webhook 完整 URL 存 Jenkins 凭据 WECOM_WEBHOOK_DEPLOY,勿写入 Git。
|
||||
// WeCom group-bot deploy notifications. Store webhook URL in Jenkins Secret text credential only.
|
||||
def notifyWecomDeploy(Map opts) {
|
||||
if ((env.DISABLE_DEPLOY_WECOM_NOTIFY ?: '').equalsIgnoreCase('true')) {
|
||||
echo '[WeCom] DISABLE_DEPLOY_WECOM_NOTIFY=true,跳过通知'
|
||||
return
|
||||
}
|
||||
|
||||
def credId = (opts.webhookCredId ?: env.WECOM_WEBHOOK_CRED ?: 'WECOM_WEBHOOK_DEPLOY').trim()
|
||||
def content = buildDeployNotifyMarkdown(opts)
|
||||
|
||||
try {
|
||||
withCredentials([string(credentialsId: credId, variable: 'WECOM_WEBHOOK_URL')]) {
|
||||
def webhookUrl = WECOM_WEBHOOK_URL?.trim()
|
||||
if (!webhookUrl) {
|
||||
echo "[WeCom] 凭据 ${credId} 为空,跳过通知"
|
||||
return
|
||||
}
|
||||
|
||||
def payload = [
|
||||
msgtype: 'markdown',
|
||||
markdown: [content: content.markdown],
|
||||
]
|
||||
writeFile(file: 'wecom-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
|
||||
|
||||
def httpCode = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
set +e
|
||||
code=$(curl -sS -o wecom-notify-response.txt -w "%{http_code}" \
|
||||
-X POST "$WECOM_WEBHOOK_URL" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @wecom-notify-payload.json)
|
||||
echo "[WeCom] HTTP ${code}" >&2
|
||||
cat wecom-notify-response.txt >&2 || true
|
||||
echo "${code}"
|
||||
'''
|
||||
).trim()
|
||||
|
||||
def resp = readFile('wecom-notify-response.txt').trim()
|
||||
if (httpCode == '200' && resp.contains('"errcode":0')) {
|
||||
echo '[WeCom] 通知已发送'
|
||||
} else {
|
||||
echo "[WeCom] 发送可能失败,HTTP=${httpCode},响应=${resp}"
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
echo "[WeCom] 通知发送异常(不影响构建结果): ${e.message}"
|
||||
}
|
||||
}
|
||||
|
||||
// PushPlus → 个人微信(方案3)。Token 存 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN,见 https://www.pushplus.plus/
|
||||
def buildDeployNotifyMarkdown(Map opts) {
|
||||
def envLabel = opts.envLabel ?: '部署环境'
|
||||
def host = opts.host ?: '-'
|
||||
def status = (opts.status ?: 'success').toString().toLowerCase()
|
||||
def isSuccess = status == 'success'
|
||||
def extraNote = (opts.extraNote ?: '').trim()
|
||||
def shortCommit = env.GIT_COMMIT ? env.GIT_COMMIT.take(8) : '-'
|
||||
def buildLink = env.BUILD_URL ?: '-'
|
||||
def title = isSuccess ? "✅ ${envLabel} 部署成功" : "❌ ${envLabel} 部署失败"
|
||||
def lines = [
|
||||
"## ${title}",
|
||||
"> **分支**: ${env.BRANCH_NAME ?: '-'}",
|
||||
"> **提交**: `${shortCommit}`",
|
||||
"> **目标主机**: ${host}",
|
||||
"> **构建**: [#${env.BUILD_NUMBER}](${buildLink})",
|
||||
"> **变更**: 前端=${env.FRONTEND_CHANGED ?: '-'} 后端=${env.BACKEND_CHANGED ?: '-'} 配置=${env.DEPLOY_CONFIG_CHANGED ?: '-'}",
|
||||
]
|
||||
if (env.FORCE_FULL_DEPLOY_USED == 'true') {
|
||||
lines << '> **备注**: 强制全量部署'
|
||||
}
|
||||
if (env.REMOTE_DRIFT_DETECTED == 'true') {
|
||||
lines << '> **备注**: 远端版本漂移触发部署'
|
||||
}
|
||||
if (env.ROLLBACK_IMAGE_TAG?.trim()) {
|
||||
lines << "> **备注**: 镜像回滚 → `${env.ROLLBACK_IMAGE_TAG.trim()}`(预构建模式,跳过 db upgrade)"
|
||||
}
|
||||
if (extraNote) {
|
||||
lines << "> **说明**: ${extraNote}"
|
||||
}
|
||||
if (!isSuccess) {
|
||||
lines << '> **处理**: 请打开 Jenkins 构建日志排查失败步骤'
|
||||
}
|
||||
return [title: title, markdown: lines.join('\n')]
|
||||
}
|
||||
|
||||
def notifyPushPlusDeploy(Map opts) {
|
||||
if ((env.DISABLE_DEPLOY_PUSHPLUS_NOTIFY ?: '').equalsIgnoreCase('true')) {
|
||||
echo '[PushPlus] DISABLE_DEPLOY_PUSHPLUS_NOTIFY=true,跳过通知'
|
||||
return
|
||||
}
|
||||
|
||||
def credId = (opts.tokenCredId ?: env.PUSHPLUS_TOKEN_CRED ?: 'PUSHPLUS_DEPLOY_TOKEN').trim()
|
||||
def content = buildDeployNotifyMarkdown(opts)
|
||||
|
||||
try {
|
||||
withCredentials([string(credentialsId: credId, variable: 'PUSHPLUS_TOKEN')]) {
|
||||
def token = PUSHPLUS_TOKEN?.trim()
|
||||
if (!token) {
|
||||
echo "[PushPlus] 凭据 ${credId} 为空,跳过通知"
|
||||
return
|
||||
}
|
||||
|
||||
def payload = [
|
||||
token: token,
|
||||
title: "[HxOps] ${content.title}",
|
||||
content: content.markdown,
|
||||
template: 'markdown',
|
||||
channel: 'wechat',
|
||||
]
|
||||
def topic = (env.PUSHPLUS_TOPIC ?: '').trim()
|
||||
if (topic) {
|
||||
payload.topic = topic
|
||||
}
|
||||
|
||||
writeFile(file: 'pushplus-notify-payload.json', encoding: 'UTF-8', text: JsonOutput.toJson(payload))
|
||||
|
||||
def httpCode = sh(
|
||||
returnStdout: true,
|
||||
script: '''
|
||||
set +e
|
||||
code=$(curl -sS -o pushplus-notify-response.txt -w "%{http_code}" \
|
||||
-X POST "https://www.pushplus.plus/send" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d @pushplus-notify-payload.json)
|
||||
echo "[PushPlus] HTTP ${code}" >&2
|
||||
cat pushplus-notify-response.txt >&2 || true
|
||||
echo "${code}"
|
||||
'''
|
||||
).trim()
|
||||
|
||||
def resp = readFile('pushplus-notify-response.txt').trim()
|
||||
if (httpCode == '200' && (resp.contains('"code":200') || resp.contains('"code": 200'))) {
|
||||
echo '[PushPlus] 微信通知已发送'
|
||||
} else {
|
||||
echo "[PushPlus] 发送可能失败,HTTP=${httpCode},响应=${resp}"
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
echo "[PushPlus] 通知发送异常(不影响构建结果): ${e.message}"
|
||||
}
|
||||
}
|
||||
|
||||
// 企业微信 + PushPlus 微信双通道
|
||||
def notifyDeployAll(Map opts) {
|
||||
notifyWecomDeploy(opts)
|
||||
// 暂时只发企业微信通知
|
||||
// notifyPushPlusDeploy(opts)
|
||||
}
|
||||
|
||||
pipeline {
|
||||
agent any
|
||||
|
||||
// 构建参数:首次在 Jenkinsfile 中加入后需至少跑一次构建,后续才能在「Build with Parameters」中看到 / Build params appear after first run
|
||||
parameters {
|
||||
// 跳过变更检测,强制进入部署阶段(等同前后端与部署配置均有变更)
|
||||
booleanParam(
|
||||
name: 'FORCE_FULL_DEPLOY',
|
||||
defaultValue: false,
|
||||
description: '勾选则跳过 Git diff(以及下方的远端校验);仍会执行生产人工确认(除非 Job 环境变量 SKIP_PROD_DEPLOY_INPUT=true)。'
|
||||
)
|
||||
// 本地判定「无变更」时,SSH 读远端部署目录的提交与分支,不一致则触发部署
|
||||
booleanParam(
|
||||
name: 'VERIFY_REMOTE_WHEN_NO_DIFF',
|
||||
defaultValue: false,
|
||||
description: '仅当本地 diff 判定无前后端/部署配置变更时生效:额外 SSH 到本分支对应目标机执行 git rev-parse / branch --show-current,与本次 GIT_COMMIT、BRANCH_NAME 比对,不一致则视为需要部署。'
|
||||
)
|
||||
// 生产镜像回滚:填写 Git 7 位短 hash 后缀(如 prod-e5b65d9),走 deploy_compose.sh 预构建模式
|
||||
string(
|
||||
name: 'ROLLBACK_IMAGE_TAG',
|
||||
defaultValue: '',
|
||||
description: '【仅生产】非空时回滚到该镜像 tag(hxops-frontend:<tag> / hxops-backend:<tag>)。示例:prod-e5b65d9(Git 短 hash 7 位)。不拉最新代码、不执行 db upgrade。留空为正常部署。'
|
||||
)
|
||||
}
|
||||
|
||||
options {
|
||||
// 打印时间戳,便于在 Jenkins 日志里定位耗时步骤 / Add timestamps to locate slow steps in Jenkins logs
|
||||
timestamps()
|
||||
// 禁止同一任务并发执行,避免部署相互覆盖 / Prevent concurrent runs to avoid deployment conflicts
|
||||
disableConcurrentBuilds()
|
||||
}
|
||||
|
||||
environment {
|
||||
// 环境服务器地址 / Environment hosts
|
||||
DEV_DEPLOY_HOST = '8.152.207.171'
|
||||
TEST_DEPLOY_HOST = '192.168.100.192'
|
||||
PROD_DEPLOY_HOST = '192.168.100.230'
|
||||
|
||||
// SSH 连接参数 / SSH connection settings
|
||||
DEV_SSH_USER = 'root'
|
||||
TEST_SSH_USER = 'lisq'
|
||||
PROD_SSH_USER = 'inspur'
|
||||
SSH_PORT = '22'
|
||||
|
||||
// 各环境统一部署目录 / Unified deploy root
|
||||
DEV_DEPLOY_ROOT = '/opt/hxops'
|
||||
TEST_DEPLOY_ROOT = '/home/lisq/ai/platform/hxops'
|
||||
PROD_DEPLOY_ROOT = '/data/ai-platform/hxops/'
|
||||
|
||||
// PushPlus 群组编码(一对多推送到个人微信);Token 仍用 Jenkins 凭据 PUSHPLUS_DEPLOY_TOKEN
|
||||
PUSHPLUS_TOPIC = 'hxops666'
|
||||
|
||||
// 生产机保留的可回滚镜像 tag 数量(deploy_compose.sh 按 ${ENV_NAME}-<commit> 清理旧 tag)
|
||||
IMAGE_TAG_RETAIN_COUNT = '10'
|
||||
}
|
||||
|
||||
stages {
|
||||
stage('Checkout') {
|
||||
steps {
|
||||
// 多分支流水线检出当前分支代码 / Checkout source from current branch in Multibranch Pipeline
|
||||
checkout scm
|
||||
echo "[Checkout] BRANCH_NAME=${env.BRANCH_NAME}, GIT_BRANCH=${env.GIT_BRANCH}, COMMIT=${env.GIT_COMMIT}"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Detect Changes') {
|
||||
steps {
|
||||
script {
|
||||
env.FORCE_FULL_DEPLOY_USED = 'false'
|
||||
env.REMOTE_DRIFT_DETECTED = 'false'
|
||||
env.REMOTE_VERIFY_SKIPPED = 'false'
|
||||
env.ROLLBACK_IMAGE_TAG = ''
|
||||
|
||||
def rollbackTag = params.ROLLBACK_IMAGE_TAG?.trim()
|
||||
if (rollbackTag) {
|
||||
env.ROLLBACK_IMAGE_TAG = rollbackTag
|
||||
env.FRONTEND_CHANGED = 'true'
|
||||
env.BACKEND_CHANGED = 'true'
|
||||
env.DEPLOY_CONFIG_CHANGED = 'false'
|
||||
echo "[Detect Changes] ROLLBACK_IMAGE_TAG=${rollbackTag},将使用预构建模式回滚(跳过 Git 更新与 db upgrade)"
|
||||
return
|
||||
}
|
||||
|
||||
// BRANCH_NAME 必须由 Multibranch Pipeline 提供 / BRANCH_NAME must be provided by Multibranch Pipeline
|
||||
def branchName = env.BRANCH_NAME?.trim()
|
||||
if (!branchName) {
|
||||
error('BRANCH_NAME is empty. Please run this as a Multibranch Pipeline job.')
|
||||
}
|
||||
|
||||
// 与 Deploy Prod 阶段一致:用于判断当前分支是否有对应部署目标(远端校验仅在这些分支上有意义)
|
||||
def extraBranches = (env.EXTRA_PROD_BRANCHES ?: '').split(',').collect { it.trim() }.findAll { it }
|
||||
def prodLikeBranches = (['prod', 'sophie', 'sophie-wecom'] + extraBranches).unique()
|
||||
|
||||
def getDeploySshTarget = { String b ->
|
||||
if (b == 'dev') {
|
||||
return [host: env.DEV_DEPLOY_HOST, user: env.DEV_SSH_USER, root: env.DEV_DEPLOY_ROOT, cred: 'SSH_DEV_DEPLOY']
|
||||
}
|
||||
if (b == 'test') {
|
||||
return [host: env.TEST_DEPLOY_HOST, user: env.TEST_SSH_USER, root: env.TEST_DEPLOY_ROOT, cred: 'SSH_TEST_DEPLOY']
|
||||
}
|
||||
if (prodLikeBranches.contains(b)) {
|
||||
return [host: env.PROD_DEPLOY_HOST, user: env.PROD_SSH_USER, root: env.PROD_DEPLOY_ROOT, cred: 'SSH_PROD_DEPLOY']
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// 强制全量:跳过 Git diff 与远端校验,避免「换分支同 SHA」或纯重发时被跳过
|
||||
if (params.FORCE_FULL_DEPLOY == true) {
|
||||
env.FRONTEND_CHANGED = 'true'
|
||||
env.BACKEND_CHANGED = 'true'
|
||||
env.DEPLOY_CONFIG_CHANGED = 'true'
|
||||
env.FORCE_FULL_DEPLOY_USED = 'true'
|
||||
echo "[Detect Changes] FORCE_FULL_DEPLOY=true,已跳过 Git diff 与远端校验"
|
||||
echo "[Detect Changes] FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
return
|
||||
}
|
||||
|
||||
// 以上次成功构建为差异基线 / Use previous successful commit as diff base
|
||||
def baseCommit = env.GIT_PREVIOUS_SUCCESSFUL_COMMIT?.trim()
|
||||
if (!baseCommit) {
|
||||
baseCommit = sh(returnStdout: true, script: 'git rev-parse HEAD^ 2>/dev/null || true').trim()
|
||||
}
|
||||
|
||||
List<String> changedFiles = []
|
||||
if (baseCommit) {
|
||||
changedFiles = sh(
|
||||
returnStdout: true,
|
||||
script: "git diff --name-only ${baseCommit} ${env.GIT_COMMIT}"
|
||||
).trim().split('\\n').findAll { it?.trim() }
|
||||
} else {
|
||||
// 首次构建默认按前后端都变更处理 / First build defaults to full-scope deployment
|
||||
changedFiles = ['frontend/', 'backend/']
|
||||
}
|
||||
|
||||
// 目录级变更识别:用于前后端增量构建 / Directory-level change detection for incremental builds
|
||||
def frontendChanged = changedFiles.any { it.startsWith('frontend/') }
|
||||
def backendChanged = changedFiles.any {
|
||||
it.startsWith('backend/') || it == 'docs/(表+字段).md'
|
||||
}
|
||||
def deployConfigChanged = changedFiles.any {
|
||||
it == 'docker-compose.yml' ||
|
||||
it == 'Jenkinsfile' ||
|
||||
it == '.dockerignore' ||
|
||||
it == 'scripts/deploy_compose.sh' ||
|
||||
it == 'scripts/healthcheck.sh' ||
|
||||
it == '.env.dev' ||
|
||||
it == '.env.test' ||
|
||||
it == '.env.prod'
|
||||
}
|
||||
|
||||
// 本地判定无变更且开启远端校验:SSH 读部署目录提交与分支,与本次构建对齐(需目标机允许只读 git 命令)
|
||||
def noLocalDiff = !frontendChanged && !backendChanged && !deployConfigChanged
|
||||
if (noLocalDiff && params.VERIFY_REMOTE_WHEN_NO_DIFF == true) {
|
||||
def target = getDeploySshTarget(branchName)
|
||||
if (!target) {
|
||||
env.REMOTE_VERIFY_SKIPPED = 'true'
|
||||
echo "[Detect Changes] VERIFY_REMOTE_WHEN_NO_DIFF=true,但当前分支无对应部署目标,跳过远端校验"
|
||||
} else {
|
||||
def expectedCommit = env.GIT_COMMIT?.trim()
|
||||
def remoteOut = ''
|
||||
sshagent(credentials: [target.cred]) {
|
||||
// 仅查询:不 fetch,不改变远端工作区;cd 失败或仓库异常会导致 SSH 步骤失败
|
||||
remoteOut = sh(
|
||||
returnStdout: true,
|
||||
script: """ssh -p ${env.SSH_PORT} -o StrictHostKeyChecking=no ${target.user}@${target.host} 'set -e; cd "${target.root}"; git rev-parse HEAD; git branch --show-current 2>/dev/null || true'"""
|
||||
).trim()
|
||||
}
|
||||
def remoteLines = remoteOut.split('\n') as List
|
||||
def remoteCommit = remoteLines ? remoteLines[0].trim() : ''
|
||||
def remoteBranch = remoteLines.size() > 1 ? remoteLines[1..-1].join('\n').trim() : ''
|
||||
|
||||
def commitMismatch = remoteCommit && expectedCommit && remoteCommit != expectedCommit
|
||||
def branchMismatch = remoteBranch && remoteBranch != branchName
|
||||
|
||||
echo "[Detect Changes] 远端校验 host=${target.host} root=${target.root}"
|
||||
echo "[Detect Changes] 远端 HEAD=${remoteCommit}, 期望=${expectedCommit}"
|
||||
echo "[Detect Changes] 远端分支=${remoteBranch ?: '(空或 detached)'}, 期望=${branchName}"
|
||||
|
||||
if (commitMismatch || branchMismatch) {
|
||||
frontendChanged = true
|
||||
backendChanged = true
|
||||
deployConfigChanged = true
|
||||
env.REMOTE_DRIFT_DETECTED = 'true'
|
||||
echo '[Detect Changes] 远端与本次构建不一致,已强制视为需要部署(前后端+部署配置标志均为 true)'
|
||||
} else {
|
||||
echo '[Detect Changes] 远端与本次构建一致(或无法解析分支名),仍按本地无变更处理'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
env.FRONTEND_CHANGED = frontendChanged ? 'true' : 'false'
|
||||
env.BACKEND_CHANGED = backendChanged ? 'true' : 'false'
|
||||
env.DEPLOY_CONFIG_CHANGED = deployConfigChanged ? 'true' : 'false'
|
||||
|
||||
echo "[Detect Changes] branch=${branchName}"
|
||||
echo "[Detect Changes] baseCommit=${baseCommit ?: 'none'}"
|
||||
echo "[Detect Changes] files=${changedFiles.join(', ')}"
|
||||
echo "[Detect Changes] FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// stage('Frontend Build (CI)') {
|
||||
// when {
|
||||
// expression { env.FRONTEND_CHANGED == 'true' }
|
||||
// }
|
||||
// steps {
|
||||
// echo '[Frontend Build] FRONTEND_CHANGED=true,容器内执行 npm ci && npm run build(与部署构建一致)'
|
||||
// sh '''
|
||||
// set -e
|
||||
// docker run --rm \
|
||||
// -v "${WORKSPACE}:/repo" \
|
||||
// -w /repo \
|
||||
// node:22-alpine sh -c "chmod +x scripts/ci_frontend_build.sh && ./scripts/ci_frontend_build.sh"
|
||||
// '''
|
||||
// }
|
||||
// }
|
||||
|
||||
stage('Deploy Dev') {
|
||||
when {
|
||||
expression {
|
||||
// dev 分支都部署到 dev 环境 / dev branches deploy to dev environment
|
||||
(env.BRANCH_NAME == 'dev') &&
|
||||
// 无变更不部署 / Skip deploy when no effective changes
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
echo "[Deploy Dev] start branch=${env.BRANCH_NAME} host=${env.DEV_DEPLOY_HOST}"
|
||||
|
||||
// 使用Jenkins中的SSH_DEV_DEPLOY私钥部署到开发服务器
|
||||
// Use SSH_DEV_DEPLOY credential to deploy to dev server
|
||||
sshagent(credentials: ['SSH_DEV_DEPLOY']) {
|
||||
sh """
|
||||
set -e
|
||||
# 远端更新代码并执行部署脚本 / Update repo on target host and run deploy script
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${DEV_SSH_USER}@${DEV_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${DEV_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
# 清掉工作区里对已跟踪文件的本地修改,否则改 deploy 脚本后 checkout 会报 “would be overwritten”
|
||||
git reset --hard HEAD
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
git reset --hard "origin/${BRANCH_NAME}"
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh dev "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
echo "[Deploy Dev] done"
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy Test') {
|
||||
when {
|
||||
expression {
|
||||
// test / env 分支均部署到 test 环境主机;代码与当前构建分支一致(不再强制 origin/test)
|
||||
(env.BRANCH_NAME == 'test' || env.BRANCH_NAME == 'env') &&
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
echo "[Deploy Test] start branch=${env.BRANCH_NAME} host=${env.TEST_DEPLOY_HOST}"
|
||||
|
||||
// 使用Jenkins中的SSH_TEST_DEPLOY私钥部署到测试服务器
|
||||
// Use SSH_TEST_DEPLOY credential to deploy to test server
|
||||
sshagent(credentials: ['SSH_TEST_DEPLOY']) {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${TEST_SSH_USER}@${TEST_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${TEST_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
git reset --hard HEAD
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
git reset --hard "origin/${BRANCH_NAME}"
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh test "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
echo "[Deploy Test] done"
|
||||
}
|
||||
post {
|
||||
success {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '测试环境',
|
||||
host: env.TEST_DEPLOY_HOST,
|
||||
status: 'success',
|
||||
)
|
||||
}
|
||||
}
|
||||
failure {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '测试环境',
|
||||
host: env.TEST_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
)
|
||||
}
|
||||
}
|
||||
aborted {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '测试环境',
|
||||
host: env.TEST_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
extraNote: '阶段已中止(可能为人工取消)',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Deploy Prod') {
|
||||
// 默认允许分支:prod、sophie。其它分支在 Job 环境变量设 EXTRA_PROD_BRANCHES=分支a,分支b
|
||||
// 临时免确认试跑:SKIP_PROD_DEPLOY_INPUT=true
|
||||
when {
|
||||
expression {
|
||||
def extra = (env.EXTRA_PROD_BRANCHES ?: '').split(',').collect { it.trim() }.findAll { it }
|
||||
def allowed = (['prod', 'sophie', 'sophie-wecom'] + extra).unique()
|
||||
allowed.contains(env.BRANCH_NAME) &&
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
def rollbackTag = env.ROLLBACK_IMAGE_TAG?.trim()
|
||||
// 临时免确认(仅无人使用的生产试跑):在 Job 环境变量设 SKIP_PROD_DEPLOY_INPUT=true;正式流程勿开启
|
||||
def skipInput = (env.SKIP_PROD_DEPLOY_INPUT ?: '').equalsIgnoreCase('true')
|
||||
if (!skipInput) {
|
||||
// 人工确认超时(分钟):超时未点「Proceed」构建将失败,避免任务永久挂在 input 上;可通过 Job 环境变量覆盖
|
||||
def inputTimeoutMin = 30
|
||||
try {
|
||||
def rawTm = (env.PROD_DEPLOY_INPUT_TIMEOUT_MINUTES ?: '30').trim()
|
||||
inputTimeoutMin = Integer.parseInt(rawTm)
|
||||
if (inputTimeoutMin <= 0) {
|
||||
inputTimeoutMin = 30
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
inputTimeoutMin = 30
|
||||
}
|
||||
echo "[Deploy Prod] 生产部署人工确认超时=${inputTimeoutMin} 分钟(环境变量 PROD_DEPLOY_INPUT_TIMEOUT_MINUTES 可覆盖)"
|
||||
def confirmMessage = rollbackTag ?
|
||||
"确认将生产回滚到镜像 tag ${rollbackTag} ?(预构建模式,不拉最新代码,不执行 db upgrade)" :
|
||||
"确认将分支 ${env.BRANCH_NAME} 部署到生产主机 ${env.PROD_DEPLOY_HOST} ?"
|
||||
timeout(time: inputTimeoutMin, unit: 'MINUTES') {
|
||||
input message: confirmMessage
|
||||
}
|
||||
} else {
|
||||
echo "[Deploy Prod] SKIP_PROD_DEPLOY_INPUT=true,已跳过人工确认"
|
||||
}
|
||||
|
||||
echo "[Deploy Prod] start branch=${env.BRANCH_NAME} host=${env.PROD_DEPLOY_HOST} rollbackTag=${rollbackTag ?: '(none)'}"
|
||||
|
||||
// 使用Jenkins中的SSH_PROD_DEPLOY私钥部署到生产服务器
|
||||
// Use SSH_PROD_DEPLOY credential to deploy to prod server
|
||||
sshagent(credentials: ['SSH_PROD_DEPLOY']) {
|
||||
if (rollbackTag) {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${PROD_SSH_USER}@${PROD_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${PROD_DEPLOY_ROOT}
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
./scripts/deploy_compose.sh prod "hxops-frontend:${rollbackTag}" "hxops-backend:${rollbackTag}" true true false true
|
||||
'
|
||||
"""
|
||||
} else {
|
||||
sh """
|
||||
set -e
|
||||
ssh -p ${SSH_PORT} -o StrictHostKeyChecking=no ${PROD_SSH_USER}@${PROD_DEPLOY_HOST} '
|
||||
set -e
|
||||
cd ${PROD_DEPLOY_ROOT}
|
||||
git fetch origin
|
||||
git reset --hard HEAD
|
||||
git checkout -B ${BRANCH_NAME} origin/${BRANCH_NAME}
|
||||
git reset --hard "origin/${BRANCH_NAME}"
|
||||
chmod +x scripts/deploy_compose.sh scripts/healthcheck.sh
|
||||
GIT_COMMIT=${env.GIT_COMMIT} IMAGE_TAG_RETAIN_COUNT=${env.IMAGE_TAG_RETAIN_COUNT} ./scripts/deploy_compose.sh prod "" "" ${FRONTEND_CHANGED} ${BACKEND_CHANGED} ${DEPLOY_CONFIG_CHANGED}
|
||||
'
|
||||
"""
|
||||
}
|
||||
}
|
||||
echo "[Deploy Prod] done"
|
||||
}
|
||||
}
|
||||
post {
|
||||
success {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '生产环境',
|
||||
host: env.PROD_DEPLOY_HOST,
|
||||
status: 'success',
|
||||
)
|
||||
}
|
||||
}
|
||||
failure {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '生产环境',
|
||||
host: env.PROD_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
)
|
||||
}
|
||||
}
|
||||
aborted {
|
||||
script {
|
||||
notifyDeployAll(
|
||||
envLabel: '生产环境',
|
||||
host: env.PROD_DEPLOY_HOST,
|
||||
status: 'failure',
|
||||
extraNote: '阶段已中止(可能为未确认生产部署或人工取消)',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
always {
|
||||
// 统一输出最终状态,便于回溯 / Print final flags for traceability
|
||||
echo "[Post] BRANCH_NAME=${env.BRANCH_NAME}, FRONTEND_CHANGED=${env.FRONTEND_CHANGED}, BACKEND_CHANGED=${env.BACKEND_CHANGED}, DEPLOY_CONFIG_CHANGED=${env.DEPLOY_CONFIG_CHANGED}"
|
||||
echo "[Post] FORCE_FULL_DEPLOY_USED=${env.FORCE_FULL_DEPLOY_USED ?: 'false'}, REMOTE_DRIFT_DETECTED=${env.REMOTE_DRIFT_DETECTED ?: 'false'}, REMOTE_VERIFY_SKIPPED=${env.REMOTE_VERIFY_SKIPPED ?: 'false'}, ROLLBACK_IMAGE_TAG=${env.ROLLBACK_IMAGE_TAG ?: ''}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,210 +1,48 @@
|
||||
# Document Cleaning
|
||||
|
||||
Independent internal web system for document cleaning, version tracking, batch download, and manual sync into Dify datasets.
|
||||
|
||||
## Stack
|
||||
|
||||
- Frontend: Vue 3, Vite, Tailwind, Uppy
|
||||
- Backend: FastAPI, SQLAlchemy, Alembic
|
||||
- Queue: RQ + Redis
|
||||
- Worker runtime: Python + LibreOffice
|
||||
- Database: SQLite or PostgreSQL (configurable)
|
||||
|
||||
## Project Layout
|
||||
|
||||
- `frontend/`: Vue workspace UI
|
||||
- `backend/`: FastAPI API, RQ worker tasks, vendored `edkb_system`
|
||||
- `project-governance/`: Codex skill governance, workflow docs, and audit snapshots
|
||||
- `docker-compose.yml`: full deployment stack for `192.168.100.230`
|
||||
|
||||
## Local Run
|
||||
|
||||
1. Copy `.env.example` to `.env` and fill in `DIFY_API_KEY`.
|
||||
2. Start services:
|
||||
|
||||
```bash
|
||||
docker compose up --build -d
|
||||
```
|
||||
|
||||
3. Open `http://localhost:8891`.
|
||||
|
||||
Default login comes from `.env`:
|
||||
|
||||
- username: `admin`
|
||||
- password: `admin123456`
|
||||
|
||||
## Local Direct Run Without Docker
|
||||
|
||||
Use this mode on a workstation that does not have Docker available.
|
||||
|
||||
1. Copy `backend/backend.env.example` to `backend/.env`.
|
||||
2. Choose a database mode in `backend/.env`:
|
||||
|
||||
```env
|
||||
# Option A: local SQLite
|
||||
DATABASE_BACKEND=sqlite
|
||||
DATABASE_URL=
|
||||
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
|
||||
|
||||
# Option B: local/shared PostgreSQL
|
||||
DATABASE_BACKEND=postgres
|
||||
DATABASE_URL=
|
||||
POSTGRES_DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db
|
||||
```
|
||||
|
||||
`DATABASE_URL` remains supported as a direct override. If it is set, it takes priority over `DATABASE_BACKEND`.
|
||||
|
||||
3. Keep `TASK_EXECUTION_MODE=sync` for local smoke tests.
|
||||
4. You can now use the project-local Python runtime under `python/`.
|
||||
|
||||
5. Start the backend:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m alembic upgrade head
|
||||
python -m uvicorn app.main:app --host 127.0.0.1 --port 8000
|
||||
```
|
||||
|
||||
6. Start the frontend in another terminal:
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm run dev -- --host 127.0.0.1 --port 5174
|
||||
```
|
||||
|
||||
7. Open `http://127.0.0.1:5174`.
|
||||
|
||||
Convenience scripts in the project root:
|
||||
|
||||
```powershell
|
||||
.\start-local-backend.ps1
|
||||
.\start-local-frontend.ps1
|
||||
.\start-local-dev.ps1
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `start-local-backend.ps1` runs Alembic first, then starts FastAPI.
|
||||
- `start-local-frontend.ps1` starts the Vite dev server.
|
||||
- `start-local-dev.ps1` starts both in background and writes logs to `tmp_run/`.
|
||||
|
||||
Notes:
|
||||
|
||||
- In local direct mode, queue tasks run inline through the API process.
|
||||
- Real Dify sync still requires a valid `DIFY_API_KEY`.
|
||||
- Server deployment should continue using `docker compose`.
|
||||
|
||||
## Production Deployment
|
||||
|
||||
The compose file is already configured for the planned entrypoint:
|
||||
|
||||
- `http://192.168.100.230:8891`
|
||||
|
||||
Deploy on the target server with:
|
||||
|
||||
```bash
|
||||
docker compose --env-file .env up --build -d
|
||||
```
|
||||
|
||||
Database selection is now configurable through `.env`:
|
||||
|
||||
```env
|
||||
# Option A: use the compose PostgreSQL service
|
||||
DATABASE_BACKEND=postgres
|
||||
DATABASE_URL=
|
||||
POSTGRES_DATABASE_URL=postgresql+psycopg://document_cleaning:document_cleaning@postgres:5432/document_cleaning
|
||||
|
||||
# Option B: use SQLite
|
||||
DATABASE_BACKEND=sqlite
|
||||
DATABASE_URL=
|
||||
SQLITE_DATABASE_URL=sqlite:///./document_cleaning.db
|
||||
|
||||
# Option C: explicit override
|
||||
DATABASE_URL=postgresql+psycopg://postgres:difyai123456@localhost:5432/doccleaning_db
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `DATABASE_URL` has the highest priority.
|
||||
- When running inside Docker, `localhost` points to the container itself. A host-level PostgreSQL service must use a reachable host name or IP instead of `localhost`.
|
||||
|
||||
Current deployment path on the server:
|
||||
|
||||
- `/home/inspur/tools/document-cleaning`
|
||||
|
||||
## Core Flows
|
||||
|
||||
- Upload one or many files into a group.
|
||||
- Deduplicate by `SHA-256` within the same group.
|
||||
- Create a new version when title matches but content changed.
|
||||
- Convert in the background through RQ workers.
|
||||
- Download original files or generated markdown individually or in bulk.
|
||||
- Manually sync selected documents to Dify.
|
||||
- Auto-create a Dify dataset on first sync for each group.
|
||||
|
||||
## Dify Integration
|
||||
|
||||
- Group name maps to one Dify dataset.
|
||||
- Sync uses cleaned markdown text, not the raw original file.
|
||||
- Existing logical documents are updated in Dify instead of duplicated.
|
||||
- Dataset defaults are managed in the admin console.
|
||||
|
||||
## External Integration API
|
||||
|
||||
Use this when another internal site needs to query knowledge-base/file relationships without direct database access.
|
||||
|
||||
1. Set `INTEGRATION_API_KEY` in `.env`.
|
||||
2. Optionally set `INTEGRATION_DOWNLOAD_SECRET` to a dedicated signing secret. If omitted, the app falls back to `JWT_SECRET`.
|
||||
3. Call the query API with `X-Integration-Key: <your key>`.
|
||||
|
||||
Recommended pattern:
|
||||
|
||||
- External site backend stores `INTEGRATION_API_KEY`
|
||||
- Backend calls this system's query API
|
||||
- Query response returns short-lived signed download URLs
|
||||
- External site frontend opens those signed URLs directly without carrying the integration key
|
||||
|
||||
Example endpoints:
|
||||
|
||||
- `GET /api/integration/knowledge-bases`
|
||||
- `GET /api/integration/files?knowledge_base_id=123`
|
||||
- `GET /api/integration/files?file_name=report`
|
||||
- `GET /api/integration/files/456`
|
||||
- `GET /api/integration/dify-file?dataset_id=<dify_dataset_id>&remote_document_id=<dify_document_id>`
|
||||
- `GET /api/integration/download?version_id=<local_version_id>&kind=source&token=<signed token>`
|
||||
- `GET /api/integration/download?version_id=<local_version_id>&kind=md&token=<signed token>`
|
||||
|
||||
## Dify Sync Throttling
|
||||
|
||||
To avoid overloading Dify when many files are pushed at once, sync jobs now support retry backoff and a short global cooldown gate.
|
||||
|
||||
Relevant `.env` knobs:
|
||||
|
||||
```env
|
||||
DIFY_SYNC_MAX_RETRIES=4
|
||||
DIFY_SYNC_RETRY_SCHEDULE=30,60,120,300
|
||||
DIFY_SYNC_COOLDOWN_SECONDS=60
|
||||
```
|
||||
|
||||
Behavior:
|
||||
|
||||
- Retryable Dify congestion errors such as `too many clients already` are not marked failed immediately.
|
||||
- The sync job is re-queued with backoff.
|
||||
- A short global cooldown prevents the next sync jobs from hammering Dify during the same congestion window.
|
||||
|
||||
## Tests
|
||||
|
||||
Backend:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python -m pytest tests -q
|
||||
```
|
||||
|
||||
Frontend:
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run build
|
||||
```
|
||||
# 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
|
||||
+68
-10
@@ -1,20 +1,78 @@
|
||||
FROM python:3.12-slim
|
||||
# syntax=docker/dockerfile:1.4
|
||||
ARG PYTHON_BASE_IMAGE=python:3.12-slim-bookworm
|
||||
FROM ${PYTHON_BASE_IMAGE}
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
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
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends libreoffice fonts-noto-cjk curl \
|
||||
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/*
|
||||
|
||||
COPY requirements.txt /app/requirements.txt
|
||||
RUN pip install --no-cache-dir -r /app/requirements.txt
|
||||
# Install Python dependencies
|
||||
COPY backend/requirements.txt backend/requirements-ocr.txt ./
|
||||
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
set -eux; \
|
||||
PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \
|
||||
if [ -n "${PIP_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \
|
||||
fi; \
|
||||
if [ -n "${PIP_EXTRA_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --extra-index-url ${PIP_EXTRA_INDEX_URL}"; \
|
||||
fi; \
|
||||
pip install $PIP_ARGS -r requirements.txt && \
|
||||
pip install $PIP_ARGS \
|
||||
"$(grep '^opencv-python-headless' requirements-ocr.txt)" && \
|
||||
pip install $PIP_ARGS --no-deps \
|
||||
"$(grep '^rapidocr-onnxruntime' requirements-ocr.txt)" && \
|
||||
pip install $PIP_ARGS \
|
||||
pyclipper Shapely six onnxruntime && \
|
||||
python -c "import cv2; from rapidocr_onnxruntime import RapidOCR; import networkx, openpyxl"
|
||||
|
||||
COPY . /app
|
||||
# Copy backend code and the Text2SQL schema required at runtime
|
||||
COPY backend/ .
|
||||
RUN mkdir -p /app/docs
|
||||
COPY docs/(表+字段).md /app/docs/(表+字段).md
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["sh", "-c", "alembic upgrade head && uvicorn app.main:app --host 0.0.0.0 --port 8000"]
|
||||
# Expose port 5000
|
||||
EXPOSE 5000
|
||||
|
||||
# Start Gunicorn
|
||||
# Using the config file we created earlier
|
||||
CMD ["gunicorn", "-c", "deploy/gunicorn_config.py", "run:app"]
|
||||
@@ -1,36 +0,0 @@
|
||||
[alembic]
|
||||
script_location = migrations
|
||||
sqlalchemy.url = sqlite:///./document_cleaning.db
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers = console
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
|
||||
+229
-1
@@ -1 +1,229 @@
|
||||
"""Document Cleaning backend package."""
|
||||
"""
|
||||
backend/app/__init__.py
|
||||
应用工厂:创建 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) # 允许跨域
|
||||
|
||||
# 注册 Blueprints
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.knowledge_base import knowledge_base_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.schedule_admin import schedule_admin_bp
|
||||
from app.api.workspace_schedule import workspace_schedule_bp
|
||||
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
|
||||
from app.api.workspace_file_check import workspace_file_check_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp
|
||||
from app.api.file_check_tools import file_check_bp
|
||||
from app.api.speech import speech_bp
|
||||
|
||||
# 聊天相关接口
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
# 管理员相关接口
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
# 普通用户可见的 Agent 列表接口
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
# 当前用户相关接口(首页、常见问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
# 知识库数据清洗模块接口
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
# 知识库外部集成接口(供外部系统按 Dify 映射反查源文件)
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
|
||||
# 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)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
from app.cli.faq_commands import init_app as init_faq_cli
|
||||
init_faq_cli(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
_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
|
||||
@@ -1 +1,52 @@
|
||||
from app.api import admin, auth, files, groups, integration, jobs
|
||||
"""
|
||||
backend/app/api/__init__.py
|
||||
|
||||
用途:集中注册所有 Blueprint(Wave 1 接入 create_app)。
|
||||
依赖:各 api 子包 blueprint。
|
||||
逻辑:替代 app/__init__.py 内 15 行散乱 register_blueprint。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Flask
|
||||
|
||||
|
||||
def register_blueprints(app: Flask) -> None:
|
||||
"""
|
||||
注册全部 HTTP Blueprint,保持对外 url_prefix 不变。
|
||||
核心逻辑:Wave 0 仍从既有单体模块 import;Wave 1+ 逐步切换至分包。
|
||||
Args:
|
||||
app: Flask 应用实例。
|
||||
"""
|
||||
# [STEP 1] 单体模块(Wave 3 前保持不变)
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.knowledge_base import knowledge_base_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.speech import speech_bp
|
||||
|
||||
# [STEP 2] 已分包骨架(re-export 旧模块,Wave 1 可切换 import 来源)
|
||||
from app.api.schedule import schedule_admin_bp
|
||||
from app.api.workspace import (
|
||||
workspace_file_check_bp,
|
||||
workspace_schedule_bp,
|
||||
workspace_shipping_notice_bp,
|
||||
)
|
||||
from app.api.tools import file_check_bp, shipping_notice_bp
|
||||
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||
+1805
-409
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,118 @@
|
||||
"""
|
||||
backend/app/api/agents.py
|
||||
文件用途:普通用户可见的 Agent 列表接口
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
||||
"""
|
||||
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():
|
||||
"""
|
||||
获取当前用户可见的 Agent 列表
|
||||
用途:Workspace 页面展示应用网格
|
||||
"""
|
||||
# 获取当前用户(目前固定为 admin 用户,用于演示)
|
||||
user: User = _get_current_user()
|
||||
|
||||
# 管理员:返回所有激活的 Agent
|
||||
if user.role == 'admin':
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url, Agent.extra_config)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
else:
|
||||
# 普通用户:仅返回多对多关系中已授权的 Agent
|
||||
agent_rows = [
|
||||
type('AgentRow', (), {
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url,
|
||||
'extra_config': a.extra_config,
|
||||
})()
|
||||
for a in user.agents
|
||||
if a.is_active
|
||||
]
|
||||
|
||||
# 序列化为前端所需字段
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
|
||||
@agents_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():
|
||||
"""
|
||||
获取公开的 Agent 列表 (无需登录)
|
||||
用途:登录页面展示
|
||||
"""
|
||||
# 返回所有激活的 Agent,包含基本信息
|
||||
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)
|
||||
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.models import User
|
||||
from app.schemas import LoginRequest, TokenResponse
|
||||
from app.security import create_access_token, verify_password
|
||||
from app.serializers import serialize_user
|
||||
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
def login(payload: LoginRequest, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.username == payload.username, User.is_active.is_(True)).first()
|
||||
if not user or not verify_password(payload.password, user.password_hash):
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
|
||||
token = create_access_token(user.username)
|
||||
return TokenResponse(access_token=token, user=serialize_user(user))
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,32 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.deps import accessible_department_ids, get_current_user
|
||||
from app.models import Department, Group, User
|
||||
from app.serializers import serialize_department
|
||||
|
||||
|
||||
router = APIRouter(prefix="/departments", tags=["departments"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_departments(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
department_ids = accessible_department_ids(db, user)
|
||||
group_counts = (
|
||||
db.query(Group.department_id.label("department_id"), func.count(Group.id).label("knowledge_base_count"))
|
||||
.group_by(Group.department_id)
|
||||
.subquery()
|
||||
)
|
||||
query = (
|
||||
db.query(Department, func.coalesce(group_counts.c.knowledge_base_count, 0).label("knowledge_base_count"))
|
||||
.outerjoin(group_counts, group_counts.c.department_id == Department.id)
|
||||
.order_by(Department.name.asc())
|
||||
)
|
||||
if department_ids is not None:
|
||||
query = query.filter(Department.id.in_(department_ids or [-1]))
|
||||
rows = query.all()
|
||||
return {"data": [serialize_department(item, knowledge_base_count=count) for item, count in rows]}
|
||||
@@ -0,0 +1,492 @@
|
||||
"""
|
||||
backend/app/api/file_check_tools.py
|
||||
|
||||
用途:文件检核 Chatflow 显式 HTTP Tool API。
|
||||
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
|
||||
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from io import BytesIO
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from sqlalchemy import text
|
||||
|
||||
from app import db
|
||||
from app.api.workspace_file_check import serialize_file_judgement
|
||||
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
from app.services.schedule.srm_service import _fetch_records
|
||||
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
|
||||
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||
|
||||
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||
_RUN_START_LOCK = threading.Lock()
|
||||
_TASK_LOCK_KEY_BASE = 8700000000
|
||||
|
||||
|
||||
def _tool_token_secret() -> str:
|
||||
return str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or current_app.config.get("SECRET_KEY")
|
||||
or "default-secret"
|
||||
).strip()
|
||||
|
||||
|
||||
def _decode_download_token(token: str | None) -> dict | None:
|
||||
normalized = str(token or "").strip()
|
||||
if not normalized:
|
||||
return None
|
||||
try:
|
||||
import jwt
|
||||
|
||||
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
|
||||
return payload if isinstance(payload, dict) else None
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||
return None
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
configured = str(
|
||||
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||
or current_app.config.get("INTEGRATION_API_KEY")
|
||||
or ""
|
||||
).strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if request.path.endswith("/excel") and _decode_download_token(request.args.get("token")):
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {
|
||||
"missing_auth",
|
||||
"invalid_auth",
|
||||
"task_not_found",
|
||||
"run_not_found",
|
||||
"excel_not_ready",
|
||||
"kb_sync_failed",
|
||||
"query_required",
|
||||
"kb_not_configured",
|
||||
"kb_group_not_found",
|
||||
"kb_dataset_not_bound",
|
||||
"dify_retrieve_failed",
|
||||
}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
if exc.code == "RESOURCE.NOT_FOUND":
|
||||
return message or "run_not_found"
|
||||
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||
return message or "invalid_request"
|
||||
if exc.code == "RESOURCE.CONFLICT":
|
||||
return message or "conflict"
|
||||
return exc.code
|
||||
|
||||
|
||||
@file_check_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
status = exc.http_status
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": _tool_error_code(exc),
|
||||
"message": exc.message,
|
||||
}), status
|
||||
|
||||
|
||||
def _public_base_url() -> str:
|
||||
return resolve_HXOPS_TOOLS_API_BASE()
|
||||
|
||||
|
||||
def _acquire_task_start_lock(task_id: int) -> None:
|
||||
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
|
||||
bind = db.session.get_bind()
|
||||
if bind.dialect.name != "postgresql":
|
||||
return
|
||||
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def _build_excel_download_url(run: ScheduleRun) -> str:
|
||||
import jwt
|
||||
|
||||
payload = {
|
||||
"scope": "file_check_excel",
|
||||
"run_id": run.id,
|
||||
"exp": int(time.time()) + 600,
|
||||
}
|
||||
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
|
||||
return f"{_public_base_url()}/api/file-check/tools/runs/{run.id}/excel?token={token}"
|
||||
|
||||
|
||||
@file_check_bp.before_request
|
||||
def _verify_tool_access():
|
||||
if request.path.endswith("/openapi.json"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _serialize_tool_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
return {
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"task_name": payload.get("schedule_name"),
|
||||
"status": payload["status"],
|
||||
"total_count": payload["total_count"],
|
||||
"success_count": payload["success_count"],
|
||||
"failed_count": payload["failed_count"],
|
||||
"skipped_count": payload["skipped_count"],
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
"error_message": payload.get("error_message"),
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": _build_excel_download_url(run) if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"enabled": bool(getattr(run.task, "kb_sync_enabled", False)) if run.task else bool(payload.get("kb_group_id")),
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
"group_id": payload.get("kb_group_id"),
|
||||
"document_id": payload.get("kb_document_id"),
|
||||
"document_version_id": payload.get("kb_document_version_id"),
|
||||
"sync_job_id": payload.get("kb_sync_job_id"),
|
||||
"error_message": payload.get("kb_sync_error"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) -> ScheduleTask:
|
||||
data = data or {}
|
||||
raw_task_id = task_id if task_id is not None else data.get("task_id")
|
||||
if raw_task_id in (None, "", 0, "0") and not str(data.get("task_no") or "").strip():
|
||||
raise ValidationError("task_id_required")
|
||||
try:
|
||||
normalized_task_id = int(raw_task_id) if raw_task_id not in (None, "", 0, "0") else None
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
task = db.session.get(ScheduleTask, normalized_task_id) if normalized_task_id is not None else None
|
||||
if not task:
|
||||
task_no = str(data.get("task_no") or "").strip()
|
||||
if task_no:
|
||||
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
|
||||
if not task:
|
||||
raise NotFoundError("task_not_found")
|
||||
return task
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks", methods=["GET"])
|
||||
def list_file_check_tasks():
|
||||
"""
|
||||
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
|
||||
"""
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
if raw_task_id is None:
|
||||
raise ValidationError("task_id_required")
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
latest = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
tasks = [{
|
||||
"task_id": task.id,
|
||||
"task_no": task.schedule_no,
|
||||
"name": task.name,
|
||||
"enabled": bool(task.enabled),
|
||||
"last_status": latest.status if latest else None,
|
||||
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
||||
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
||||
}]
|
||||
return jsonify({"ok": True, "tasks": tasks})
|
||||
|
||||
|
||||
def _normalize_bind_payload(data: dict | None) -> dict:
|
||||
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
|
||||
payload = dict(data or {})
|
||||
session_id = str(payload.get("hxops_session_id") or "").strip()
|
||||
if session_id:
|
||||
return payload
|
||||
conversation_id = str(payload.get("conversation_id") or "").strip()
|
||||
if not conversation_id:
|
||||
return payload
|
||||
from app.models import ChatSession
|
||||
|
||||
session = ChatSession.query.filter_by(session_id=conversation_id).first()
|
||||
if session:
|
||||
payload["hxops_session_id"] = conversation_id
|
||||
return payload
|
||||
|
||||
|
||||
def _prepare_bind_payload(data: dict | None) -> dict:
|
||||
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
|
||||
|
||||
payload = _normalize_bind_payload(data)
|
||||
inferred = infer_bind_context_for_run_request(payload)
|
||||
if inferred:
|
||||
payload = {**payload, **inferred}
|
||||
return payload
|
||||
|
||||
|
||||
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
|
||||
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
|
||||
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||
|
||||
merge_chat_log_bind_context(run, data)
|
||||
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||
if turn_id:
|
||||
attach_run_to_turn(turn_id, int(run.id))
|
||||
|
||||
|
||||
def _build_no_data_response(task: ScheduleTask) -> dict:
|
||||
"""无待检资料时直接返回提示,不创建批次也不绑定 run_id。"""
|
||||
return {
|
||||
"ok": False,
|
||||
"error_code": "no_data_to_check",
|
||||
"message": "目前没有资料需要检核",
|
||||
"task": {
|
||||
"task_id": task.id,
|
||||
"task_name": task.name,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||
"""
|
||||
启动前预检当前任务是否存在待检资料。
|
||||
|
||||
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
|
||||
避免创建空批次并向 ChatLog 回写 run_id。
|
||||
"""
|
||||
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
|
||||
return None
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg or not str(cfg.fetch_sql or "").strip():
|
||||
return None
|
||||
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
|
||||
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||
if rows:
|
||||
return None
|
||||
return _build_no_data_response(task)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
|
||||
def run_file_check():
|
||||
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
||||
perf_started = time.perf_counter()
|
||||
data = _prepare_bind_payload(request.get_json(silent=True) or {})
|
||||
task = _resolve_check_task(data)
|
||||
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
|
||||
lock_started = time.perf_counter()
|
||||
with _RUN_START_LOCK:
|
||||
_acquire_task_start_lock(task.id)
|
||||
existing = (
|
||||
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
|
||||
.order_by(ScheduleRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
_record_run_bind(existing, data)
|
||||
db.session.commit()
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
existing.id,
|
||||
)
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": "check_running",
|
||||
"message": "该检核任务正在执行中,请稍后查询结果",
|
||||
"run": _serialize_tool_run(existing),
|
||||
})
|
||||
|
||||
no_data_response = _precheck_no_data(task)
|
||||
if no_data_response:
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
task.id,
|
||||
)
|
||||
return jsonify(no_data_response)
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
schedule_task_id=task.id,
|
||||
trigger_type="dify_chatflow",
|
||||
started_at=datetime.utcnow(),
|
||||
status="running",
|
||||
api_request_json={
|
||||
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
||||
"conversation_id": data.get("conversation_id"),
|
||||
"hxops_session_id": data.get("hxops_session_id"),
|
||||
"hxops_turn_id": data.get("hxops_turn_id"),
|
||||
"user_message": data.get("user_message"),
|
||||
},
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
_record_run_bind(run, data)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
task_id = task.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
|
||||
except Exception as exc:
|
||||
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == "running":
|
||||
r.status = "failed"
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
|
||||
db.session.refresh(run)
|
||||
lock_ms = int((time.perf_counter() - lock_started) * 1000)
|
||||
total_ms = int((time.perf_counter() - perf_started) * 1000)
|
||||
current_app.logger.info(
|
||||
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
|
||||
resolve_ms,
|
||||
lock_ms,
|
||||
total_ms,
|
||||
run_id,
|
||||
)
|
||||
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
||||
def get_file_check_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs", methods=["GET"])
|
||||
def list_file_check_runs():
|
||||
raw_task_id = request.args.get("task_id", type=int)
|
||||
raw_limit = request.args.get("limit", default=20, type=int)
|
||||
limit = max(1, min(int(raw_limit or 20), 100))
|
||||
if raw_task_id is not None:
|
||||
task = _resolve_check_task(task_id=raw_task_id)
|
||||
query = ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
||||
else:
|
||||
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
|
||||
runs = [_serialize_tool_run(row) for row in rows]
|
||||
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def download_file_check_run_excel(run_id: int):
|
||||
token_payload = _decode_download_token(request.args.get("token"))
|
||||
if token_payload:
|
||||
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
|
||||
raise UnauthorizedError("Unauthorized")
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not run.excel_file_data:
|
||||
raise ConflictError("excel_not_ready")
|
||||
filename = run.excel_file_name or f"{run.run_no}.xlsx"
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=filename,
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
||||
def get_latest_file_check_run(task_id: int):
|
||||
task = _resolve_check_task(task_id=task_id)
|
||||
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/history/search", methods=["POST"])
|
||||
def search_file_check_history():
|
||||
"""
|
||||
检索已入库的历史检核报告片段;按 task_id 解析 ScheduleTask → KbGroup → Dify Dataset。
|
||||
|
||||
核心逻辑:Chatflow history_report_query 分支调用;task_id 来自 HXOPS 注入的 Start 变量。
|
||||
"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_task_id = data.get("task_id")
|
||||
try:
|
||||
task_id = int(raw_task_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError("task_id_invalid")
|
||||
if task_id <= 0:
|
||||
raise ValidationError("task_id_invalid")
|
||||
|
||||
from app.services.file_check_tools.history_search_service import search_file_check_history as run_history_search
|
||||
|
||||
result = run_history_search(
|
||||
task_id=task_id,
|
||||
query=str(data.get("query") or ""),
|
||||
top_k=data.get("top_k"),
|
||||
score_threshold=data.get("score_threshold"),
|
||||
)
|
||||
return jsonify({"ok": True, **result})
|
||||
|
||||
|
||||
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def file_check_openapi_spec():
|
||||
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||
@@ -1,490 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import uuid
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.deps import accessible_group_ids, ensure_group_access, get_current_user
|
||||
from app.models import Document, DocumentVersion, DifySyncRecord, Group, Job, User
|
||||
from app.schemas import BatchDownloadRequest, BatchSyncRequest
|
||||
from app.serializers import current_version, serialize_document, serialize_job, serialize_version
|
||||
from app.services.queue_service import get_queue
|
||||
from app.services.storage_service import build_zip, remove_path_if_exists, sha256_file, version_dir
|
||||
|
||||
|
||||
router = APIRouter(prefix="/files", tags=["files"])
|
||||
settings = get_settings()
|
||||
MAX_BATCH_UPLOAD_FILES = 500
|
||||
|
||||
|
||||
def _group_scope_filter(db: Session, user: User):
|
||||
group_ids = accessible_group_ids(db, user)
|
||||
return None if group_ids is None else (group_ids or [-1])
|
||||
|
||||
|
||||
def _get_document_for_user(db: Session, user: User, file_id: int) -> Document | None:
|
||||
query = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Document.id == file_id, Document.is_deleted.is_(False))
|
||||
)
|
||||
group_ids = _group_scope_filter(db, user)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Document.group_id.in_(group_ids))
|
||||
return query.first()
|
||||
|
||||
|
||||
def _create_job(
|
||||
db: Session,
|
||||
*,
|
||||
job_type: str,
|
||||
created_by_id: int,
|
||||
group_id: int,
|
||||
document_id: int,
|
||||
version_id: int,
|
||||
payload: dict | None = None,
|
||||
) -> Job:
|
||||
job = Job(
|
||||
id=str(uuid.uuid4()),
|
||||
job_type=job_type,
|
||||
status="queued",
|
||||
group_id=group_id,
|
||||
document_id=document_id,
|
||||
version_id=version_id,
|
||||
created_by_id=created_by_id,
|
||||
payload=payload or {},
|
||||
)
|
||||
db.add(job)
|
||||
db.commit()
|
||||
db.refresh(job)
|
||||
return job
|
||||
|
||||
|
||||
def _enqueue(job: Job, task_name: str, version_id: int, db: Session) -> Job:
|
||||
return _enqueue_args(job, task_name, db, version_id)
|
||||
|
||||
|
||||
def _enqueue_args(job: Job, task_name: str, db: Session, *task_args) -> Job:
|
||||
queue = get_queue()
|
||||
rq_job = queue.enqueue(task_name, job.id, *task_args)
|
||||
job.queue_job_id = rq_job.id
|
||||
db.commit()
|
||||
db.refresh(job)
|
||||
return job
|
||||
|
||||
|
||||
def _resolve_storage_target(path_value: str | None, *, parent: bool = False) -> Path | None:
|
||||
if not path_value:
|
||||
return None
|
||||
raw_target = Path(path_value)
|
||||
data_root = settings.data_root.resolve(strict=False)
|
||||
if raw_target.is_absolute():
|
||||
target = raw_target
|
||||
else:
|
||||
resolved_raw = raw_target.resolve(strict=False)
|
||||
target = resolved_raw if resolved_raw.is_relative_to(data_root) else settings.data_root / raw_target
|
||||
if parent:
|
||||
target = target.parent
|
||||
resolved = target.resolve(strict=False)
|
||||
if not resolved.is_relative_to(data_root):
|
||||
return None
|
||||
return resolved
|
||||
|
||||
|
||||
def _cleanup_document_storage(document: Document) -> None:
|
||||
targets: set[Path] = set()
|
||||
for version in document.versions:
|
||||
for candidate in (
|
||||
_resolve_storage_target(version.source_path, parent=True),
|
||||
_resolve_storage_target(version.md_path, parent=True),
|
||||
_resolve_storage_target(version.asset_dir),
|
||||
):
|
||||
if candidate is not None:
|
||||
targets.add(candidate)
|
||||
|
||||
for target in sorted(targets, key=lambda item: len(item.parts), reverse=True):
|
||||
remove_path_if_exists(target)
|
||||
|
||||
|
||||
@router.post("/upload")
|
||||
async def upload_files(
|
||||
group_id: int = Form(...),
|
||||
files: list[UploadFile] = File(default_factory=list),
|
||||
file: UploadFile | None = File(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
ensure_group_access(db, user, group_id)
|
||||
group = db.query(Group).filter(Group.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found.")
|
||||
|
||||
incoming = list(files)
|
||||
if file is not None:
|
||||
incoming.append(file)
|
||||
if not incoming:
|
||||
raise HTTPException(status_code=400, detail="No files uploaded.")
|
||||
if len(incoming) > MAX_BATCH_UPLOAD_FILES:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Batch upload accepts at most {MAX_BATCH_UPLOAD_FILES} files at a time.",
|
||||
)
|
||||
|
||||
created: list[dict] = []
|
||||
duplicates: list[dict] = []
|
||||
|
||||
for upload in incoming:
|
||||
tmp_dir = settings.data_root / "tmp" / "uploads"
|
||||
tmp_dir.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = tmp_dir / f"{uuid.uuid4()}_{Path(upload.filename).name}"
|
||||
with tmp_path.open("wb") as handle:
|
||||
while True:
|
||||
chunk = await upload.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
handle.write(chunk)
|
||||
digest = sha256_file(tmp_path)
|
||||
ext = Path(upload.filename).suffix.lower()
|
||||
title = Path(upload.filename).stem
|
||||
|
||||
duplicate_version = (
|
||||
db.query(DocumentVersion)
|
||||
.join(Document, Document.id == DocumentVersion.document_id)
|
||||
.filter(
|
||||
Document.group_id == group.id,
|
||||
Document.is_deleted.is_(False),
|
||||
DocumentVersion.source_sha256 == digest,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if duplicate_version:
|
||||
duplicates.append(
|
||||
{
|
||||
"filename": upload.filename,
|
||||
"document_id": duplicate_version.document_id,
|
||||
"version_id": duplicate_version.id,
|
||||
"reason": "same_sha256_in_group",
|
||||
}
|
||||
)
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
continue
|
||||
|
||||
document = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions))
|
||||
.filter(
|
||||
Document.group_id == group.id,
|
||||
func.lower(Document.title) == title.lower(),
|
||||
Document.is_deleted.is_(False),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if document is None:
|
||||
document = Document(group_id=group.id, title=title, created_by_id=user.id, is_deleted=False)
|
||||
db.add(document)
|
||||
db.commit()
|
||||
db.refresh(document)
|
||||
version_no = 1
|
||||
else:
|
||||
for item in document.versions:
|
||||
if item.is_current:
|
||||
item.is_current = False
|
||||
db.commit()
|
||||
version_no = (document.versions[0].version_no + 1) if document.versions else 1
|
||||
|
||||
sync_status = "unsynced"
|
||||
prior_sync = (
|
||||
db.query(DifySyncRecord)
|
||||
.join(DocumentVersion, DifySyncRecord.version_id == DocumentVersion.id)
|
||||
.filter(DocumentVersion.document_id == document.id, DifySyncRecord.status == "synced")
|
||||
.first()
|
||||
)
|
||||
if prior_sync:
|
||||
sync_status = "stale"
|
||||
|
||||
source_dir = version_dir("original", group.id, document.id, version_no)
|
||||
source_dir.mkdir(parents=True, exist_ok=True)
|
||||
final_source = source_dir / Path(upload.filename).name
|
||||
shutil.move(str(tmp_path), str(final_source))
|
||||
|
||||
version = DocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=version_no,
|
||||
is_current=True,
|
||||
source_filename=Path(upload.filename).name,
|
||||
source_ext=ext,
|
||||
source_path=str(final_source),
|
||||
source_sha256=digest,
|
||||
file_size=final_source.stat().st_size,
|
||||
uploader_id=user.id,
|
||||
convert_status="queued",
|
||||
sync_status=sync_status,
|
||||
)
|
||||
db.add(version)
|
||||
db.commit()
|
||||
db.refresh(version)
|
||||
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="convert",
|
||||
created_by_id=user.id,
|
||||
group_id=group.id,
|
||||
document_id=document.id,
|
||||
version_id=version.id,
|
||||
payload={"filename": upload.filename},
|
||||
)
|
||||
_enqueue(job, "app.tasks.run_convert_job", version.id, db)
|
||||
created.append(
|
||||
{
|
||||
"document_id": document.id,
|
||||
"version_id": version.id,
|
||||
"job": serialize_job(job),
|
||||
}
|
||||
)
|
||||
|
||||
return {"created": created, "duplicates": duplicates}
|
||||
|
||||
|
||||
@router.get("/group/{group_id}")
|
||||
def list_group_files(
|
||||
group_id: int,
|
||||
q: str | None = None,
|
||||
status: str | None = None,
|
||||
sync_status: str | None = None,
|
||||
file_type: str | None = None,
|
||||
uploaded_from: str | None = None,
|
||||
uploaded_to: str | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
ensure_group_access(db, user, group_id)
|
||||
query = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Document.group_id == group_id, Document.is_deleted.is_(False))
|
||||
.order_by(Document.updated_at.desc())
|
||||
)
|
||||
documents = query.all()
|
||||
filtered: list[Document] = []
|
||||
uploaded_from_date = date.fromisoformat(uploaded_from) if uploaded_from else None
|
||||
uploaded_to_date = date.fromisoformat(uploaded_to) if uploaded_to else None
|
||||
for document in documents:
|
||||
version = current_version(document)
|
||||
if version is None:
|
||||
continue
|
||||
version_uploaded_at = version.uploaded_at.date() if version.uploaded_at else None
|
||||
if q and q.lower() not in document.title.lower():
|
||||
continue
|
||||
if status and version.convert_status != status:
|
||||
continue
|
||||
if sync_status and version.sync_status != sync_status:
|
||||
continue
|
||||
if file_type and version.source_ext != file_type:
|
||||
continue
|
||||
if uploaded_from_date and (version_uploaded_at is None or version_uploaded_at < uploaded_from_date):
|
||||
continue
|
||||
if uploaded_to_date and (version_uploaded_at is None or version_uploaded_at > uploaded_to_date):
|
||||
continue
|
||||
filtered.append(document)
|
||||
return {"data": [serialize_document(document) for document in filtered]}
|
||||
|
||||
|
||||
@router.get("/{file_id}")
|
||||
def get_file(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
payload = serialize_document(document)
|
||||
payload["versions"] = [serialize_version(item) for item in document.versions]
|
||||
return payload
|
||||
|
||||
|
||||
@router.get("/{file_id}/download")
|
||||
def download_file(
|
||||
file_id: int,
|
||||
kind: str = Query("md"),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
if not version:
|
||||
raise HTTPException(status_code=404, detail="No version found.")
|
||||
|
||||
if kind == "source":
|
||||
path = Path(version.source_path)
|
||||
filename = version.source_filename
|
||||
else:
|
||||
if not version.md_path:
|
||||
raise HTTPException(status_code=409, detail="Markdown not ready.")
|
||||
path = Path(version.md_path)
|
||||
filename = f"{document.title}.md"
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail="File missing on disk.")
|
||||
return FileResponse(path, filename=filename)
|
||||
|
||||
|
||||
@router.post("/download-batch")
|
||||
def batch_download(
|
||||
payload: BatchDownloadRequest,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
query = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions))
|
||||
.filter(Document.id.in_(payload.document_ids), Document.is_deleted.is_(False))
|
||||
)
|
||||
group_ids = _group_scope_filter(db, user)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Document.group_id.in_(group_ids))
|
||||
documents = query.all()
|
||||
if not documents:
|
||||
raise HTTPException(status_code=404, detail="No documents found.")
|
||||
bundle_id = str(uuid.uuid4())
|
||||
bundle_dir = settings.data_root / "tmp" / "downloads"
|
||||
bundle_path = bundle_dir / f"download_{bundle_id}.zip"
|
||||
entries: list[tuple[Path, str]] = []
|
||||
for document in documents:
|
||||
version = current_version(document)
|
||||
if not version:
|
||||
continue
|
||||
if payload.kind == "source":
|
||||
entries.append((Path(version.source_path), version.source_filename))
|
||||
else:
|
||||
if version.md_path:
|
||||
entries.append((Path(version.md_path), f"{document.title}.md"))
|
||||
if not entries:
|
||||
raise HTTPException(status_code=409, detail="No downloadable files available.")
|
||||
build_zip(entries, bundle_path)
|
||||
download_date = date.today().strftime("%Y%m%d")
|
||||
return FileResponse(bundle_path, filename=f"文件下载_{download_date}.zip")
|
||||
|
||||
|
||||
@router.post("/{file_id}/retry-convert")
|
||||
def retry_convert(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
if not version:
|
||||
raise HTTPException(status_code=404, detail="Version not found.")
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="convert",
|
||||
created_by_id=user.id,
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
version_id=version.id,
|
||||
payload={"retry": True},
|
||||
)
|
||||
_enqueue(job, "app.tasks.run_convert_job", version.id, db)
|
||||
return serialize_job(job)
|
||||
|
||||
|
||||
@router.post("/{file_id}/sync-dify")
|
||||
def sync_dify(file_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
if not version or version.convert_status != "success":
|
||||
raise HTTPException(status_code=409, detail="Document is not ready for sync.")
|
||||
if version.sync_status == "synced":
|
||||
raise HTTPException(status_code=409, detail="Current version is already synced to Dify.")
|
||||
if version.sync_status == "syncing":
|
||||
raise HTTPException(status_code=409, detail="Current version is already syncing to Dify.")
|
||||
version.sync_status = "syncing"
|
||||
db.commit()
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="sync",
|
||||
created_by_id=user.id,
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
version_id=version.id,
|
||||
payload={"single": True},
|
||||
)
|
||||
_enqueue(job, "app.tasks.run_sync_job", version.id, db)
|
||||
return serialize_job(job)
|
||||
|
||||
|
||||
@router.post("/sync-dify-batch")
|
||||
def batch_sync(
|
||||
payload: BatchSyncRequest,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Document).options(joinedload(Document.versions)).filter(Document.id.in_(payload.document_ids))
|
||||
group_ids = _group_scope_filter(db, user)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Document.group_id.in_(group_ids))
|
||||
documents = query.all()
|
||||
jobs: list[dict] = []
|
||||
for document in documents:
|
||||
if document.is_deleted:
|
||||
continue
|
||||
version = current_version(document)
|
||||
if not version or version.convert_status != "success":
|
||||
continue
|
||||
if version.sync_status in {"synced", "syncing"}:
|
||||
continue
|
||||
version.sync_status = "syncing"
|
||||
db.commit()
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="sync",
|
||||
created_by_id=user.id,
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
version_id=version.id,
|
||||
payload={"batch": True},
|
||||
)
|
||||
_enqueue(job, "app.tasks.run_sync_job", version.id, db)
|
||||
jobs.append(serialize_job(job))
|
||||
return {"data": jobs}
|
||||
|
||||
|
||||
@router.delete("/{file_id}")
|
||||
def delete_file(
|
||||
file_id: int,
|
||||
delete_dify: bool = Query(False),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
document = _get_document_for_user(db, user, file_id)
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
|
||||
version = current_version(document)
|
||||
original_title = document.title
|
||||
document.is_deleted = True
|
||||
document.title = f"{document.title}__deleted__{document.id}"
|
||||
db.commit()
|
||||
try:
|
||||
job = _create_job(
|
||||
db,
|
||||
job_type="delete",
|
||||
created_by_id=user.id,
|
||||
group_id=document.group_id,
|
||||
document_id=document.id,
|
||||
version_id=version.id if version else None,
|
||||
payload={"delete_dify": delete_dify},
|
||||
)
|
||||
_enqueue_args(job, "app.tasks.run_delete_document_job", db, document.id)
|
||||
except Exception:
|
||||
document.is_deleted = False
|
||||
document.title = original_title
|
||||
db.commit()
|
||||
raise
|
||||
return {"deleted": True}
|
||||
@@ -1,757 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.deps import (
|
||||
accessible_department_ids,
|
||||
accessible_group_ids,
|
||||
ensure_department_access,
|
||||
ensure_group_access,
|
||||
get_current_user,
|
||||
require_admin,
|
||||
)
|
||||
from app.models import Department, DifySyncRecord, Document, DocumentVersion, Group, Job, SystemSetting, User
|
||||
from app.schemas import DifyImportRequest, GroupCreateRequest, GroupUpdateRequest
|
||||
from app.serializers import current_version, serialize_document, serialize_group
|
||||
from app.services.dify_service import DifyError, DifyService
|
||||
from app.services.storage_service import public_storage_url, remove_path_if_exists, sha256_file, version_dir
|
||||
from app.time_utils import utc_now
|
||||
import requests
|
||||
|
||||
|
||||
router = APIRouter(prefix="/groups", tags=["groups"])
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
def _scoped_group_ids(db: Session, user: User) -> list[int] | None:
|
||||
return accessible_group_ids(db, user)
|
||||
|
||||
|
||||
def _scoped_department_ids(db: Session, user: User) -> list[int] | None:
|
||||
return accessible_department_ids(db, user)
|
||||
|
||||
|
||||
def _scoped_groups_query(db: Session, user: User, *, department_id: int | None = None):
|
||||
query = db.query(Group)
|
||||
group_ids = _scoped_group_ids(db, user)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Group.id.in_(group_ids or [-1]))
|
||||
if department_id is not None:
|
||||
query = query.filter(Group.department_id == department_id)
|
||||
return query
|
||||
|
||||
|
||||
def _document_name_key(name: str) -> str:
|
||||
trimmed = (name or "").strip().lower()
|
||||
candidate = Path(trimmed)
|
||||
return candidate.stem if candidate.suffix else trimmed
|
||||
|
||||
|
||||
def _normalized_document_title(name: str) -> str:
|
||||
candidate = Path((name or "").strip())
|
||||
return candidate.stem if candidate.suffix else candidate.name
|
||||
|
||||
|
||||
def _resolve_storage_target(path_value: str | None, *, parent: bool = False) -> Path | None:
|
||||
if not path_value:
|
||||
return None
|
||||
raw_target = Path(path_value)
|
||||
data_root = settings.data_root.resolve(strict=False)
|
||||
if raw_target.is_absolute():
|
||||
target = raw_target
|
||||
else:
|
||||
resolved_raw = raw_target.resolve(strict=False)
|
||||
target = resolved_raw if resolved_raw.is_relative_to(data_root) else settings.data_root / raw_target
|
||||
if parent:
|
||||
target = target.parent
|
||||
resolved = target.resolve(strict=False)
|
||||
if not resolved.is_relative_to(data_root):
|
||||
return None
|
||||
return resolved
|
||||
|
||||
|
||||
def _cleanup_document_storage(document: Document) -> None:
|
||||
targets: set[Path] = set()
|
||||
for version in document.versions:
|
||||
for candidate in (
|
||||
_resolve_storage_target(version.source_path, parent=True),
|
||||
_resolve_storage_target(version.md_path, parent=True),
|
||||
_resolve_storage_target(version.asset_dir),
|
||||
):
|
||||
if candidate is not None:
|
||||
targets.add(candidate)
|
||||
|
||||
for target in sorted(targets, key=lambda item: len(item.parts), reverse=True):
|
||||
remove_path_if_exists(target)
|
||||
|
||||
|
||||
def _local_documents_for_group(group: Group) -> dict[str, list[dict]]:
|
||||
local_docs: dict[str, list[dict]] = {}
|
||||
for document in group.documents:
|
||||
if document.is_deleted:
|
||||
continue
|
||||
version = current_version(document)
|
||||
if version is None:
|
||||
continue
|
||||
local_docs.setdefault(_document_name_key(document.title), []).append(
|
||||
{
|
||||
"document_id": document.id,
|
||||
"title": document.title,
|
||||
"source_ext": version.source_ext,
|
||||
"convert_status": version.convert_status,
|
||||
"sync_status": version.sync_status,
|
||||
"remote_document_id": version.sync_records[0].remote_document_id if version.sync_records else None,
|
||||
}
|
||||
)
|
||||
return local_docs
|
||||
|
||||
|
||||
def _remote_documents_for_dataset(dify: DifyService, dataset_id: str | None) -> dict[str, list[dict]]:
|
||||
if not dataset_id:
|
||||
return {}
|
||||
remote_docs: dict[str, list[dict]] = {}
|
||||
for remote in dify.list_documents(dataset_id=dataset_id):
|
||||
remote_docs.setdefault(_document_name_key(remote.name), []).append(
|
||||
{
|
||||
"document_id": remote.id,
|
||||
"name": remote.name,
|
||||
"indexing_status": remote.indexing_status,
|
||||
"display_status": remote.display_status,
|
||||
"enabled": remote.enabled,
|
||||
}
|
||||
)
|
||||
return remote_docs
|
||||
|
||||
|
||||
def _diff_status(local_entry: dict | None, remote_entry: dict | None) -> str:
|
||||
if local_entry and not remote_entry:
|
||||
return "local_only"
|
||||
if remote_entry and not local_entry:
|
||||
return "dify_only"
|
||||
if (
|
||||
(local_entry or {}).get("sync_status") != "synced"
|
||||
or (remote_entry or {}).get("indexing_status") not in {"completed", "completed_with_warning"}
|
||||
):
|
||||
return "attention"
|
||||
return "matched"
|
||||
|
||||
|
||||
def _build_diff_rows(
|
||||
*,
|
||||
knowledge_base_name: str,
|
||||
dataset_id: str | None,
|
||||
local_docs: dict[str, list[dict]],
|
||||
remote_docs: dict[str, list[dict]],
|
||||
group: Group | None = None,
|
||||
term: str = "",
|
||||
include_knowledge_base: bool = False,
|
||||
) -> list[dict]:
|
||||
rows: list[dict] = []
|
||||
for key in sorted(set(local_docs) | set(remote_docs)):
|
||||
local_entries = list(local_docs.get(key, []))
|
||||
remote_entries = list(remote_docs.get(key, []))
|
||||
|
||||
local_entries.sort(
|
||||
key=lambda item: (
|
||||
f"{item.get('title') or ''}{item.get('source_ext') or ''}".lower(),
|
||||
int(item.get("document_id") or 0),
|
||||
)
|
||||
)
|
||||
remote_entries.sort(
|
||||
key=lambda item: (
|
||||
(item.get("name") or "").lower(),
|
||||
str(item.get("document_id") or ""),
|
||||
)
|
||||
)
|
||||
|
||||
paired_rows: list[tuple[dict | None, dict | None]] = []
|
||||
remaining_remote = remote_entries.copy()
|
||||
|
||||
for local_entry in local_entries:
|
||||
local_full_name = f"{local_entry.get('title') or ''}{local_entry.get('source_ext') or ''}".lower()
|
||||
match_index = next(
|
||||
(
|
||||
index
|
||||
for index, remote_entry in enumerate(remaining_remote)
|
||||
if (remote_entry.get("name") or "").strip().lower() == local_full_name
|
||||
),
|
||||
None,
|
||||
)
|
||||
if match_index is None and remaining_remote:
|
||||
match_index = 0
|
||||
|
||||
if match_index is None:
|
||||
paired_rows.append((local_entry, None))
|
||||
else:
|
||||
paired_rows.append((local_entry, remaining_remote.pop(match_index)))
|
||||
|
||||
paired_rows.extend((None, remote_entry) for remote_entry in remaining_remote)
|
||||
|
||||
for index, (local_entry, remote_entry) in enumerate(paired_rows, start=1):
|
||||
display_name = (local_entry or {}).get("title") or (remote_entry or {}).get("name") or key
|
||||
haystacks = [display_name.lower(), knowledge_base_name.lower()]
|
||||
if term and not any(term in item for item in haystacks):
|
||||
continue
|
||||
|
||||
row = {
|
||||
"key": f"{knowledge_base_name}:{key}:{index}" if include_knowledge_base else f"{key}:{index}",
|
||||
"status": _diff_status(local_entry, remote_entry),
|
||||
"local": local_entry,
|
||||
"remote": remote_entry,
|
||||
"display_name": display_name,
|
||||
}
|
||||
if include_knowledge_base:
|
||||
row["knowledge_base"] = {
|
||||
"group_id": group.id if group else None,
|
||||
"name": knowledge_base_name,
|
||||
"dataset_id": dataset_id,
|
||||
}
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def _summarize_diff_rows(rows: list[dict]) -> dict[str, int]:
|
||||
return {
|
||||
"matched": sum(1 for row in rows if row["status"] == "matched"),
|
||||
"local_only": sum(1 for row in rows if row["status"] == "local_only"),
|
||||
"dify_only": sum(1 for row in rows if row["status"] == "dify_only"),
|
||||
"attention": sum(1 for row in rows if row["status"] == "attention"),
|
||||
}
|
||||
|
||||
|
||||
def _create_group_from_remote_name(*, db: Session, admin: User, group_name: str) -> Group:
|
||||
if admin.primary_department_id is None:
|
||||
raise HTTPException(status_code=400, detail="Admin must belong to a department before importing Dify documents.")
|
||||
return _create_group_from_remote_name_in_department(
|
||||
db=db,
|
||||
admin=admin,
|
||||
group_name=group_name,
|
||||
department_id=admin.primary_department_id,
|
||||
)
|
||||
|
||||
|
||||
def _create_group_from_remote_name_in_department(
|
||||
*,
|
||||
db: Session,
|
||||
admin: User,
|
||||
group_name: str,
|
||||
department_id: int,
|
||||
) -> Group:
|
||||
defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
|
||||
existing = (
|
||||
db.query(Group)
|
||||
.filter(Group.department_id == department_id, Group.name == group_name)
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
return existing
|
||||
group = Group(
|
||||
name=group_name,
|
||||
description=None,
|
||||
department_id=department_id,
|
||||
created_by_id=admin.id,
|
||||
indexing_technique=defaults.indexing_technique if defaults else "high_quality",
|
||||
search_method=defaults.search_method if defaults else "hybrid_search",
|
||||
doc_form=defaults.doc_form if defaults else "text_model",
|
||||
top_k=defaults.top_k if defaults else 5,
|
||||
score_threshold_enabled=defaults.score_threshold_enabled if defaults else True,
|
||||
score_threshold=defaults.score_threshold if defaults else "0.35",
|
||||
)
|
||||
db.add(group)
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
return group
|
||||
|
||||
|
||||
def _download_remote_upload(upload_file: dict | None) -> tuple[str, bytes] | None:
|
||||
if not upload_file:
|
||||
return None
|
||||
download_url = upload_file.get("download_url") or upload_file.get("url")
|
||||
if not download_url:
|
||||
return None
|
||||
response = requests.get(download_url, timeout=60)
|
||||
response.raise_for_status()
|
||||
filename = upload_file.get("name") or "remote-file"
|
||||
return filename, response.content
|
||||
|
||||
|
||||
def _import_dify_document_to_local(
|
||||
*,
|
||||
db: Session,
|
||||
user: User,
|
||||
dataset_id: str,
|
||||
remote_document_id: str,
|
||||
group: Group,
|
||||
) -> Document:
|
||||
dify = DifyService()
|
||||
detail = dify.get_document_detail(dataset_id=dataset_id, document_id=remote_document_id)
|
||||
remote_name = (detail.get("name") or "").strip() or remote_document_id
|
||||
title = _normalized_document_title(remote_name)
|
||||
|
||||
existing = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(
|
||||
Document.group_id == group.id,
|
||||
func.lower(Document.title) == title.lower(),
|
||||
Document.is_deleted.is_(False),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail="Document already exists locally. Refresh diff and retry.")
|
||||
|
||||
segments = dify.list_document_segments(dataset_id=dataset_id, document_id=remote_document_id)
|
||||
markdown_text = "\n\n".join(item.content.strip() for item in segments if item.content and item.content.strip()).strip()
|
||||
if not markdown_text:
|
||||
raise HTTPException(status_code=409, detail="Remote Dify document has no importable content.")
|
||||
|
||||
document = Document(group_id=group.id, title=title, created_by_id=user.id, is_deleted=False)
|
||||
db.add(document)
|
||||
db.commit()
|
||||
db.refresh(document)
|
||||
|
||||
version_no = 1
|
||||
source_dir = version_dir("original", group.id, document.id, version_no)
|
||||
markdown_dir = version_dir("markdown", group.id, document.id, version_no)
|
||||
source_dir.mkdir(parents=True, exist_ok=True)
|
||||
markdown_dir.mkdir(parents=True, exist_ok=True)
|
||||
markdown_target = markdown_dir / "document.md"
|
||||
markdown_target.write_text(markdown_text, encoding="utf-8")
|
||||
|
||||
source_filename = remote_name if Path(remote_name).suffix else f"{remote_name}.md"
|
||||
source_ext = Path(source_filename).suffix.lower() or ".md"
|
||||
source_target = source_dir / source_filename
|
||||
|
||||
upload_file = None
|
||||
try:
|
||||
upload_file = dify.get_upload_file(dataset_id=dataset_id, document_id=remote_document_id)
|
||||
except DifyError:
|
||||
upload_file = None
|
||||
|
||||
downloaded = None
|
||||
if upload_file:
|
||||
try:
|
||||
downloaded = _download_remote_upload(upload_file)
|
||||
except Exception:
|
||||
downloaded = None
|
||||
|
||||
if downloaded:
|
||||
source_filename, source_bytes = downloaded
|
||||
source_ext = Path(source_filename).suffix.lower() or ".bin"
|
||||
source_target = source_dir / source_filename
|
||||
source_target.write_bytes(source_bytes)
|
||||
else:
|
||||
source_target.write_text(markdown_text, encoding="utf-8")
|
||||
source_filename = source_target.name
|
||||
source_ext = ".md"
|
||||
|
||||
version = DocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=version_no,
|
||||
is_current=True,
|
||||
source_filename=source_filename,
|
||||
source_ext=source_ext,
|
||||
source_path=str(source_target),
|
||||
source_sha256=sha256_file(source_target),
|
||||
md_path=str(markdown_target),
|
||||
md_public_url=public_storage_url(markdown_target),
|
||||
asset_dir=None,
|
||||
file_size=source_target.stat().st_size,
|
||||
word_count=len(markdown_text.split()),
|
||||
convert_status="success",
|
||||
sync_status="synced",
|
||||
uploader_id=user.id,
|
||||
uploaded_at=utc_now(),
|
||||
converted_at=utc_now(),
|
||||
warnings_json=[{"message": "imported_from_dify"}],
|
||||
)
|
||||
db.add(version)
|
||||
db.commit()
|
||||
db.refresh(version)
|
||||
|
||||
sync_record = DifySyncRecord(
|
||||
version_id=version.id,
|
||||
dataset_id=dataset_id,
|
||||
remote_document_id=remote_document_id,
|
||||
status="synced",
|
||||
last_indexing_status=detail.get("indexing_status"),
|
||||
last_synced_at=utc_now(),
|
||||
error=None,
|
||||
)
|
||||
db.add(sync_record)
|
||||
if group.dify_dataset_id != dataset_id:
|
||||
group.dify_dataset_id = dataset_id
|
||||
db.commit()
|
||||
db.refresh(document)
|
||||
return document
|
||||
|
||||
|
||||
def _group_name_conflict(
|
||||
db: Session,
|
||||
*,
|
||||
department_id: int | None,
|
||||
name: str,
|
||||
exclude_group_id: int | None = None,
|
||||
) -> bool:
|
||||
query = db.query(Group).filter(Group.department_id == department_id, Group.name == name)
|
||||
if exclude_group_id is not None:
|
||||
query = query.filter(Group.id != exclude_group_id)
|
||||
return db.query(query.exists()).scalar()
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_groups(
|
||||
department_id: int | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if department_id is not None:
|
||||
ensure_department_access(db, user, department_id)
|
||||
group_ids = _scoped_group_ids(db, user)
|
||||
document_counts_query = (
|
||||
db.query(
|
||||
Document.group_id.label("group_id"),
|
||||
func.count(Document.id).label("document_count"),
|
||||
)
|
||||
.filter(Document.is_deleted.is_(False))
|
||||
.group_by(Document.group_id)
|
||||
)
|
||||
if group_ids is not None:
|
||||
document_counts_query = document_counts_query.filter(Document.group_id.in_(group_ids or [-1]))
|
||||
document_counts = document_counts_query.subquery()
|
||||
query = db.query(
|
||||
Group,
|
||||
func.coalesce(document_counts.c.document_count, 0).label("document_count"),
|
||||
).options(joinedload(Group.department)).outerjoin(document_counts, document_counts.c.group_id == Group.id)
|
||||
if group_ids is not None:
|
||||
query = query.filter(Group.id.in_(group_ids or [-1]))
|
||||
if department_id is not None:
|
||||
query = query.filter(Group.department_id == department_id)
|
||||
groups = query.order_by(Group.name.asc()).all()
|
||||
return {
|
||||
"data": [serialize_group(group, document_count=document_count) for group, document_count in groups]
|
||||
}
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
def get_dashboard_summary(
|
||||
department_id: int | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if department_id is not None:
|
||||
ensure_department_access(db, user, department_id)
|
||||
group_ids = _scoped_group_ids(db, user)
|
||||
knowledge_base_query = db.query(Group)
|
||||
file_query = db.query(Document).filter(Document.is_deleted.is_(False))
|
||||
if group_ids is not None:
|
||||
scoped_filter = group_ids or [-1]
|
||||
knowledge_base_query = knowledge_base_query.filter(Group.id.in_(scoped_filter))
|
||||
file_query = file_query.filter(Document.group_id.in_(scoped_filter))
|
||||
if department_id is not None:
|
||||
knowledge_base_query = knowledge_base_query.filter(Group.department_id == department_id)
|
||||
file_query = file_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
|
||||
knowledge_base_count = knowledge_base_query.count()
|
||||
file_count = file_query.count()
|
||||
running_query = (
|
||||
db.query(DocumentVersion)
|
||||
.join(Document, Document.id == DocumentVersion.document_id)
|
||||
.filter(Document.is_deleted.is_(False), DocumentVersion.is_current.is_(True))
|
||||
.filter(
|
||||
or_(
|
||||
DocumentVersion.convert_status.in_(["queued", "running"]),
|
||||
DocumentVersion.sync_status == "syncing",
|
||||
)
|
||||
)
|
||||
)
|
||||
if group_ids is not None:
|
||||
running_query = running_query.filter(Document.group_id.in_(group_ids or [-1]))
|
||||
if department_id is not None:
|
||||
running_query = running_query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
|
||||
running_count = running_query.count()
|
||||
return {
|
||||
"knowledge_base_count": knowledge_base_count,
|
||||
"file_count": file_count,
|
||||
"running_count": running_count,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/dify-diff-global")
|
||||
def get_global_dify_diff(
|
||||
q: str | None = Query(None),
|
||||
department_id: int | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
if department_id is not None:
|
||||
ensure_department_access(db, user, department_id)
|
||||
groups_query = (
|
||||
db.query(Group)
|
||||
.options(joinedload(Group.department))
|
||||
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
)
|
||||
group_ids = _scoped_group_ids(db, user)
|
||||
if group_ids is not None:
|
||||
groups_query = groups_query.filter(Group.id.in_(group_ids or [-1]))
|
||||
if department_id is not None:
|
||||
groups_query = groups_query.filter(Group.department_id == department_id)
|
||||
groups = groups_query.order_by(Group.name.asc()).all()
|
||||
dify = DifyService()
|
||||
datasets = dify.list_datasets()
|
||||
datasets_by_id = {item.id: item for item in datasets}
|
||||
datasets_by_name = {item.name: item for item in datasets}
|
||||
used_dataset_ids: set[str] = set()
|
||||
term = (q or "").strip().lower()
|
||||
rows: list[dict] = []
|
||||
|
||||
for group in groups:
|
||||
dataset = datasets_by_id.get(group.dify_dataset_id or "") or datasets_by_name.get(group.name)
|
||||
dataset_id = dataset.id if dataset else group.dify_dataset_id
|
||||
if dataset:
|
||||
used_dataset_ids.add(dataset.id)
|
||||
rows.extend(
|
||||
_build_diff_rows(
|
||||
knowledge_base_name=group.name,
|
||||
dataset_id=dataset_id,
|
||||
local_docs=_local_documents_for_group(group),
|
||||
remote_docs=_remote_documents_for_dataset(dify, dataset.id if dataset else group.dify_dataset_id),
|
||||
group=group,
|
||||
term=term,
|
||||
include_knowledge_base=True,
|
||||
)
|
||||
)
|
||||
|
||||
return {"summary": _summarize_diff_rows(rows), "rows": rows}
|
||||
|
||||
|
||||
@router.post("/import-dify-document")
|
||||
def import_dify_document(
|
||||
payload: DifyImportRequest,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
target_group: Group | None = None
|
||||
if payload.group_id is not None:
|
||||
ensure_group_access(db, user, payload.group_id)
|
||||
target_group = db.query(Group).filter(Group.id == payload.group_id).first()
|
||||
if not target_group:
|
||||
raise HTTPException(status_code=404, detail="Knowledge base not found.")
|
||||
else:
|
||||
if user.role not in {"admin", "super_admin"}:
|
||||
raise HTTPException(status_code=403, detail="Admin permission required.")
|
||||
knowledge_base_name = (payload.knowledge_base_name or "").strip()
|
||||
if not knowledge_base_name:
|
||||
raise HTTPException(status_code=400, detail="Knowledge base name is required for Dify import.")
|
||||
department_id = payload.department_id or user.primary_department_id
|
||||
if department_id is None:
|
||||
raise HTTPException(status_code=400, detail="Department is required for Dify import.")
|
||||
ensure_department_access(db, user, department_id)
|
||||
target_group = _create_group_from_remote_name_in_department(
|
||||
db=db,
|
||||
admin=user,
|
||||
group_name=knowledge_base_name,
|
||||
department_id=department_id,
|
||||
)
|
||||
|
||||
document = _import_dify_document_to_local(
|
||||
db=db,
|
||||
user=user,
|
||||
dataset_id=payload.dataset_id,
|
||||
remote_document_id=payload.remote_document_id,
|
||||
group=target_group,
|
||||
)
|
||||
return {
|
||||
"group_id": target_group.id,
|
||||
"group_name": target_group.name,
|
||||
"document": serialize_document(document),
|
||||
}
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_group(
|
||||
payload: GroupCreateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
ensure_department_access(db, admin, payload.department_id)
|
||||
if _group_name_conflict(db, department_id=payload.department_id, name=payload.name):
|
||||
raise HTTPException(status_code=409, detail="Group already exists.")
|
||||
defaults = db.query(SystemSetting).filter(SystemSetting.id == 1).first()
|
||||
group = Group(
|
||||
name=payload.name,
|
||||
description=payload.description,
|
||||
department_id=payload.department_id,
|
||||
created_by_id=admin.id,
|
||||
indexing_technique=defaults.indexing_technique if defaults else "high_quality",
|
||||
search_method=defaults.search_method if defaults else "hybrid_search",
|
||||
doc_form=defaults.doc_form if defaults else "text_model",
|
||||
top_k=defaults.top_k if defaults else 5,
|
||||
score_threshold_enabled=defaults.score_threshold_enabled if defaults else True,
|
||||
score_threshold=defaults.score_threshold if defaults else "0.35",
|
||||
)
|
||||
db.add(group)
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
return serialize_group(group)
|
||||
|
||||
|
||||
@router.patch("/{group_id}")
|
||||
def update_group(
|
||||
group_id: int,
|
||||
payload: GroupUpdateRequest,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
ensure_group_access(db, admin, group_id)
|
||||
group = db.query(Group).filter(Group.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found.")
|
||||
old_name = group.name
|
||||
target_name = payload.name or group.name
|
||||
target_department_id = payload.department_id if payload.department_id is not None else group.department_id
|
||||
if payload.department_id is not None and payload.department_id != group.department_id:
|
||||
ensure_department_access(db, admin, payload.department_id)
|
||||
if payload.name or payload.department_id is not None:
|
||||
if _group_name_conflict(
|
||||
db,
|
||||
department_id=target_department_id,
|
||||
name=target_name,
|
||||
exclude_group_id=group.id,
|
||||
):
|
||||
raise HTTPException(status_code=409, detail="Group already exists.")
|
||||
if payload.name:
|
||||
group.name = payload.name
|
||||
if payload.description is not None:
|
||||
group.description = payload.description
|
||||
if payload.department_id is not None and payload.department_id != group.department_id:
|
||||
group.department_id = payload.department_id
|
||||
db.commit()
|
||||
if payload.rename_dify and group.dify_dataset_id and payload.name and payload.name != old_name:
|
||||
dify = DifyService()
|
||||
dify.update_dataset(dataset_id=group.dify_dataset_id, name=payload.name)
|
||||
db.refresh(group)
|
||||
return serialize_group(group)
|
||||
|
||||
|
||||
@router.delete("/{group_id}")
|
||||
def delete_group(
|
||||
group_id: int,
|
||||
delete_dify: bool = Query(False),
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_admin),
|
||||
):
|
||||
ensure_group_access(db, admin, group_id)
|
||||
group = (
|
||||
db.query(Group)
|
||||
.options(joinedload(Group.department))
|
||||
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Group.id == group_id)
|
||||
.first()
|
||||
)
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found.")
|
||||
|
||||
running_job = (
|
||||
db.query(Job)
|
||||
.filter(Job.group_id == group.id, Job.status.in_(["queued", "running"]))
|
||||
.first()
|
||||
)
|
||||
if running_job:
|
||||
raise HTTPException(status_code=409, detail="Group has running jobs and cannot be deleted.")
|
||||
|
||||
if delete_dify and group.dify_dataset_id:
|
||||
dify = DifyService()
|
||||
dify.delete_dataset(dataset_id=group.dify_dataset_id)
|
||||
|
||||
for document in group.documents:
|
||||
_cleanup_document_storage(document)
|
||||
|
||||
db.query(Job).filter(Job.group_id == group.id).delete(synchronize_session=False)
|
||||
for document in list(group.documents):
|
||||
db.delete(document)
|
||||
db.delete(group)
|
||||
db.commit()
|
||||
return {"deleted": True}
|
||||
|
||||
|
||||
@router.get("/{group_id}/files")
|
||||
def list_group_files(
|
||||
group_id: int,
|
||||
q: str | None = Query(None),
|
||||
status: str | None = Query(None),
|
||||
sync_status: str | None = Query(None),
|
||||
file_type: str | None = Query(None),
|
||||
uploaded_from: str | None = Query(None),
|
||||
uploaded_to: str | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
ensure_group_access(db, user, group_id)
|
||||
query = (
|
||||
db.query(Document)
|
||||
.options(joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Document.group_id == group_id, Document.is_deleted.is_(False))
|
||||
.order_by(Document.updated_at.desc())
|
||||
)
|
||||
documents = query.all()
|
||||
filtered: list[Document] = []
|
||||
uploaded_from_date = date.fromisoformat(uploaded_from) if uploaded_from else None
|
||||
uploaded_to_date = date.fromisoformat(uploaded_to) if uploaded_to else None
|
||||
for document in documents:
|
||||
version = current_version(document)
|
||||
if version is None:
|
||||
continue
|
||||
version_uploaded_at = version.uploaded_at.date() if version.uploaded_at else None
|
||||
if q and q.lower() not in document.title.lower():
|
||||
continue
|
||||
if status and version.convert_status != status:
|
||||
continue
|
||||
if sync_status and version.sync_status != sync_status:
|
||||
continue
|
||||
if file_type and version.source_ext != file_type:
|
||||
continue
|
||||
if uploaded_from_date and (version_uploaded_at is None or version_uploaded_at < uploaded_from_date):
|
||||
continue
|
||||
if uploaded_to_date and (version_uploaded_at is None or version_uploaded_at > uploaded_to_date):
|
||||
continue
|
||||
filtered.append(document)
|
||||
return {"data": [serialize_document(document) for document in filtered]}
|
||||
|
||||
|
||||
@router.get("/{group_id}/dify-diff")
|
||||
def get_group_dify_diff(
|
||||
group_id: int,
|
||||
q: str | None = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
ensure_group_access(db, user, group_id)
|
||||
group = (
|
||||
db.query(Group)
|
||||
.options(joinedload(Group.department))
|
||||
.options(joinedload(Group.documents).joinedload(Document.versions).joinedload(DocumentVersion.sync_records))
|
||||
.filter(Group.id == group_id)
|
||||
.first()
|
||||
)
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Group not found.")
|
||||
|
||||
term = (q or "").strip().lower()
|
||||
dify = DifyService() if group.dify_dataset_id else None
|
||||
rows = _build_diff_rows(
|
||||
knowledge_base_name=group.name,
|
||||
dataset_id=group.dify_dataset_id,
|
||||
local_docs=_local_documents_for_group(group),
|
||||
remote_docs=_remote_documents_for_dataset(dify, group.dify_dataset_id) if dify else {},
|
||||
group=group,
|
||||
term=term,
|
||||
)
|
||||
return {"group": serialize_group(group), "summary": _summarize_diff_rows(rows), "rows": rows}
|
||||
+273
-348
@@ -1,378 +1,303 @@
|
||||
"""
|
||||
backend/app/api/integration.py
|
||||
文件用途:知识库外部集成查询接口
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import FileResponse
|
||||
from flask import Blueprint, abort, current_app, jsonify, request, send_file
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.deps import require_integration_key
|
||||
from app.models import DifySyncRecord, Document, DocumentVersion, Group
|
||||
from app.security import create_integration_download_token, decode_integration_download_token
|
||||
from app.serializers import current_version, serialize_group
|
||||
from app.time_utils import utc_now
|
||||
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__)
|
||||
|
||||
|
||||
router = APIRouter(prefix="/integration", tags=["integration"])
|
||||
settings = get_settings()
|
||||
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()
|
||||
|
||||
|
||||
class DifyResolveItem(BaseModel):
|
||||
remote_document_id: str
|
||||
dataset_id: str | None = None
|
||||
|
||||
|
||||
class DifyResolveRequest(BaseModel):
|
||||
items: list[DifyResolveItem]
|
||||
|
||||
|
||||
def _document_query(db: Session):
|
||||
return (
|
||||
db.query(Document)
|
||||
.options(
|
||||
joinedload(Document.group).joinedload(Group.department),
|
||||
joinedload(Document.versions).joinedload(DocumentVersion.sync_records),
|
||||
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'],
|
||||
)
|
||||
.filter(Document.is_deleted.is_(False))
|
||||
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 _knowledge_base_summary(group: Group, *, document_count: int) -> dict:
|
||||
payload = serialize_group(group, document_count=document_count)
|
||||
payload["knowledge_base_id"] = payload["id"]
|
||||
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)
|
||||
|
||||
def _integration_document_payload(
|
||||
document: Document,
|
||||
*,
|
||||
version: DocumentVersion | None = None,
|
||||
sync_record: DifySyncRecord | None = None,
|
||||
) -> dict:
|
||||
version = version or current_version(document)
|
||||
if version is None:
|
||||
raise HTTPException(status_code=404, detail="No current version found.")
|
||||
sync_record = sync_record or (version.sync_records[0] if version.sync_records else None)
|
||||
try:
|
||||
source_token, source_expires_at = create_integration_download_token(
|
||||
file_id=document.id,
|
||||
version_id=version.id,
|
||||
kind="source",
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
||||
md_token = None
|
||||
md_expires_at = None
|
||||
if version.md_path:
|
||||
try:
|
||||
md_token, md_expires_at = create_integration_download_token(
|
||||
file_id=document.id,
|
||||
version_id=version.id,
|
||||
kind="md",
|
||||
)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
||||
return {
|
||||
"queried_at": utc_now().isoformat(),
|
||||
"document_id": document.id,
|
||||
"knowledge_base": {
|
||||
"id": document.group.id,
|
||||
"name": document.group.name,
|
||||
"department_id": document.group.department_id,
|
||||
"department_name": document.group.department.name if document.group.department else None,
|
||||
"dify_dataset_id": document.group.dify_dataset_id,
|
||||
},
|
||||
"title": document.title,
|
||||
"source_filename": version.source_filename,
|
||||
"source_ext": version.source_ext,
|
||||
"file_name": version.source_filename,
|
||||
"version_id": version.id,
|
||||
"version_no": version.version_no,
|
||||
"convert_status": version.convert_status,
|
||||
"sync_status": version.sync_status,
|
||||
"uploaded_at": version.uploaded_at.isoformat() if version.uploaded_at else None,
|
||||
"converted_at": version.converted_at.isoformat() if version.converted_at else None,
|
||||
"download_url_expires_at": source_expires_at.isoformat(),
|
||||
"source_download_url": (
|
||||
f"{settings.public_base_url}{settings.api_prefix}/integration/download"
|
||||
f"?version_id={version.id}&kind=source&token={source_token}"
|
||||
),
|
||||
"markdown_download_url": (
|
||||
f"{settings.public_base_url}{settings.api_prefix}/integration/download"
|
||||
f"?version_id={version.id}&kind=md&token={md_token}"
|
||||
if version.md_path and md_token
|
||||
else None
|
||||
),
|
||||
"markdown_download_url_expires_at": md_expires_at.isoformat() if md_expires_at else None,
|
||||
"markdown_public_url": version.md_public_url,
|
||||
"dify": {
|
||||
"dataset_id": sync_record.dataset_id if sync_record else document.group.dify_dataset_id,
|
||||
"remote_document_id": sync_record.remote_document_id if sync_record else None,
|
||||
"status": sync_record.status if sync_record else None,
|
||||
"last_indexing_status": sync_record.last_indexing_status if sync_record else None,
|
||||
"last_synced_at": sync_record.last_synced_at.isoformat() if sync_record and sync_record.last_synced_at else None,
|
||||
},
|
||||
}
|
||||
@integration_bp.before_request
|
||||
def _verify_integration_access():
|
||||
result = _require_integration_key()
|
||||
if result is not None:
|
||||
return result
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/knowledge-bases")
|
||||
def list_knowledge_bases(
|
||||
department_id: int | None = None,
|
||||
q: str | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
document_counts = (
|
||||
db.query(Document.group_id.label("group_id"), func.count(Document.id).label("document_count"))
|
||||
.filter(Document.is_deleted.is_(False))
|
||||
.group_by(Document.group_id)
|
||||
.subquery()
|
||||
)
|
||||
query = (
|
||||
db.query(Group, func.coalesce(document_counts.c.document_count, 0).label("document_count"))
|
||||
.outerjoin(document_counts, document_counts.c.group_id == Group.id)
|
||||
.options(joinedload(Group.department))
|
||||
.order_by(Group.name.asc())
|
||||
)
|
||||
if department_id is not None:
|
||||
query = query.filter(Group.department_id == department_id)
|
||||
if q:
|
||||
query = query.filter(Group.name.ilike(f"%{q.strip()}%"))
|
||||
rows = query.all()
|
||||
return {"data": [_knowledge_base_summary(group, document_count=document_count) for group, document_count in rows]}
|
||||
|
||||
|
||||
@router.get("/files")
|
||||
def list_files(
|
||||
knowledge_base_id: int | None = None,
|
||||
department_id: int | None = None,
|
||||
file_name: str | None = Query(default=None, description="Filter by source filename or title."),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
query = _document_query(db)
|
||||
if knowledge_base_id is not None:
|
||||
query = query.filter(Document.group_id == knowledge_base_id)
|
||||
if department_id is not None:
|
||||
query = query.join(Group, Group.id == Document.group_id).filter(Group.department_id == department_id)
|
||||
documents = query.order_by(Document.updated_at.desc()).all()
|
||||
normalized = file_name.strip().lower() if file_name else None
|
||||
|
||||
payload: list[dict] = []
|
||||
for document in documents:
|
||||
version = current_version(document)
|
||||
if version is None:
|
||||
continue
|
||||
if normalized and normalized not in version.source_filename.lower() and normalized not in document.title.lower():
|
||||
continue
|
||||
payload.append(_integration_document_payload(document))
|
||||
return {"data": payload}
|
||||
|
||||
|
||||
@router.get("/knowledge-bases/{knowledge_base_id}/files")
|
||||
def list_files_for_knowledge_base(
|
||||
knowledge_base_id: int,
|
||||
file_name: str | None = Query(default=None, description="Filter by source filename or title."),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
return list_files(
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
file_name=file_name,
|
||||
db=db,
|
||||
_="integration",
|
||||
)
|
||||
|
||||
|
||||
@router.get("/files/{file_id}")
|
||||
def get_file_detail(
|
||||
file_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
document = _document_query(db).filter(Document.id == file_id).first()
|
||||
@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 HTTPException(status_code=404, detail="Document not found.")
|
||||
return _integration_document_payload(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]})
|
||||
|
||||
@router.get("/dify-file")
|
||||
def get_file_detail_by_dify(
|
||||
remote_document_id: str = Query(..., description="Dify document id."),
|
||||
dataset_id: str | None = Query(default=None, description="Optional Dify dataset id."),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
record_query = (
|
||||
db.query(DifySyncRecord)
|
||||
.join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id)
|
||||
.join(Document, Document.id == DocumentVersion.document_id)
|
||||
.options(
|
||||
joinedload(DifySyncRecord.version)
|
||||
.joinedload(DocumentVersion.document)
|
||||
.joinedload(Document.group)
|
||||
.joinedload(Group.department),
|
||||
joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records),
|
||||
)
|
||||
.filter(
|
||||
Document.is_deleted.is_(False),
|
||||
DifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
|
||||
)
|
||||
@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(DifySyncRecord.dataset_id == dataset_id)
|
||||
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
|
||||
record = record_query.first()
|
||||
if not record or not record.version or not record.version.document:
|
||||
raise HTTPException(status_code=404, detail="No local file mapping found for the given Dify document.")
|
||||
return _integration_document_payload(record.version.document, version=record.version, sync_record=record)
|
||||
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))
|
||||
|
||||
|
||||
@router.post("/dify-files/resolve")
|
||||
def resolve_files_by_dify(
|
||||
payload: DifyResolveRequest,
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
if not payload.items:
|
||||
return {"data": []}
|
||||
|
||||
remote_ids = sorted({item.remote_document_id for item in payload.items if item.remote_document_id})
|
||||
dataset_ids = sorted({item.dataset_id for item in payload.items if item.dataset_id})
|
||||
|
||||
record_query = (
|
||||
db.query(DifySyncRecord)
|
||||
.join(DocumentVersion, DocumentVersion.id == DifySyncRecord.version_id)
|
||||
.join(Document, Document.id == DocumentVersion.document_id)
|
||||
.options(
|
||||
joinedload(DifySyncRecord.version)
|
||||
.joinedload(DocumentVersion.document)
|
||||
.joinedload(Document.group)
|
||||
.joinedload(Group.department),
|
||||
joinedload(DifySyncRecord.version).joinedload(DocumentVersion.sync_records),
|
||||
)
|
||||
.filter(
|
||||
Document.is_deleted.is_(False),
|
||||
DifySyncRecord.remote_document_id.in_(remote_ids),
|
||||
)
|
||||
.order_by(DifySyncRecord.updated_at.desc(), DifySyncRecord.created_at.desc())
|
||||
)
|
||||
@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:
|
||||
record_query = record_query.filter(
|
||||
(DifySyncRecord.dataset_id.in_(dataset_ids)) | (DifySyncRecord.dataset_id.is_(None))
|
||||
)
|
||||
records = record_query.all()
|
||||
|
||||
records_by_key: dict[tuple[str | None, str], DifySyncRecord] = {}
|
||||
records_by_remote: dict[str, DifySyncRecord] = {}
|
||||
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})
|
||||
|
||||
data: list[dict] = []
|
||||
for item in payload.items:
|
||||
record = records_by_key.get((item.dataset_id, item.remote_document_id))
|
||||
if record is None and item.dataset_id is None:
|
||||
record = records_by_remote.get(item.remote_document_id)
|
||||
data.append(
|
||||
{
|
||||
"request": {
|
||||
"dataset_id": item.dataset_id,
|
||||
"remote_document_id": item.remote_document_id,
|
||||
},
|
||||
"found": bool(record and record.version and record.version.document),
|
||||
"document": (
|
||||
_integration_document_payload(record.version.document, version=record.version, sync_record=record)
|
||||
if record and record.version and record.version.document
|
||||
else None
|
||||
),
|
||||
}
|
||||
)
|
||||
return {"data": data}
|
||||
|
||||
|
||||
@router.get("/files/{file_id}/download")
|
||||
def download_file(
|
||||
file_id: int,
|
||||
kind: str = Query(default="md"),
|
||||
db: Session = Depends(get_db),
|
||||
_: str = Depends(require_integration_key),
|
||||
):
|
||||
document = _document_query(db).filter(Document.id == file_id).first()
|
||||
@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 HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
raise NotFoundError('Document not found.')
|
||||
if not version:
|
||||
raise HTTPException(status_code=404, detail="No version found.")
|
||||
|
||||
if kind == "source":
|
||||
path = Path(version.source_path)
|
||||
filename = version.source_filename
|
||||
else:
|
||||
if not version.md_path:
|
||||
raise HTTPException(status_code=409, detail="Markdown not ready.")
|
||||
path = Path(version.md_path)
|
||||
filename = f"{document.title}.md"
|
||||
|
||||
raise NotFoundError('No version found.')
|
||||
path, filename = _resolve_download_path(version, kind)
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail="File missing on disk.")
|
||||
|
||||
return FileResponse(path, filename=filename)
|
||||
|
||||
|
||||
@router.get("/download")
|
||||
def download_file_from_signed_url(
|
||||
file_id: int | None = Query(default=None),
|
||||
version_id: int | None = Query(default=None),
|
||||
kind: str = Query(default="source"),
|
||||
token: str = Query(...),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
try:
|
||||
payload = decode_integration_download_token(token)
|
||||
except RuntimeError as exc:
|
||||
raise HTTPException(status_code=503, detail=str(exc)) from exc
|
||||
if not payload:
|
||||
raise HTTPException(status_code=401, detail="Invalid or expired download token.")
|
||||
expected_kind = payload.get("kind")
|
||||
expected_version_id = payload.get("version_id")
|
||||
expected_file_id = payload.get("file_id")
|
||||
if expected_kind != kind:
|
||||
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
|
||||
if expected_version_id is not None:
|
||||
if version_id != int(expected_version_id):
|
||||
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
|
||||
version = db.query(DocumentVersion).join(Document).filter(
|
||||
DocumentVersion.id == version_id,
|
||||
Document.is_deleted.is_(False),
|
||||
).first()
|
||||
if not version or not version.document:
|
||||
raise HTTPException(status_code=404, detail="Version not found.")
|
||||
document = version.document
|
||||
else:
|
||||
if file_id is None or expected_file_id is None or int(expected_file_id) != file_id:
|
||||
raise HTTPException(status_code=401, detail="Download token does not match the requested file.")
|
||||
document = _document_query(db).filter(Document.id == file_id).first()
|
||||
if not document:
|
||||
raise HTTPException(status_code=404, detail="Document not found.")
|
||||
version = current_version(document)
|
||||
if not version:
|
||||
raise HTTPException(status_code=404, detail="No version found.")
|
||||
|
||||
if kind == "source":
|
||||
path = Path(version.source_path)
|
||||
filename = version.source_filename
|
||||
else:
|
||||
if not version.md_path:
|
||||
raise HTTPException(status_code=409, detail="Markdown not ready.")
|
||||
path = Path(version.md_path)
|
||||
filename = f"{document.title}.md"
|
||||
|
||||
if not path.exists():
|
||||
raise HTTPException(status_code=404, detail="File missing on disk.")
|
||||
return FileResponse(path, filename=filename)
|
||||
raise NotFoundError('File not found on disk.')
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/api/internal/__init__.py
|
||||
|
||||
用途:内部 job 回调/健康检查 Blueprint。
|
||||
"""
|
||||
from app.api.internal.jobs import internal_jobs_bp # noqa: F401
|
||||
|
||||
__all__ = ['internal_jobs_bp']
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/api/internal/jobs.py
|
||||
|
||||
用途:内部 jobs API(Wave 1 自 internal_jobs.py 迁入)。
|
||||
"""
|
||||
from app.api.internal_jobs import internal_jobs_bp # noqa: F401
|
||||
|
||||
__all__ = ['internal_jobs_bp']
|
||||
@@ -0,0 +1,124 @@
|
||||
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 {}
|
||||
if key in {'fixed-assets-snapshot', 'fixed_assets_snapshot', 'fixedassets'}:
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
|
||||
summary = FixedAssetsSnapshotService.sync_once(reason='internal_api', attempt=1)
|
||||
row_count = int(summary.get('row_count') or 0)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': row_count,
|
||||
'success_count': row_count,
|
||||
'failed_count': 0,
|
||||
'skipped_count': 0,
|
||||
},
|
||||
'details': [summary],
|
||||
'errors': [],
|
||||
'step_logs': [
|
||||
{
|
||||
'step': 'fixed_assets_snapshot_sync',
|
||||
'status': 'success',
|
||||
'detail': {
|
||||
'version': summary.get('current_version'),
|
||||
'row_count': row_count,
|
||||
},
|
||||
}
|
||||
],
|
||||
})
|
||||
if key in {'faq-aggregate-hot', 'faq_hot_aggregate', 'faq-hot-aggregate'}:
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
agent_id = data.get('agent_id')
|
||||
if schedule_task_id:
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id))
|
||||
if task and task.dify_agent_id:
|
||||
agent_id = task.dify_agent_id
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(
|
||||
agent_id=int(agent_id) if agent_id else None,
|
||||
dry_run=False,
|
||||
)
|
||||
if not result.get('enabled'):
|
||||
message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
|
||||
return jsonify({
|
||||
'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 1},
|
||||
'details': [],
|
||||
'errors': [message],
|
||||
'step_logs': [{'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}}],
|
||||
})
|
||||
promoted = int(result.get('promoted_count') or 0)
|
||||
skipped = int(result.get('skipped_count') or 0)
|
||||
total = max(promoted + skipped, 1)
|
||||
return jsonify({
|
||||
'summary': {
|
||||
'total_count': total,
|
||||
'success_count': promoted,
|
||||
'failed_count': 0,
|
||||
'skipped_count': skipped,
|
||||
},
|
||||
'details': (result.get('candidates') or [])[:20],
|
||||
'errors': [],
|
||||
'step_logs': [{
|
||||
'step': 'faq_hot_aggregate',
|
||||
'status': 'success',
|
||||
'detail': {
|
||||
'scanned_logs': result.get('scanned_logs'),
|
||||
'promoted_count': promoted,
|
||||
'skipped_count': skipped,
|
||||
},
|
||||
}],
|
||||
})
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
task = None
|
||||
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})
|
||||
@@ -1,47 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.database import get_db
|
||||
from app.deps import accessible_group_ids, get_current_user, is_super_admin
|
||||
from app.models import Job, User
|
||||
from app.serializers import serialize_job
|
||||
|
||||
|
||||
router = APIRouter(prefix="/jobs", tags=["jobs"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_jobs(
|
||||
limit: int = 50,
|
||||
db: Session = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Job).order_by(Job.created_at.desc())
|
||||
if not is_super_admin(user):
|
||||
group_ids = accessible_group_ids(db, user)
|
||||
if user.role == "admin":
|
||||
query = query.filter(or_(Job.created_by_id == user.id, Job.group_id.in_(group_ids or [-1])))
|
||||
else:
|
||||
query = query.filter(Job.created_by_id == user.id)
|
||||
jobs = query.limit(min(limit, 200)).all()
|
||||
return {"data": [serialize_job(job) for job in jobs]}
|
||||
|
||||
|
||||
@router.get("/{job_id}")
|
||||
def get_job(job_id: str, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
|
||||
job = db.query(Job).filter(Job.id == job_id).first()
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail="Job not found.")
|
||||
if is_super_admin(user):
|
||||
return serialize_job(job)
|
||||
if user.role == "admin":
|
||||
group_ids = accessible_group_ids(db, user)
|
||||
if job.created_by_id != user.id and job.group_id not in (group_ids or []):
|
||||
raise HTTPException(status_code=403, detail="Forbidden")
|
||||
return serialize_job(job)
|
||||
if job.created_by_id != user.id:
|
||||
raise HTTPException(status_code=403, detail="Forbidden")
|
||||
return serialize_job(job)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/api/schedule/__init__.py
|
||||
|
||||
用途:排程管理 Blueprint 入口(自 schedule_admin.py 收敛)。
|
||||
逻辑:Wave 1 前 re-export 旧模块 blueprint。
|
||||
"""
|
||||
from app.api.schedule_admin import schedule_admin_bp # noqa: F401
|
||||
|
||||
__all__ = ['schedule_admin_bp']
|
||||
@@ -0,0 +1,513 @@
|
||||
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)
|
||||
raw_kb_sync = data.get('kb_sync_enabled', False)
|
||||
if isinstance(raw_kb_sync, str):
|
||||
test_kb_sync_enabled = raw_kb_sync.strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
else:
|
||||
test_kb_sync_enabled = bool(raw_kb_sync)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
test_sql = base
|
||||
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
||||
from app.services.schedule.srm_service import _fetch_records, _run_check_job_loop, _build_record_text, _execute_writeback
|
||||
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
agent = _resolve_dify_agent(task) if task else None
|
||||
user = _resolve_schedule_user(task) if task else 'test_user'
|
||||
wait_seconds = task.wait_seconds if task else 120
|
||||
dify_agent_id = task.dify_agent_id if task else None
|
||||
run = ScheduleRun(run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=getattr(get_current_user(), 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
if not cfg.fetch_sql:
|
||||
run.status = 'success'
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
db.session.commit()
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': '', 'limit': 0, 'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0, 'details': [], 'errors': [], 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], 'dify_agent_id': dify_agent_id})
|
||||
|
||||
def _test_fetch_fn(conn_str_arg):
|
||||
return _fetch_records(conn_str_arg, test_sql)
|
||||
|
||||
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
|
||||
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
test_pre_dify = None
|
||||
test_build_record = None
|
||||
if cfg.detail_sql:
|
||||
|
||||
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
||||
try:
|
||||
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
||||
except Exception as detail_exc:
|
||||
return {'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc)}
|
||||
detail_lines = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_lines.append(', '.join(parts))
|
||||
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
|
||||
item['_detail_rows'] = detail_rows
|
||||
return None
|
||||
test_pre_dify = _test_pre_dify
|
||||
|
||||
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
||||
detail_rows = item.get('_detail_rows', [])
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_with_detail
|
||||
else:
|
||||
|
||||
def _test_build_simple(conn_str_arg, item, row_id_value):
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_simple
|
||||
start_ts = _time.time()
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(conn_str=conn_str, run_no=run.run_no, agent=agent, user=user, wait_seconds=wait_seconds, run_id=run.id, fetch_fn=_test_fetch_fn, build_record_fn=test_build_record, writeback_fn=_test_writeback_fn, writeback_sql=cfg.writeback_sql, row_id_key=cfg.row_id_key, log_prefix=cfg.log_prefix, fetch_sql=test_sql, max_rows=limit, pre_dify_fn=test_pre_dify, dify_system_prompt=cfg.dify_system_prompt)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
if total_count == 0 and (not errors):
|
||||
status = 'success'
|
||||
elif failed_count == 0:
|
||||
status = 'success'
|
||||
elif success_count == 0:
|
||||
status = 'failed'
|
||||
else:
|
||||
status = 'partial_failed'
|
||||
header_order = cfg.alias_order if cfg.alias_order else None
|
||||
header_labels = cfg.header_labels if cfg.header_labels else None
|
||||
detail_alias_order = cfg.detail_alias_order or []
|
||||
try:
|
||||
file_data, file_name, file_size = export_schedule_result_excel(run_no=run.run_no, summary={'status': status, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'duration_ms': duration_ms}, details=details, header_order=header_order, header_labels=header_labels, detail_alias_order=detail_alias_order)
|
||||
except Exception as excel_exc:
|
||||
current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True)
|
||||
file_data, file_name, file_size = (None, None, 0)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = status
|
||||
run.total_count = total_count
|
||||
run.success_count = success_count
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
run.step_logs = step_logs if step_logs else None
|
||||
run.error_message = '; '.join(errors[:3]) if errors else None
|
||||
run.excel_file_data = file_data
|
||||
run.excel_file_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
db.session.commit()
|
||||
if test_kb_sync_enabled:
|
||||
try:
|
||||
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
||||
|
||||
db.session.refresh(task)
|
||||
db.session.refresh(run)
|
||||
sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True)
|
||||
db.session.refresh(run)
|
||||
except Exception as kb_exc:
|
||||
db.session.rollback()
|
||||
db.session.refresh(run)
|
||||
current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True)
|
||||
run.kb_sync_status = 'failed'
|
||||
run.kb_group_id = getattr(task, 'kb_group_id', None)
|
||||
run.kb_sync_error = str(kb_exc)
|
||||
db.session.commit()
|
||||
try:
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
except Exception as wecom_exc:
|
||||
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||
import decimal, datetime as dt
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
if isinstance(v, (dt.date, dt.datetime)):
|
||||
return v.isoformat()
|
||||
if isinstance(v, dt.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
safe_details = []
|
||||
for item in details:
|
||||
safe_item = {k: _safe(v) for k, v in item.items()}
|
||||
safe_details.append(safe_item)
|
||||
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot, 'kb_sync_status': run.kb_sync_status, 'kb_sync_error': run.kb_sync_error, 'kb_document_id': run.kb_document_id})
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
run = db.session.get(ScheduleRun, run.id)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = duration_ms
|
||||
run.status = 'failed'
|
||||
run.error_message = str(e)
|
||||
db.session.commit()
|
||||
import traceback
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
return jsonify(list_tasks())
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||
@require_admin
|
||||
def export_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
payload = {'schema_version': 1, 'exported_at': datetime.utcnow().isoformat(), 'schedules': [_serialize_task_for_export(task, cfg_model)]}
|
||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||
@require_admin
|
||||
def import_schedules():
|
||||
data = request.get_json(silent=True) or {}
|
||||
schedules = data.get('schedules')
|
||||
if not isinstance(schedules, list):
|
||||
raise ValidationError('Invalid import file: schedules missing')
|
||||
user = get_current_user()
|
||||
imported = 0
|
||||
skipped = 0
|
||||
errors: list[str] = []
|
||||
for item in schedules:
|
||||
if not isinstance(item, dict):
|
||||
skipped += 1
|
||||
continue
|
||||
try:
|
||||
name = str(item.get('name') or '').strip()
|
||||
cron_expr = str(item.get('cron_expr') or '').strip()
|
||||
owner_user_id = int(item.get('owner_user_id'))
|
||||
if not name or not cron_expr:
|
||||
raise ValueError('name or cron_expr missing')
|
||||
existing = None
|
||||
schedule_no = str(item.get('schedule_no') or '').strip()
|
||||
if schedule_no:
|
||||
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
||||
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'schedule_timezone': item.get('schedule_timezone'), 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
|
||||
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
|
||||
if existing:
|
||||
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
|
||||
existing.data_source_type = task_payload['data_source_type']
|
||||
if cfg:
|
||||
upsert_schedule_task_config(existing.id, cfg)
|
||||
else:
|
||||
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, schedule_timezone=task_payload['schedule_timezone'], wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = task_payload['data_source_type']
|
||||
task.kb_sync_enabled = task_payload['kb_sync_enabled']
|
||||
task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None
|
||||
db.session.commit()
|
||||
if cfg:
|
||||
upsert_schedule_task_config(task.id, cfg)
|
||||
imported += 1
|
||||
except Exception as exc:
|
||||
errors.append(str(exc))
|
||||
skipped += 1
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||
@require_admin
|
||||
def post_schedule():
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
data_source_type = str(data.get('data_source_type') or 'database')
|
||||
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), schedule_timezone=data.get('schedule_timezone'), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
|
||||
task.data_source_type = data_source_type
|
||||
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
|
||||
raw_kb_group_id = data.get('kb_group_id')
|
||||
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
|
||||
if data_source_type == 'faq_hot_aggregate':
|
||||
task.platform_api_path = 'faq-aggregate-hot'
|
||||
else:
|
||||
task.platform_api_path = f'/{task.id}'
|
||||
db.session.commit()
|
||||
db.session.refresh(task)
|
||||
config_data = data.get('config')
|
||||
if config_data and data_source_type != 'faq_hot_aggregate':
|
||||
upsert_schedule_task_config(task.id, config_data)
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return (jsonify(serialize_task(task)), 201)
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def patch_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data)
|
||||
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all()
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.cron_util import normalize_cron_expr
|
||||
from app.services.schedule.query_service import serialize_task
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
from app.services.schedule.timezone_util import normalize_schedule_timezone
|
||||
|
||||
task.enabled = True
|
||||
if task.cron_expr:
|
||||
task.cron_expr = normalize_cron_expr(task.cron_expr)
|
||||
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
|
||||
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
||||
db.session.commit()
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
def disable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
task.next_run_at = None
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
user = get_current_user()
|
||||
existing = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running').first()
|
||||
if existing:
|
||||
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||
run = ScheduleRun(run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type='manual', triggered_by_user_id=getattr(user, 'id', None), started_at=datetime.utcnow(), status='running')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
def _background():
|
||||
with app.app_context():
|
||||
t = db.session.get(ScheduleTask, task_id)
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if not t or not r:
|
||||
return
|
||||
try:
|
||||
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||
except Exception as exc:
|
||||
try:
|
||||
r = db.session.get(ScheduleRun, run_id)
|
||||
if r and r.status == 'running':
|
||||
r.status = 'failed'
|
||||
r.error_message = str(exc)
|
||||
r.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||
t.start()
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_runs(task_id: int):
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
started_after = None
|
||||
started_before = None
|
||||
sa = request.args.get('started_after')
|
||||
sb = request.args.get('started_before')
|
||||
if sa:
|
||||
try:
|
||||
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
if sb:
|
||||
try:
|
||||
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
@@ -0,0 +1,412 @@
|
||||
"""
|
||||
api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:shipping_notice.tools、query_service、openapi_spec、tool_api_url、Flask Blueprint。
|
||||
逻辑:上游由 Dify/OpenAPI 或 RPA 请求进入本文件;本文件做轻量参数编排,再下沉到 services/shipping_notice/* workflow。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_by_no,
|
||||
get_focus_task_for_batch,
|
||||
get_task_by_ref,
|
||||
get_task_in_batch,
|
||||
list_batch_task_summaries,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||
|
||||
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_tool_auth() -> None:
|
||||
"""
|
||||
校验货代 Tool API 鉴权 Header。
|
||||
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
|
||||
|
||||
核心逻辑:对齐文件检核 Tool,只接受 `Authorization: Bearer <token>` 或
|
||||
`X-Integration-Key`,并统一使用 `INTEGRATION_API_KEY` 作为服务端校验值;
|
||||
未配置时报服务不可用,缺失或错误时报未授权。
|
||||
"""
|
||||
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
if not configured:
|
||||
raise ServiceUnavailableError(
|
||||
"INTEGRATION_API_KEY is not configured",
|
||||
code="missing_auth",
|
||||
)
|
||||
|
||||
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||
if configured in {token, integration_key}:
|
||||
return
|
||||
if not token and not integration_key:
|
||||
raise UnauthorizedError("missing_auth")
|
||||
raise UnauthorizedError("invalid_auth")
|
||||
|
||||
|
||||
def _tool_error_code(exc: AppError) -> str:
|
||||
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
|
||||
message = str(exc.message or "").strip()
|
||||
if message in {"missing_auth", "invalid_auth"}:
|
||||
return message
|
||||
if exc.code == "AUTH.UNAUTHORIZED":
|
||||
return "invalid_auth"
|
||||
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||
return "missing_auth"
|
||||
return exc.code
|
||||
|
||||
|
||||
@shipping_notice_bp.errorhandler(AppError)
|
||||
def _handle_tool_app_error(exc: AppError):
|
||||
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||
return jsonify({
|
||||
"ok": False,
|
||||
"error_code": _tool_error_code(exc),
|
||||
"message": exc.message,
|
||||
}), exc.http_status
|
||||
|
||||
|
||||
@shipping_notice_bp.before_request
|
||||
def _verify_tool_access():
|
||||
"""
|
||||
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
|
||||
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
|
||||
"""
|
||||
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||
return None
|
||||
_require_tool_auth()
|
||||
return None
|
||||
|
||||
|
||||
def _tool_api_base_url() -> str:
|
||||
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
|
||||
return resolve_tool_api_base_url()
|
||||
|
||||
|
||||
def _dify_openapi_spec() -> dict:
|
||||
return build_dify_openapi_spec(_tool_api_base_url())
|
||||
|
||||
|
||||
def _payload() -> dict:
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _generate_batch_no() -> str:
|
||||
from datetime import datetime
|
||||
|
||||
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
return jsonify(_dify_openapi_spec())
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/checkpoint-catalog", methods=["GET"])
|
||||
def checkpoint_catalog():
|
||||
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
|
||||
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
|
||||
|
||||
return jsonify(build_checkpoint_catalog())
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||
def openapi_dify_yaml():
|
||||
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
|
||||
import yaml
|
||||
|
||||
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
|
||||
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
|
||||
def tool_create_task():
|
||||
"""
|
||||
创建单个发货任务。
|
||||
【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/create_batch", methods=["POST"])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
创建或复用发货批次。
|
||||
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
|
||||
"""
|
||||
payload = _payload()
|
||||
if isinstance(payload.get("notice_items"), list) and payload.get("notice_items"):
|
||||
return jsonify(shipping_tools.create_batch_tasks(payload))
|
||||
batch_no = str(payload.get("batch_no") or "").strip()
|
||||
if batch_no:
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if batch:
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已复用批次 {batch.batch_no}",
|
||||
"data": serialize_batch_summary(batch),
|
||||
}
|
||||
)
|
||||
batch = shipping_tools.create_batch(payload)
|
||||
db.session.commit()
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已创建批次 {batch.batch_no}",
|
||||
"data": serialize_batch_summary(batch),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
|
||||
def tool_parse_notice():
|
||||
"""
|
||||
解析发货通知正文。
|
||||
【AI 触发时机】:当用户上传、粘贴或修正发货通知内容后,需要把文本转成任务单头和订单行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_notice(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/update_notice_fields", methods=["POST"])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
修改发货通知单头字段。
|
||||
【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_fields(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/update_notice_line", methods=["POST"])
|
||||
def tool_update_notice_line():
|
||||
"""
|
||||
修改指定订单行。
|
||||
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.update_notice_line(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/add_notice_line", methods=["POST"])
|
||||
def tool_add_notice_line():
|
||||
"""
|
||||
新增订单行。
|
||||
【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.add_notice_line(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/remove_notice_line", methods=["POST"])
|
||||
def tool_remove_notice_line():
|
||||
"""
|
||||
删除订单行。
|
||||
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.remove_notice_line(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"])
|
||||
def tool_parse_inventory():
|
||||
"""
|
||||
解析库存内容。
|
||||
【AI 触发时机】:当用户提供库存文本或表格内容,需要把库存转成系统可匹配格式时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
|
||||
def tool_upload_inventory_file():
|
||||
"""
|
||||
服务器侧接收库存 Excel 并解析。
|
||||
【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。
|
||||
"""
|
||||
task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip()
|
||||
upload = request.files.get("file")
|
||||
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
|
||||
def tool_get_inventory_schema_preview():
|
||||
"""
|
||||
获取库存表头预览。
|
||||
【AI 触发时机】:当 Agent 需要先看 Excel/表格列名,再决定 map_json 或提示用户确认映射时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"])
|
||||
def tool_apply_inventory_mapping():
|
||||
"""
|
||||
应用库存字段映射。
|
||||
【AI 触发时机】:当用户或 Agent 已确认列名与系统字段的对应关系,需要提交 map_json 时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
保证任务已取得库存数据。
|
||||
【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
|
||||
def tool_auto_progress():
|
||||
"""
|
||||
自动推进任务。
|
||||
【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
|
||||
def tool_match_inventory():
|
||||
"""
|
||||
执行库存匹配。
|
||||
【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.match_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"])
|
||||
def tool_submit_decision():
|
||||
"""
|
||||
提交人工决策。
|
||||
【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_decision(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"])
|
||||
def tool_generate_shipment_excel():
|
||||
"""
|
||||
生成出货 Excel。
|
||||
【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
|
||||
def tool_upload_to_freight():
|
||||
"""
|
||||
上传到货代系统或确认人工上传完成。
|
||||
【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.upload_to_freight(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
|
||||
def tool_get_task_status():
|
||||
"""
|
||||
查询任务状态。
|
||||
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_task_status(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/get_batch_status", methods=["POST"])
|
||||
def tool_get_batch_status():
|
||||
"""
|
||||
查询批次状态。
|
||||
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get("batch_no") or "").strip()
|
||||
if not batch_no:
|
||||
return jsonify({"status": "failed", "message": "batch_no is required"}), 400
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
return jsonify({"status": "failed", "message": "batch not found"}), 404
|
||||
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已获取批次 {batch.batch_no} 状态",
|
||||
"data": {
|
||||
**serialize_batch_summary(batch),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
"tasks": list_batch_task_summaries(batch),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tools/switch_focus_task", methods=["POST"])
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
切换批次当前焦点任务。
|
||||
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
|
||||
"""
|
||||
payload = _payload()
|
||||
batch_no = str(payload.get("batch_no") or "").strip()
|
||||
task_no = str(payload.get("task_no") or payload.get("target_task_no") or "").strip()
|
||||
if not batch_no or not task_no:
|
||||
return jsonify({"status": "failed", "message": "batch_no and task_no are required"}), 400
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
return jsonify({"status": "failed", "message": "batch not found"}), 404
|
||||
task = get_task_in_batch(batch_no, task_no)
|
||||
if not task:
|
||||
return jsonify({"status": "failed", "message": "task not found in batch"}), 404
|
||||
batch.current_focus_task_no = task.task_no
|
||||
db.session.commit()
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"task_no": task.task_no,
|
||||
"message": f"已切换当前任务到 {task.task_no}",
|
||||
"data": {
|
||||
"batch": serialize_batch_summary(batch),
|
||||
"focus_task": serialize_task_summary(task),
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
|
||||
def rpa_inventory_ready():
|
||||
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"])
|
||||
def rpa_upload_complete():
|
||||
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||
return jsonify(shipping_tools.rpa_report_upload(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
|
||||
def download_task_export(task_no: str):
|
||||
"""下载任务已生成的出货 Excel。"""
|
||||
task = get_task_by_ref(task_no)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
return jsonify({"error": err_msg}), 404
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=download_name,
|
||||
mimetype=EXPORT_MIME_TYPE,
|
||||
)
|
||||
@@ -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,
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
backend/app/api/tools/__init__.py
|
||||
|
||||
用途:Dify HTTP Tool API Blueprint 聚合。
|
||||
逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。
|
||||
"""
|
||||
from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401
|
||||
from app.api.tools.file_check import file_check_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp', 'file_check_bp']
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/api/tools/file_check.py
|
||||
|
||||
用途:文件检核 Tool API Blueprint(Wave 1 自 file_check_tools.py 迁入)。
|
||||
"""
|
||||
from app.api.file_check_tools import file_check_bp # noqa: F401
|
||||
|
||||
__all__ = ['file_check_bp']
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/api/tools/shipping_notice.py
|
||||
|
||||
用途:出货通知 Tool API Blueprint(Wave 1 自 shipping_notice_tools.py 迁入)。
|
||||
"""
|
||||
from app.api.shipping_notice_tools import shipping_notice_bp # noqa: F401
|
||||
|
||||
__all__ = ['shipping_notice_bp']
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,15 @@
|
||||
"""
|
||||
backend/app/api/workspace/__init__.py
|
||||
|
||||
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check)。
|
||||
逻辑:Wave 1 前 re-export 旧 workspace_* 模块。
|
||||
"""
|
||||
from app.api.workspace_schedule import workspace_schedule_bp # noqa: F401
|
||||
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp # noqa: F401
|
||||
from app.api.workspace_file_check import workspace_file_check_bp # noqa: F401
|
||||
|
||||
__all__ = [
|
||||
'workspace_schedule_bp',
|
||||
'workspace_shipping_notice_bp',
|
||||
'workspace_file_check_bp',
|
||||
]
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/api/workspace/file_check.py
|
||||
|
||||
用途:工作台文件检核路由(Wave 1 自 workspace_file_check.py 迁入)。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/api/workspace/schedule.py
|
||||
|
||||
用途:工作台排程路由(Wave 1 自 workspace_schedule.py 迁入)。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/api/workspace/shipping_notice.py
|
||||
|
||||
用途:工作台出货通知路由(Wave 1 自 workspace_shipping_notice.py 迁入)。
|
||||
"""
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
backend/app/api/workspace_file_check.py
|
||||
|
||||
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||
依赖:file_check_tools.chat_log_run_resolver、schedule.query_service。
|
||||
逻辑:前端按 chat_log_id / run_id 轮询检核批次状态与 Excel 链接。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import NotFoundError, UnauthorizedError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log
|
||||
from app.services.schedule.query_service import get_run, serialize_run
|
||||
|
||||
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def serialize_file_judgement(payload: dict) -> dict:
|
||||
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
|
||||
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
|
||||
judgement = response_summary.get("file_judgement")
|
||||
if not isinstance(judgement, dict):
|
||||
judgement = {}
|
||||
return {
|
||||
"qualified_count": int(judgement.get("qualified_count") or 0),
|
||||
"unqualified_count": int(judgement.get("unqualified_count") or 0),
|
||||
"manual_count": int(judgement.get("manual_count") or 0),
|
||||
"dify_error_count": int(judgement.get("dify_error_count") or 0),
|
||||
"invalid_result_count": int(judgement.get("invalid_result_count") or 0),
|
||||
}
|
||||
|
||||
|
||||
def serialize_current_step(payload: dict) -> dict | None:
|
||||
response_summary = payload.get("response_summary_json") if isinstance(payload.get("response_summary_json"), dict) else {}
|
||||
current_step = response_summary.get("current_step") if isinstance(response_summary.get("current_step"), dict) else None
|
||||
if not current_step:
|
||||
return None
|
||||
return {
|
||||
"step": str(current_step.get("step") or ""),
|
||||
"label": str(current_step.get("label") or current_step.get("step") or ""),
|
||||
"row_id": current_step.get("row_id"),
|
||||
"started_at": current_step.get("started_at"),
|
||||
"processed_count": int(current_step.get("processed_count") or 0),
|
||||
"success_count": int(current_step.get("success_count") or 0),
|
||||
"failed_count": int(current_step.get("failed_count") or 0),
|
||||
"skipped_count": int(current_step.get("skipped_count") or 0),
|
||||
}
|
||||
|
||||
|
||||
def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
payload = serialize_run(run)
|
||||
total = int(payload.get("total_count") or 0)
|
||||
success = int(payload.get("success_count") or 0)
|
||||
failed = int(payload.get("failed_count") or 0)
|
||||
skipped = int(payload.get("skipped_count") or 0)
|
||||
processed = success + failed + skipped
|
||||
percent = int(round((processed / total) * 100)) if total > 0 else 0
|
||||
percent = max(0, min(percent, 100))
|
||||
return {
|
||||
"run_id": payload["id"],
|
||||
"run_no": payload["run_no"],
|
||||
"task_id": payload["schedule_task_id"],
|
||||
"title": payload.get("schedule_name") or "",
|
||||
"status": payload["status"],
|
||||
"total_count": total,
|
||||
"processed_count": processed,
|
||||
"success_count": success,
|
||||
"failed_count": failed,
|
||||
"skipped_count": skipped,
|
||||
"judgement": serialize_file_judgement(payload),
|
||||
"current_step": serialize_current_step(payload),
|
||||
"progress_percent": percent,
|
||||
"started_at": payload.get("started_at"),
|
||||
"finished_at": payload.get("finished_at"),
|
||||
"duration_ms": payload.get("duration_ms"),
|
||||
"error_message": payload.get("error_message"),
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": f"/api/workspace/file-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
"group_id": payload.get("kb_group_id"),
|
||||
"document_id": payload.get("kb_document_id"),
|
||||
"document_version_id": payload.get("kb_document_version_id"),
|
||||
"sync_job_id": payload.get("kb_sync_job_id"),
|
||||
"error_message": payload.get("kb_sync_error"),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-log", methods=["GET"])
|
||||
def workspace_file_check_run_for_log():
|
||||
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
chat_log_id = request.args.get("chat_log_id", type=int)
|
||||
if not task_id or task_id <= 0:
|
||||
return jsonify({"ok": False, "error": "task_id_required"}), 400
|
||||
if not chat_log_id or chat_log_id <= 0:
|
||||
return jsonify({"ok": False, "error": "chat_log_id_required"}), 400
|
||||
|
||||
run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id)
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"run": _serialize_progress_run(run) if run else None,
|
||||
"match_source": "chat_log" if run else None,
|
||||
})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/for-session", methods=["GET"])
|
||||
def workspace_file_check_run_for_session():
|
||||
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
|
||||
_require_user()
|
||||
return jsonify({"ok": True, "run": None, "match_source": None, "session_updated_at": None})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/active", methods=["GET"])
|
||||
def workspace_file_check_active_run():
|
||||
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||
_require_user()
|
||||
task_id = request.args.get("task_id", type=int)
|
||||
conversation_id = str(request.args.get("conversation_id") or "").strip()
|
||||
query = (
|
||||
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
||||
.filter(ScheduleRun.status == "running")
|
||||
)
|
||||
if task_id is not None:
|
||||
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||
rows = query.order_by(ScheduleRun.id.desc()).all()
|
||||
if task_id is not None:
|
||||
run = rows[0] if rows else None
|
||||
else:
|
||||
run = next((
|
||||
row for row in rows
|
||||
if (
|
||||
not conversation_id
|
||||
or str((row.api_request_json or {}).get("conversation_id") or "").strip() == conversation_id
|
||||
)
|
||||
), None)
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run) if run else None})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>", methods=["GET"])
|
||||
def workspace_file_check_run_detail(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run)})
|
||||
|
||||
|
||||
@workspace_file_check_bp.route("/file-check/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_file_check_run_excel(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError("excel_not_found")
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or f"{run.run_no}.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -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.replace('Z', '+00:00')) if started_after_str else None
|
||||
started_before = datetime.fromisoformat(started_before_str.replace('Z', '+00:00')) if started_before_str else None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return jsonify(list_runs(notify_user_id=user.id, schedule_name=schedule_name, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
def workspace_schedule_run_detail(run_id: int):
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError('Forbidden')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
def workspace_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError('Not found')
|
||||
if not can_view_run(run, user.id):
|
||||
raise ForbiddenError('Forbidden')
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError('Excel not found')
|
||||
buf = BytesIO(run.excel_file_data)
|
||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||
@@ -0,0 +1,682 @@
|
||||
"""
|
||||
api/workspace_shipping_notice.py
|
||||
|
||||
用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||
依赖:auth_jwt、query_service、shipping_notice.tools、notice_upload、chat_actions。
|
||||
逻辑:前端通过本 Blueprint 访问用户鉴权路由;本文件做权限校验与参数编排,再调用 shipping_notice service/workflow 返回页面所需数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
get_batch_for_user,
|
||||
get_focus_task_for_batch,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
list_tasks_for_batch,
|
||||
list_tasks_for_user,
|
||||
resolve_task_export_download,
|
||||
serialize_batch_summary,
|
||||
serialize_task_detail,
|
||||
serialize_task_summary,
|
||||
task_export_error_message,
|
||||
)
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
"""校验当前请求用户,统一返回 `(user, error_response)` 结构。"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return None, (jsonify({"error": "Unauthorized"}), 401)
|
||||
return user, None
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
|
||||
def workspace_shipping_tasks():
|
||||
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch_no = str(request.args.get("batch_no") or "").strip() or None
|
||||
process_status = str(request.args.get("process_status") or "").strip() or None
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches", methods=["GET"])
|
||||
def workspace_shipping_batches():
|
||||
"""列出当前用户的发货批次摘要。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
limit = int(request.args.get("limit") or 100)
|
||||
return jsonify(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/create-from-notices", methods=["POST"])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
|
||||
uploads = request.files.getlist("files")
|
||||
if not uploads:
|
||||
single = request.files.get("file")
|
||||
if single:
|
||||
uploads = [single]
|
||||
if not uploads:
|
||||
return jsonify({"error": "files is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
extract_notice_text,
|
||||
guess_source_type,
|
||||
max_notice_chars,
|
||||
save_task_notice_upload,
|
||||
)
|
||||
|
||||
conversation_id = str(request.form.get("conversation_id") or "").strip()
|
||||
notice_items: list[dict] = []
|
||||
for upload in uploads:
|
||||
raw = upload.read() or b""
|
||||
filename = upload.filename or "notice"
|
||||
source_type = guess_source_type(filename)
|
||||
text = ""
|
||||
warnings: list[str] = []
|
||||
try:
|
||||
temp_task_no = f"TMP-{len(notice_items) + 1}"
|
||||
saved_path = save_task_notice_upload(temp_task_no, filename, raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
|
||||
except Exception as exc:
|
||||
warnings = [f"notice_extract_failed:{exc}"]
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
warnings.append(f"notice_text_truncated:{limit}")
|
||||
notice_items.append(
|
||||
{
|
||||
"source_type": source_type,
|
||||
"source_file_name": filename,
|
||||
"source_file_type": str(getattr(upload, "mimetype", "") or "").strip() or None,
|
||||
"raw_text": text,
|
||||
"warnings": warnings,
|
||||
}
|
||||
)
|
||||
|
||||
payload = {
|
||||
"user_id": user.id,
|
||||
"conversation_id": conversation_id or None,
|
||||
"file_count": len(notice_items),
|
||||
"notice_items": notice_items,
|
||||
# 上传接口先快速完成建批/建任务与 raw_text 落库,避免请求阻塞;
|
||||
# 后续首轮解析与可自动推进步骤交给后台编排线程逐票执行。
|
||||
"defer_parse": True,
|
||||
}
|
||||
created = shipping_tools.create_batch_tasks(payload)
|
||||
data = created.get("data") if isinstance(created, dict) else None
|
||||
batch_data = data.get("batch") if isinstance(data, dict) else None
|
||||
tasks_data = data.get("tasks") if isinstance(data, dict) else None
|
||||
batch_no = str(created.get("batch_no") or (batch_data or {}).get("batch_no") or "").strip()
|
||||
orchestrator_started = False
|
||||
if batch_no:
|
||||
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
|
||||
|
||||
orchestrator_started = start_batch_orchestrator(batch_no)
|
||||
if isinstance(data, dict) and batch_no:
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if focus_task:
|
||||
data["focus_task"] = serialize_task_summary(focus_task)
|
||||
if isinstance(tasks_data, list):
|
||||
data["tasks"] = tasks_data
|
||||
data["orchestrator_started"] = orchestrator_started
|
||||
if isinstance(created, dict):
|
||||
base_message = str(created.get("message") or "").strip()
|
||||
if orchestrator_started:
|
||||
created["message"] = (
|
||||
f"{base_message},后台已开始逐票处理。"
|
||||
if base_message
|
||||
else "后台已开始逐票处理。"
|
||||
)
|
||||
return jsonify(created)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>", methods=["GET"])
|
||||
def workspace_shipping_batch_detail(batch_no: str):
|
||||
"""返回批次详情、批次内任务列表和当前焦点任务。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
return jsonify(
|
||||
{
|
||||
**serialize_batch_summary(batch),
|
||||
"tasks": list_tasks_for_batch(batch_no, user.id),
|
||||
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/tasks", methods=["GET"])
|
||||
def workspace_shipping_batch_tasks(batch_no: str):
|
||||
"""返回指定批次下的任务列表。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(list_tasks_for_batch(batch_no, user.id))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["GET"])
|
||||
def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
"""返回指定批次当前焦点任务的摘要。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||
if not focus_task:
|
||||
return jsonify({"error": "Focus task not found"}), 404
|
||||
return jsonify(serialize_task_summary(focus_task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["POST"])
|
||||
def workspace_switch_shipping_batch_focus_task(batch_no: str):
|
||||
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_no = str(data.get("task_no") or data.get("target_task_no") or "").strip()
|
||||
if not task_no:
|
||||
return jsonify({"error": "task_no is required"}), 400
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task or task.batch_id != batch.id:
|
||||
return jsonify({"error": "Task not found in batch"}), 404
|
||||
batch.current_focus_task_no = task.task_no
|
||||
db.session.commit()
|
||||
return jsonify(
|
||||
{
|
||||
"batch": serialize_batch_summary(batch),
|
||||
"focus_task": serialize_task_summary(task),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
|
||||
def workspace_create_shipping_task():
|
||||
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {"user_id": user.id}
|
||||
source_type = str(data.get("source_type") or "").strip()
|
||||
if source_type:
|
||||
payload["source_type"] = source_type
|
||||
conversation_id = str(data.get("conversation_id") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
raw_content = str(data.get("raw_content") or "").strip()
|
||||
if raw_content:
|
||||
payload["raw_content"] = raw_content
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.create_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
|
||||
upload = request.files.get("file")
|
||||
if not upload:
|
||||
return jsonify({"error": "file is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
extract_notice_text,
|
||||
guess_source_type,
|
||||
max_notice_chars,
|
||||
save_task_notice_upload,
|
||||
)
|
||||
|
||||
source_type = guess_source_type(upload.filename or "")
|
||||
conversation_id = str(request.form.get("conversation_id") or "").strip()
|
||||
payload = {"user_id": user.id, "source_type": source_type}
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
created = shipping_tools.create_task(payload)
|
||||
task_id = str(created.get("task_id") or "").strip()
|
||||
if not task_id:
|
||||
return jsonify({"error": "failed to create task"}), 500
|
||||
|
||||
raw = upload.read() or b""
|
||||
saved_path = save_task_notice_upload(task_id, upload.filename or "notice", raw)
|
||||
text, meta = extract_notice_text(saved_path)
|
||||
if not text:
|
||||
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"status": "needs_human",
|
||||
"task_id": task_id,
|
||||
"message": "未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。",
|
||||
"data": {"notice_upload": {"filename": upload.filename or "", **meta}},
|
||||
"human_options": ["reparse", "reject"],
|
||||
"checkpoint": CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
"action_buttons": action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED),
|
||||
}
|
||||
)
|
||||
|
||||
if text:
|
||||
limit = max_notice_chars()
|
||||
if len(text) > limit:
|
||||
text = text[:limit]
|
||||
meta.setdefault("warnings", []).append(f"notice_text_truncated:{limit}")
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.raw_content = text
|
||||
db.session.commit()
|
||||
|
||||
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||
if task:
|
||||
task.source_file_name = str(upload.filename or "").strip() or task.source_file_name
|
||||
task.source_file_type = str(getattr(upload, "mimetype", "") or "").strip() or task.source_file_type
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||
|
||||
orchestrator_started = start_task_orchestrator(task_id)
|
||||
return jsonify(
|
||||
{
|
||||
"status": "ok",
|
||||
"task_id": task_id,
|
||||
"message": (
|
||||
f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。"
|
||||
if orchestrator_started
|
||||
else f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存。"
|
||||
),
|
||||
"data": {
|
||||
"task": serialize_task_summary(task) if task else {"task_no": task_id},
|
||||
"notice_upload": {"filename": upload.filename or "", **meta},
|
||||
"parse_status": "deferred",
|
||||
"orchestrator_started": orchestrator_started,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>", methods=["GET"])
|
||||
def workspace_shipping_task_detail(task_no: str):
|
||||
"""返回指定任务的详情快照。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(serialize_task_detail(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/chat-actions", methods=["GET"])
|
||||
def workspace_shipping_task_chat_actions(task_no: str):
|
||||
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
return jsonify(build_chat_actions_payload(task))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/retry", methods=["POST"])
|
||||
def workspace_retry_shipping_task(task_no: str):
|
||||
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload = {"task_id": task.task_no}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.retry_task(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/upload-inventory", methods=["POST"])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
upload = request.files.get("file")
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/apply-inventory-mapping", methods=["POST"])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
map_json = data.get(MAP_JSON)
|
||||
if not isinstance(map_json, dict) or not map_json:
|
||||
return jsonify({"error": f"{MAP_JSON} is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/submit-decision", methods=["POST"])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
decision = str(data.get("decision") or "").strip()
|
||||
if not decision:
|
||||
return jsonify({"error": "decision is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "decision": decision, AUTO_CHAIN_FALLBACK: True}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.submit_decision(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-fields", methods=["POST"])
|
||||
def workspace_update_shipping_notice_fields(task_no: str):
|
||||
"""更新发货通知单头字段。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
fields = data.get("fields")
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
return jsonify({"error": "fields is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "fields": fields}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.update_notice_fields(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-line", methods=["POST"])
|
||||
def workspace_update_shipping_notice_line(task_no: str):
|
||||
"""更新发货通知中的指定订单行。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get("line_index"))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"error": "line_index is required"}), 400
|
||||
patch = data.get("patch")
|
||||
if not isinstance(patch, dict) or not patch:
|
||||
return jsonify({"error": "patch is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "line_index": line_index, "patch": patch}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.update_notice_line(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/add-notice-line", methods=["POST"])
|
||||
def workspace_add_shipping_notice_line(task_no: str):
|
||||
"""为发货通知新增订单行。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
line = data.get("line")
|
||||
if not isinstance(line, dict) or not line:
|
||||
return jsonify({"error": "line is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "line": line}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.add_notice_line(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/remove-notice-line", methods=["POST"])
|
||||
def workspace_remove_shipping_notice_line(task_no: str):
|
||||
"""删除发货通知中的指定订单行。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
line_index = int(data.get("line_index"))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({"error": "line_index is required"}), 400
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
payload = {"task_id": task.task_no, "line_index": line_index}
|
||||
comment = str(data.get("comment") or "").strip()
|
||||
if comment:
|
||||
payload["comment"] = comment
|
||||
return jsonify(shipping_tools.remove_notice_line(payload))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/auto-progress", methods=["POST"])
|
||||
def workspace_auto_progress_shipping_task(task_no: str):
|
||||
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
payload: dict = {"task_id": task.task_no}
|
||||
for key in ("lang", "locale", "language"):
|
||||
if data.get(key):
|
||||
payload[key] = data[key]
|
||||
break
|
||||
result = shipping_tools.auto_progress(payload)
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
gen_data = result.get("data")
|
||||
if isinstance(gen_data, dict) and gen_data.get("export_file_path"):
|
||||
gen_data = {**gen_data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"}
|
||||
result = {**result, "data": gen_data}
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
|
||||
def workspace_match_shipping_inventory(task_no: str):
|
||||
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
action_buttons_for_checkpoint,
|
||||
human_options_for_checkpoint,
|
||||
)
|
||||
|
||||
matched = shipping_tools.match_inventory({"task_id": task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||
if not isinstance(matched, dict):
|
||||
return jsonify(matched)
|
||||
data = matched.get("data")
|
||||
if isinstance(data, dict) and data.get("export_file_path"):
|
||||
matched = {
|
||||
**matched,
|
||||
"data": {**data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"},
|
||||
}
|
||||
checkpoint = matched.get("checkpoint") or CP_EXPORT_GENERATED
|
||||
if matched.get("status") == "ok" and data and data.get("export_file_path"):
|
||||
matched["checkpoint"] = checkpoint
|
||||
if "human_options" not in matched:
|
||||
options = human_options_for_checkpoint(checkpoint)
|
||||
if options is not None:
|
||||
matched["human_options"] = options
|
||||
if "action_buttons" not in matched:
|
||||
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||
if buttons:
|
||||
matched["action_buttons"] = buttons
|
||||
return jsonify(matched)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
return jsonify(
|
||||
shipping_tools.upload_to_freight({"task_id": task.task_no, "mode": "manual_confirm"})
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
|
||||
def workspace_generate_shipping_excel(task_no: str):
|
||||
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
result = shipping_tools.generate_excel({"task_id": task.task_no})
|
||||
if isinstance(result, dict) and result.get("status") == "ok":
|
||||
data = result.get("data")
|
||||
if not isinstance(data, dict):
|
||||
data = {}
|
||||
result["data"] = data
|
||||
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
return jsonify({"error": err_msg}), 404
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
return send_file(
|
||||
path,
|
||||
as_attachment=True,
|
||||
download_name=download_name,
|
||||
mimetype=EXPORT_MIME_TYPE,
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/retry-pending", methods=["POST"])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
batch = get_batch_for_user(batch_no, user.id)
|
||||
if not batch:
|
||||
return jsonify({"error": "Not found"}), 404
|
||||
|
||||
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||
|
||||
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||
@@ -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')
|
||||
@@ -0,0 +1 @@
|
||||
"""FAQ CLI 包。"""
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
backend/app/cli/faq_commands.py
|
||||
|
||||
用途:FAQ 相关 Flask CLI 命令注册。
|
||||
依赖:HotFaqAggregator、Flask click。
|
||||
逻辑:create_app 时 init_app 注册 faq-aggregate-hot 命令。
|
||||
"""
|
||||
import click
|
||||
from flask.cli import with_appcontext
|
||||
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
|
||||
@click.command('faq-aggregate-hot')
|
||||
@click.option('--agent-id', type=int, default=None, help='仅聚合指定 Agent')
|
||||
@click.option('--dry-run', is_flag=True, help='只统计不写 PostgreSQL')
|
||||
@with_appcontext
|
||||
def faq_aggregate_hot(agent_id: int | None, dry_run: bool):
|
||||
"""
|
||||
离线聚合 ChatLog 热点 FAQ 候选并写入 faq_hot_candidates 表。
|
||||
核心逻辑:委托 HotFaqAggregator.aggregate_hot_faq_candidates。
|
||||
"""
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
if not result.get('enabled'):
|
||||
click.echo(result.get('message', 'FAQ hot aggregation disabled'))
|
||||
return
|
||||
|
||||
click.echo(
|
||||
f"scanned={result['scanned_logs']} groups={result['group_count']} "
|
||||
f"promoted={result['promoted_count']} skipped={result['skipped_count']} dry_run={dry_run}"
|
||||
)
|
||||
for item in result.get('candidates', [])[:20]:
|
||||
click.echo(
|
||||
f" [{item.get('agent_name')}] {item.get('canonical_query')} "
|
||||
f"asks={item.get('ask_count_7d')} users={item.get('user_count_7d')} "
|
||||
f"dominance={item.get('answer_dominance')}"
|
||||
)
|
||||
if len(result.get('candidates', [])) > 20:
|
||||
click.echo(f" ... and {len(result['candidates']) - 20} more")
|
||||
|
||||
|
||||
def init_app(app):
|
||||
"""向 Flask app 注册 FAQ CLI 命令。"""
|
||||
app.cli.add_command(faq_aggregate_hot)
|
||||
+315
-102
@@ -1,112 +1,325 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
"""
|
||||
backend/app/config.py
|
||||
配置类,区分开发/生产环境
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import Field, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _load_environment_files() -> str:
|
||||
"""Load env files from project root with stable priority.
|
||||
|
||||
Priority (low -> high):
|
||||
1. .env.shared
|
||||
2. .env.<ENV_NAME>
|
||||
3. .env.local (only for dev)
|
||||
4. system environment variables (always highest, never overridden)
|
||||
"""
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
shared_file = _ROOT_DIR / '.env.shared'
|
||||
if shared_file.exists():
|
||||
load_dotenv(shared_file, override=False)
|
||||
|
||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||
if env_file.exists():
|
||||
load_dotenv(env_file, override=True)
|
||||
|
||||
if env_name == 'dev':
|
||||
local_file = _ROOT_DIR / '.env.local'
|
||||
if local_file.exists():
|
||||
load_dotenv(local_file, override=True)
|
||||
return env_name
|
||||
|
||||
|
||||
ACTIVE_ENV_NAME = _load_environment_files()
|
||||
|
||||
|
||||
def _data_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath("data", *parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
def _backend_path(env_key: str, *parts: str) -> str:
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = _BACKEND_DIR.joinpath(*parts)
|
||||
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
|
||||
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
'max_overflow': 10,
|
||||
'pool_recycle': 3600,
|
||||
'pool_pre_ping': True,
|
||||
}
|
||||
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
|
||||
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||
'OA_WORKFLOW_WSDL_URL',
|
||||
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 共用;无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||
|
||||
# 货代发货通知 Agent Tool API
|
||||
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||
|
||||
# 文件检核 Chatflow Tool API
|
||||
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
|
||||
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
|
||||
)
|
||||
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
|
||||
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
|
||||
)
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '3'
|
||||
)
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
|
||||
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||
'shipment_{task_no}_{ts}.xlsx',
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||
)
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path("FREIGHT_INVENTORY_DROP_DIR", "freight_rpa", "inventory_drop")
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "freight_rpa", "inventory_triggers"
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path("FREIGHT_UPLOAD_QUEUE_DIR", "freight_rpa", "upload_queue")
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "freight_rpa", "upload_triggers"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
)
|
||||
|
||||
app_name: str = "Document Cleaning"
|
||||
api_prefix: str = "/api"
|
||||
jwt_secret: str = "change-me-in-production"
|
||||
jwt_algorithm: str = "HS256"
|
||||
access_token_expire_minutes: int = 720
|
||||
# WeCom (企业微信) 登录配置
|
||||
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||
WECOM_AGENT_ID = os.getenv('WECOM_AGENT_ID')
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
database_backend: Literal["sqlite", "postgres"] = "sqlite"
|
||||
database_url: str = ""
|
||||
sqlite_database_url: str = "sqlite:///./document_cleaning.db"
|
||||
postgres_database_url: str = "postgresql+psycopg://postgres:postgres@localhost:5432/document_cleaning"
|
||||
redis_url: str = "redis://redis:6379/0"
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
AUTH_JWT_REQUIRED = os.getenv('AUTH_JWT_REQUIRED', 'true').lower() == 'true'
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN = os.getenv('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', 'true').lower() == 'true'
|
||||
# Login mode switch: "casdoor" (default) or "password".
|
||||
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
|
||||
# password: keep legacy local username/password login.
|
||||
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
|
||||
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
|
||||
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
|
||||
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
|
||||
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE')
|
||||
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL')
|
||||
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
|
||||
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
|
||||
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
|
||||
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
|
||||
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
|
||||
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||
# Casdoor organization (userOwner) for set-password and other management APIs.
|
||||
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
|
||||
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
|
||||
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||
SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '')
|
||||
SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '')
|
||||
SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server')
|
||||
SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no')
|
||||
SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes')
|
||||
SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15'))
|
||||
SMTP_HOST = os.getenv('SMTP_HOST', '')
|
||||
SMTP_PORT = int(os.getenv('SMTP_PORT', '25'))
|
||||
SMTP_USER = os.getenv('SMTP_USER', '')
|
||||
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
|
||||
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
|
||||
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
|
||||
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
|
||||
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
|
||||
)
|
||||
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
|
||||
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
|
||||
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
|
||||
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
|
||||
)
|
||||
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
|
||||
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
|
||||
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
|
||||
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
|
||||
str(_ROOT_DIR / 'docs'),
|
||||
)
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
|
||||
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
|
||||
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
|
||||
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
|
||||
|
||||
data_root: Path = Field(default=Path("./data"))
|
||||
public_base_url: str = "http://192.168.100.230:8891"
|
||||
allowed_origins: str = "http://192.168.100.230:8891,http://localhost:5173"
|
||||
|
||||
dify_base_url: str = "https://api.dify.ai/v1"
|
||||
dify_api_key: str = ""
|
||||
dify_permission: str = "all_team_members"
|
||||
|
||||
default_indexing_technique: str = "high_quality"
|
||||
default_search_method: str = "hybrid_search"
|
||||
default_doc_form: str = "text_model"
|
||||
default_embedding_model_provider: str = ""
|
||||
default_embedding_model: str = ""
|
||||
default_reranking_model_provider: str = ""
|
||||
default_reranking_model: str = ""
|
||||
default_top_k: int = 5
|
||||
default_score_threshold_enabled: bool = True
|
||||
default_score_threshold: float = 0.35
|
||||
|
||||
default_admin_username: str = "admin"
|
||||
default_admin_password: str = "admin123456"
|
||||
default_admin_name: str = "System Admin"
|
||||
integration_api_key: str = ""
|
||||
integration_download_secret: str = ""
|
||||
integration_download_expire_minutes: int = 15
|
||||
|
||||
rq_queue_name: str = "document-cleaning"
|
||||
rq_default_timeout: int = 3600
|
||||
task_execution_mode: Literal["rq", "sync"] = "rq"
|
||||
dify_sync_max_retries: int = 4
|
||||
dify_sync_retry_schedule: str = "30,60,120,300"
|
||||
dify_sync_cooldown_seconds: int = 60
|
||||
watchdog_stale_sync_timeout_seconds: int = 900
|
||||
watchdog_stale_convert_timeout_seconds: int = 900
|
||||
watchdog_convert_orphan_grace_seconds: int = 120
|
||||
|
||||
edkb_word_timeout_sec: int = 120
|
||||
edkb_file_timeout_sec: int = 900
|
||||
|
||||
def origins_list(self) -> list[str]:
|
||||
return [item.strip() for item in self.allowed_origins.split(",") if item.strip()]
|
||||
|
||||
def dify_sync_retry_delays(self) -> list[int]:
|
||||
values: list[int] = []
|
||||
for raw in self.dify_sync_retry_schedule.split(","):
|
||||
token = raw.strip()
|
||||
if not token:
|
||||
continue
|
||||
try:
|
||||
parsed = int(token)
|
||||
except ValueError:
|
||||
continue
|
||||
if parsed > 0:
|
||||
values.append(parsed)
|
||||
return values or [30, 60, 120, 300]
|
||||
|
||||
@staticmethod
|
||||
def _normalize_database_url(url: str) -> str:
|
||||
normalized = url.strip()
|
||||
if normalized.startswith("postgresql://"):
|
||||
return normalized.replace("postgresql://", "postgresql+psycopg://", 1)
|
||||
return normalized
|
||||
|
||||
@model_validator(mode="after")
|
||||
def resolve_database_url(self) -> "Settings":
|
||||
if self.database_url:
|
||||
self.database_url = self._normalize_database_url(self.database_url)
|
||||
return self
|
||||
|
||||
selected = self.sqlite_database_url if self.database_backend == "sqlite" else self.postgres_database_url
|
||||
self.database_url = self._normalize_database_url(selected)
|
||||
return self
|
||||
|
||||
def ensure_data_dirs(self) -> None:
|
||||
for name in ["original", "markdown", "assets", "jobs", "tmp"]:
|
||||
(self.data_root / name).mkdir(parents=True, exist_ok=True)
|
||||
# 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')
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
settings = Settings()
|
||||
settings.ensure_data_dirs()
|
||||
return settings
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
SCHEDULE_WORKER_ENABLED = False
|
||||
FIXED_ASSETS_SYNC_ENABLED = False
|
||||
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||
|
||||
|
||||
config = {
|
||||
'dev': DevelopmentConfig,
|
||||
'development': DevelopmentConfig,
|
||||
'test': TestingConfig,
|
||||
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
||||
'prod': ProductionConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/core/__init__.py
|
||||
|
||||
用途:横切能力包入口(errors、response、auth、config、db)。
|
||||
逻辑:Wave 1 逐步将 app 根目录模块迁入 core/ 子包;过渡期旧路径 re-export。
|
||||
"""
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/core/auth/__init__.py
|
||||
|
||||
用途:认证与当前用户解析包入口。
|
||||
逻辑:api 层通过 get_current_user 获取 User;Wave 1 自 auth_jwt.py 迁入 jwt.py。
|
||||
"""
|
||||
@@ -0,0 +1,39 @@
|
||||
"""
|
||||
backend/app/core/auth/context.py
|
||||
|
||||
用途:从 Flask g/request 解析请求上下文(request_id、user),供 api 层薄封装。
|
||||
逻辑:Wave 3 拆分 user/chat 路由时,将重复 auth 逻辑收敛到本模块。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def get_request_id() -> str | None:
|
||||
"""
|
||||
读取当前请求的 X-Request-Id 或 g.request_id。
|
||||
核心逻辑:延迟 import flask.g,避免 services 层依赖。
|
||||
Returns:
|
||||
request_id 字符串,无上下文时返回 None。
|
||||
"""
|
||||
try:
|
||||
from flask import g
|
||||
|
||||
return getattr(g, 'request_id', None)
|
||||
except RuntimeError:
|
||||
return None
|
||||
|
||||
|
||||
def get_optional_config(key: str, default: Any = None) -> Any:
|
||||
"""
|
||||
读取 Flask app.config 项(仅 api / jobs context 使用)。
|
||||
Args:
|
||||
key: config 键名。
|
||||
default: 无 app context 时的默认值。
|
||||
"""
|
||||
try:
|
||||
from flask import current_app
|
||||
|
||||
return current_app.config.get(key, default)
|
||||
except RuntimeError:
|
||||
return default
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/core/auth/jwt.py
|
||||
|
||||
用途:Casdoor JWT 校验与当前用户解析(Wave 1 自 app/auth_jwt.py 迁入)。
|
||||
逻辑:api 路由与 decorators 调用 get_current_user()。
|
||||
"""
|
||||
from app.auth_jwt import get_current_user # noqa: F401
|
||||
|
||||
__all__ = ['get_current_user']
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/core/config/__init__.py
|
||||
|
||||
用途:应用配置包入口(settings、env_persistence)。
|
||||
逻辑:create_app 加载 Config;before_request 刷新 DB 持久化配置。
|
||||
"""
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/core/config/env_persistence.py
|
||||
|
||||
用途:DB 持久化运行时配置(Wave 1 自 app/env_persistence.py 迁入)。
|
||||
逻辑:before_request 调用 apply_env_settings 刷新 app.config。
|
||||
"""
|
||||
from app.env_persistence import apply_env_settings # noqa: F401
|
||||
|
||||
__all__ = ['apply_env_settings']
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/core/config/settings.py
|
||||
|
||||
用途:Config 类与环境映射(Wave 1 自 app/config.py 迁入)。
|
||||
逻辑:create_app(config_name) 通过 config[config_name] 加载。
|
||||
"""
|
||||
from app.config import ACTIVE_ENV_NAME, config # noqa: F401
|
||||
|
||||
__all__ = ['config', 'ACTIVE_ENV_NAME']
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/core/db/__init__.py
|
||||
|
||||
用途:数据库会话工具包入口。
|
||||
逻辑:Wave 1 提供 run_with_retry;sequence 工具供迁移/运维脚本使用。
|
||||
"""
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
backend/app/core/db/sequence.py
|
||||
|
||||
用途:PostgreSQL 序列修复工具(Wave 1 自 services/db_sequence.py 迁入)。
|
||||
逻辑:迁移脚本与 check_schema_drift 调用。
|
||||
"""
|
||||
from app.services.db_sequence import * # noqa: F403
|
||||
@@ -0,0 +1,28 @@
|
||||
"""
|
||||
backend/app/core/db/session.py
|
||||
|
||||
用途:数据库会话辅助(重试、只读查询封装)。
|
||||
逻辑:Wave 1 从 api/user.py、knowledge_base.py 等抽取 _run_db_with_retry 模式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import TypeVar
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
|
||||
def run_with_retry(fn: Callable[[], T], *, max_attempts: int = 3) -> T:
|
||||
"""
|
||||
在数据库短暂失败时重试可调用对象。
|
||||
核心逻辑:捕获 OperationalError/DisconnectionError 后 rollback 并重试。
|
||||
Args:
|
||||
fn: 无参 callable,内部使用 db.session。
|
||||
max_attempts: 最大尝试次数。
|
||||
Returns:
|
||||
fn 的返回值。
|
||||
Raises:
|
||||
最后一次失败的异常。
|
||||
"""
|
||||
# [STEP 1] Wave 0 占位:Wave 1 从 user.py / knowledge_base.py 抽取实现
|
||||
return fn()
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/core/decorators.py
|
||||
|
||||
用途:路由权限装饰器(Wave 1 自 app/decorators.py 迁入)。
|
||||
逻辑:api 层路由使用 @require_admin、@require_agent_permission。
|
||||
"""
|
||||
from app.decorators import require_admin, require_agent_permission # noqa: F401
|
||||
|
||||
__all__ = ['require_admin', 'require_agent_permission']
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
backend/app/core/errors.py
|
||||
|
||||
用途:统一业务异常类型(Wave 1 自 app/errors.py 迁入)。
|
||||
依赖:无 Flask 依赖。
|
||||
逻辑:API 全局 handler 识别 AppError;业务层 raise 子类替代 jsonify(error)。
|
||||
"""
|
||||
from app.errors import ( # noqa: F401 — Wave 1: 实现迁入本文件后删除 app/errors.py shim
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'AppError',
|
||||
'ValidationError',
|
||||
'UnauthorizedError',
|
||||
'ForbiddenError',
|
||||
'NotFoundError',
|
||||
'ConflictError',
|
||||
'ServiceUnavailableError',
|
||||
]
|
||||
@@ -0,0 +1,9 @@
|
||||
"""
|
||||
backend/app/core/response.py
|
||||
|
||||
用途:统一 API 响应工具(Wave 1 自 app/response_utils.py 迁入)。
|
||||
逻辑:error_payload 供全局异常 handler 使用;ok() 供成功 envelope(可选)。
|
||||
"""
|
||||
from app.response_utils import error_payload, ok, utc_iso_now # noqa: F401
|
||||
|
||||
__all__ = ['error_payload', 'ok', 'utc_iso_now']
|
||||
@@ -1,31 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import declarative_base, sessionmaker
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
connect_args: dict[str, object] = {}
|
||||
if settings.database_url.startswith("sqlite"):
|
||||
connect_args["check_same_thread"] = False
|
||||
|
||||
engine = create_engine(
|
||||
settings.database_url,
|
||||
future=True,
|
||||
pool_pre_ping=True,
|
||||
connect_args=connect_args,
|
||||
)
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False, future=True)
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""
|
||||
backend/app/decorators.py
|
||||
文件用途:权限控制装饰器集合
|
||||
引用文件:flask, functools, models, db
|
||||
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
||||
"""
|
||||
from functools import wraps
|
||||
from flask import request, jsonify, g, current_app
|
||||
from app.models import Agent, User
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
|
||||
def _get_current_user() -> User:
|
||||
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
|
||||
user = _auth_current_user()
|
||||
if user:
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 agent_id
|
||||
2. 获取当前用户 (临时固定为 ID=1)
|
||||
3. 如果用户是 admin,则放行
|
||||
4. 否则检查 user.agents 是否包含该 agent
|
||||
传入参数:
|
||||
f: 被装饰的视图函数
|
||||
返回值:
|
||||
包装后的视图函数
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
data = request.get_json(silent=True) or {}
|
||||
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
||||
if not agent_id:
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
if agent not in user.agents:
|
||||
raise ForbiddenError('Permission denied for this agent')
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制只有管理员角色才能访问的接口
|
||||
核心逻辑:
|
||||
1. 获取当前用户
|
||||
2. 判断 user.role 是否为 'admin'
|
||||
"""
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||
raise UnauthorizedError('JWT token is required')
|
||||
if user.role != 'admin':
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
return f(*args, **kwargs)
|
||||
return decorated_function
|
||||
@@ -1,94 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.database import get_db
|
||||
from app.models import Group, User, UserDepartmentAccess
|
||||
from app.security import decode_access_token
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.api_prefix}/auth/login")
|
||||
|
||||
|
||||
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)) -> User:
|
||||
username = decode_access_token(token)
|
||||
if not username:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
user = db.query(User).filter(User.username == username, User.is_active.is_(True)).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
|
||||
return user
|
||||
|
||||
|
||||
def is_super_admin(user: User) -> bool:
|
||||
return user.role == "super_admin"
|
||||
|
||||
|
||||
def is_admin(user: User) -> bool:
|
||||
return user.role in {"super_admin", "admin"}
|
||||
|
||||
|
||||
def accessible_department_ids(db: Session, user: User) -> list[int] | None:
|
||||
department_ids = set()
|
||||
if user.primary_department_id is not None:
|
||||
department_ids.add(user.primary_department_id)
|
||||
department_ids.update(
|
||||
item.department_id
|
||||
for item in db.query(UserDepartmentAccess).filter(UserDepartmentAccess.user_id == user.id).all()
|
||||
if item.department_id is not None
|
||||
)
|
||||
return sorted(department_ids)
|
||||
|
||||
|
||||
def accessible_group_ids(db: Session, user: User) -> list[int] | None:
|
||||
department_ids = accessible_department_ids(db, user) or [-1]
|
||||
return [item[0] for item in db.query(Group.id).filter(Group.department_id.in_(department_ids)).all()]
|
||||
|
||||
|
||||
def require_super_admin(user: User = Depends(get_current_user)) -> User:
|
||||
if not is_super_admin(user):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Super admin only")
|
||||
return user
|
||||
|
||||
|
||||
def require_admin(user: User = Depends(get_current_user)) -> User:
|
||||
if not is_admin(user):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin only")
|
||||
return user
|
||||
|
||||
|
||||
def ensure_department_access(db: Session, user: User, department_id: int) -> None:
|
||||
if department_id not in (accessible_department_ids(db, user) or []):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
|
||||
|
||||
|
||||
def ensure_group_access(db: Session, user: User, group_id: int) -> None:
|
||||
group = db.query(Group.id, Group.department_id).filter(Group.id == group_id).first()
|
||||
if not group:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Knowledge base not found.")
|
||||
if group.department_id not in (accessible_department_ids(db, user) or []):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
|
||||
|
||||
|
||||
def require_integration_key(
|
||||
x_integration_key: str | None = Header(default=None, alias="X-Integration-Key"),
|
||||
authorization: str | None = Header(default=None),
|
||||
) -> str:
|
||||
configured_key = settings.integration_api_key
|
||||
if not configured_key:
|
||||
raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Integration API is not configured.")
|
||||
|
||||
token = x_integration_key
|
||||
if not token and authorization:
|
||||
scheme, _, credentials = authorization.partition(" ")
|
||||
if scheme.lower() == "bearer" and credentials:
|
||||
token = credentials
|
||||
|
||||
if token != configured_key:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid integration key")
|
||||
|
||||
return token
|
||||
@@ -0,0 +1,255 @@
|
||||
"""Persistent storage for runtime-editable application settings.
|
||||
|
||||
Settings managed from the admin console (e.g. WeCom configuration) need to
|
||||
survive process restarts AND container/image rebuilds in production. Writing
|
||||
only to ``backend/.env`` is not enough on Docker deployments because the
|
||||
container's writable layer is discarded on every ``docker compose up --build``.
|
||||
|
||||
Storage strategy:
|
||||
|
||||
1. Database (``app_settings`` table) - canonical, always authoritative.
|
||||
2. ``.env.local`` (dev only) - best-effort secondary write so local/dev
|
||||
workflows that restart without DB access still see updates.
|
||||
3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay
|
||||
in sync within the running process.
|
||||
|
||||
On read we merge env files (lowest priority) over DB (highest priority); the DB
|
||||
value wins whenever it exists.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
from dotenv import dotenv_values, set_key
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
# Backward-compatible alias for tests and older callers that still patch/read
|
||||
# the historical backend/.env location directly.
|
||||
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
'WECOM_MOBILE_NORMALIZE',
|
||||
'WECOM_NOTIFY_ENABLED',
|
||||
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not ROOT_ENV_LOCAL_PATH.exists():
|
||||
ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
if value is None:
|
||||
return ''
|
||||
return str(value)
|
||||
|
||||
|
||||
def _parse_env_value(key: str, value: object) -> object:
|
||||
if value is None:
|
||||
return None
|
||||
if key in WECOM_BOOL_KEYS:
|
||||
return str(value).strip().lower() == 'true'
|
||||
return str(value)
|
||||
|
||||
|
||||
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||
return any(key.startswith(prefix) for prefix in prefixes)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Database read/write (primary store)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||
"""Write key/value pairs into the ``app_settings`` table.
|
||||
|
||||
Returns True if every value was committed, False otherwise. The function
|
||||
is defensive: it must not raise, because settings persistence is also
|
||||
written to ``.env`` and we don't want to fail the API request.
|
||||
"""
|
||||
if not values:
|
||||
return True
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover - import safety net
|
||||
logger.warning('AppSetting model unavailable: %s', exc)
|
||||
return False
|
||||
|
||||
try:
|
||||
for key, value in values.items():
|
||||
existing = db.session.get(AppSetting, key)
|
||||
if existing is None:
|
||||
db.session.add(AppSetting(key=key, value=value))
|
||||
else:
|
||||
existing.value = value
|
||||
db.session.commit()
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
try:
|
||||
from app import db
|
||||
from app.models import AppSetting
|
||||
except Exception as exc: # pragma: no cover
|
||||
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||
return {}
|
||||
|
||||
try:
|
||||
rows = db.session.query(AppSetting).all()
|
||||
except Exception as exc:
|
||||
# Most common case: the migration has not been applied yet on a
|
||||
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||
logger.debug('app_settings table not readable yet: %s', exc)
|
||||
try:
|
||||
db.session.rollback()
|
||||
except Exception: # pragma: no cover
|
||||
pass
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
if row.key and _matches_prefixes(row.key, prefixes):
|
||||
result[row.key] = row.value if row.value is not None else ''
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# .env read/write (secondary store, best-effort)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
if env_name != 'dev':
|
||||
return True
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
return False
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
merged: dict[str, str] = {}
|
||||
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
if not env_path.exists():
|
||||
continue
|
||||
try:
|
||||
loaded = dotenv_values(env_path)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', env_path, exc)
|
||||
continue
|
||||
for key, value in loaded.items():
|
||||
if key and _matches_prefixes(key, prefixes):
|
||||
merged[key] = value if value is not None else ''
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public API
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||
|
||||
Order:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
|
||||
persisted: dict[str, str] = {}
|
||||
for key, value in values.items():
|
||||
env_value = _to_env_string(value)
|
||||
os.environ[key] = env_value
|
||||
persisted[key] = env_value
|
||||
|
||||
db_ok = _persist_to_db(persisted)
|
||||
file_ok = _persist_to_env_file(persisted)
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env.local mirror. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
|
||||
return persisted
|
||||
|
||||
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
db_values = _load_from_db(prefixes)
|
||||
|
||||
merged: dict[str, str] = {**file_values, **db_values}
|
||||
|
||||
applied: dict[str, object] = {}
|
||||
for key, raw_value in merged.items():
|
||||
parsed = _parse_env_value(key, raw_value)
|
||||
os.environ[key] = _to_env_string(parsed)
|
||||
applied[key] = parsed
|
||||
return applied
|
||||
@@ -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 {},
|
||||
)
|
||||
@@ -0,0 +1,12 @@
|
||||
"""
|
||||
backend/app/extensions.py
|
||||
|
||||
用途:Flask 扩展实例(db、migrate)集中定义;Wave 1 从 __init__.py 迁入并接线。
|
||||
依赖:flask_sqlalchemy、flask_migrate。
|
||||
逻辑:create_app 调用 db.init_app(app);models 与各 service 从本模块 import db。
|
||||
"""
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
@@ -0,0 +1,11 @@
|
||||
"""
|
||||
backend/app/jobs/__init__.py
|
||||
|
||||
用途:统一后台任务层入口(方案 D)。
|
||||
依赖:types、registry、queue、runner。
|
||||
逻辑:Web API enqueue;worker.py 调用 runner.run_forever。
|
||||
"""
|
||||
from app.jobs.types import JobStatus, JobType
|
||||
from app.jobs.queue import enqueue
|
||||
|
||||
__all__ = ['JobType', 'JobStatus', 'enqueue']
|
||||
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
backend/app/jobs/context.py
|
||||
|
||||
用途:Worker 运行时上下文,注入 config / db / logger。
|
||||
逻辑:handler.run(ctx, payload) 通过 ctx 访问依赖,禁止 import flask.request。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class JobContext:
|
||||
"""
|
||||
Worker 执行上下文。
|
||||
Attributes:
|
||||
config: Flask app.config 快照或类 dict。
|
||||
logger: 模块 logger。
|
||||
extras: 扩展字段(如 worker_label)。
|
||||
"""
|
||||
|
||||
config: dict[str, Any]
|
||||
logger: logging.Logger
|
||||
extras: dict[str, Any] = field(default_factory=dict)
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/__init__.py
|
||||
|
||||
用途:导入各 handler 模块以触发 @register_handler 注册。
|
||||
逻辑:Wave 2 起在 worker 启动前 import 本包。
|
||||
"""
|
||||
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_run, wecom_directory_sync # noqa: F401
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/file_check_run.py
|
||||
|
||||
用途:文件检核异步执行 handler。
|
||||
逻辑:Wave 4 替代 api/file_check_tools 内 threading.Thread。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
@register_handler(JobType.FILE_CHECK_RUN)
|
||||
def run_file_check(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行异步文件检核。"""
|
||||
ctx.logger.info('file_check_run handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('file_check_run handler pending Wave 4')
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/kb_clean.py
|
||||
|
||||
用途:KB 文档清洗任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.queue_service.process_next_clean_job。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
@register_handler(JobType.KB_CLEAN)
|
||||
def run_kb_clean(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行单条 KB 清洗任务。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
payload: 含 document_id 等字段。
|
||||
"""
|
||||
ctx.logger.info('kb_clean handler skeleton invoked payload=%s', payload)
|
||||
# Wave 2: from app.services.knowledge_cleaning.queue_service import process_job
|
||||
raise NotImplementedError('kb_clean handler pending Wave 2')
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/kb_dify_sync.py
|
||||
|
||||
用途:KB 文档同步至 Dify 任务 handler。
|
||||
逻辑:Wave 2 包装 knowledge_cleaning.dify_sync_service。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
@register_handler(JobType.KB_DIFY_SYNC)
|
||||
def run_kb_dify_sync(ctx: JobContext, payload: dict) -> None:
|
||||
"""同步已清洗文档到 Dify。"""
|
||||
ctx.logger.info('kb_dify_sync handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('kb_dify_sync handler pending Wave 2')
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/schedule_run.py
|
||||
|
||||
用途:排程任务执行 handler。
|
||||
逻辑:Wave 4 从 scheduler_service in-process 执行体迁入。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
@register_handler(JobType.SCHEDULE_RUN)
|
||||
def run_schedule(ctx: JobContext, payload: dict) -> None:
|
||||
"""执行单条 ScheduleTask。"""
|
||||
ctx.logger.info('schedule_run handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('schedule_run handler pending Wave 4')
|
||||
@@ -0,0 +1,19 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_notice_run.py
|
||||
|
||||
用途:货代发货单票后台任务 handler。
|
||||
依赖:jobs.context、jobs.registry、shipping_notice.queue_service。
|
||||
逻辑:统一由 worker 消费 `shipping_notice_run` 队列任务,再委托 shipping_notice.queue_service 执行单票。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice.queue_service import run_shipping_notice_job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_NOTICE_RUN)
|
||||
def run_shipping_notice(ctx: JobContext, payload: dict) -> None:
|
||||
"""消费单票发货后台任务。"""
|
||||
run_shipping_notice_job(payload, logger=ctx.logger)
|
||||
@@ -0,0 +1,18 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/wecom_directory_sync.py
|
||||
|
||||
用途:企微通讯录同步 handler。
|
||||
逻辑:Wave 4 包装 wecom_directory_sync 服务。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
@register_handler(JobType.WECOM_DIRECTORY_SYNC)
|
||||
def run_wecom_directory_sync(ctx: JobContext, payload: dict) -> None:
|
||||
"""同步企微通讯录到本地用户/部门。"""
|
||||
ctx.logger.info('wecom_directory_sync handler skeleton invoked payload=%s', payload)
|
||||
raise NotImplementedError('wecom_directory_sync handler pending Wave 4')
|
||||
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
backend/app/jobs/queue.py
|
||||
|
||||
用途:任务入队 API。
|
||||
逻辑:API / services 调用 enqueue;Wave 2 写入 Job 表并 adapter KbJob。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.jobs.types import JobType
|
||||
|
||||
|
||||
def enqueue(
|
||||
job_type: JobType,
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
correlation_id: str | None = None,
|
||||
scheduled_at: Any = None,
|
||||
) -> int:
|
||||
"""
|
||||
将任务写入队列并返回 job id。
|
||||
核心逻辑:Wave 2 实现 store.create + KbJob adapter。
|
||||
Args:
|
||||
job_type: 任务类型。
|
||||
payload: 任务参数 JSON。
|
||||
correlation_id: 关联业务 id(如 kb_document_id)。
|
||||
scheduled_at: 延迟执行时间(可选)。
|
||||
Returns:
|
||||
Job 主键。
|
||||
Raises:
|
||||
NotImplementedError: Wave 0 占位。
|
||||
"""
|
||||
raise NotImplementedError('jobs.enqueue is not wired until Wave 2')
|
||||
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
backend/app/jobs/registry.py
|
||||
|
||||
用途:JobType → Handler 注册表。
|
||||
逻辑:handlers 模块 import 时 @register_handler 装饰;runner 按 type 分发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from app.jobs.types import JobType
|
||||
|
||||
HandlerFn = Callable[[Any, dict], None]
|
||||
|
||||
_REGISTRY: dict[JobType, HandlerFn] = {}
|
||||
|
||||
|
||||
def register_handler(job_type: JobType) -> Callable[[HandlerFn], HandlerFn]:
|
||||
"""
|
||||
注册某 JobType 的处理函数。
|
||||
Args:
|
||||
job_type: 任务类型枚举。
|
||||
Returns:
|
||||
装饰器。
|
||||
"""
|
||||
|
||||
def decorator(fn: HandlerFn) -> HandlerFn:
|
||||
_REGISTRY[job_type] = fn
|
||||
return fn
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def get_handler(job_type: JobType) -> HandlerFn | None:
|
||||
"""按类型获取 handler;未注册返回 None。"""
|
||||
return _REGISTRY.get(job_type)
|
||||
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
backend/app/jobs/runner.py
|
||||
|
||||
用途:Worker 主循环 poll → dispatch → ack/fail。
|
||||
逻辑:worker.py 调用 run_forever(ctx);Wave 2 接入 store 与 registry。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import get_handler
|
||||
from app.jobs import store
|
||||
|
||||
|
||||
def run_forever(ctx: JobContext, *, poll_interval_seconds: float = 2.0) -> None:
|
||||
"""
|
||||
持续轮询并执行任务。
|
||||
核心逻辑:claim_next → get_handler → handler(ctx, payload) → 更新状态。
|
||||
Args:
|
||||
ctx: Worker 上下文。
|
||||
poll_interval_seconds: 无任务时的休眠秒数。
|
||||
"""
|
||||
ctx.logger.info('Job runner started (skeleton mode — Wave 2 will enable claim loop)')
|
||||
while True:
|
||||
try:
|
||||
job = store.claim_next()
|
||||
except NotImplementedError:
|
||||
time.sleep(poll_interval_seconds)
|
||||
continue
|
||||
if not job:
|
||||
time.sleep(poll_interval_seconds)
|
||||
continue
|
||||
handler = get_handler(job['job_type'])
|
||||
if not handler:
|
||||
ctx.logger.error('No handler for job_type=%s', job.get('job_type'))
|
||||
continue
|
||||
handler(ctx, job.get('payload') or {})
|
||||
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
backend/app/jobs/store.py
|
||||
|
||||
用途:Job 表 CRUD(claim、update status)。
|
||||
逻辑:runner 通过 claim_next 获取待执行任务;Wave 2 落地 SQLAlchemy 模型。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def claim_next() -> dict[str, Any] | None:
|
||||
"""
|
||||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED)。
|
||||
Returns:
|
||||
job 字典或 None。
|
||||
Raises:
|
||||
NotImplementedError: Wave 0 占位。
|
||||
"""
|
||||
raise NotImplementedError('jobs.store.claim_next is not wired until Wave 2')
|
||||
@@ -0,0 +1,30 @@
|
||||
"""
|
||||
backend/app/jobs/types.py
|
||||
|
||||
用途:Job 类型与状态枚举。
|
||||
逻辑:handlers 与 queue 通过 JobType 注册;store 持久化 status 字符串。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class JobType(StrEnum):
|
||||
"""后台任务类型。"""
|
||||
|
||||
KB_CLEAN = 'kb_clean'
|
||||
KB_DIFY_SYNC = 'kb_dify_sync'
|
||||
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
|
||||
SCHEDULE_RUN = 'schedule_run'
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
|
||||
|
||||
class JobStatus(StrEnum):
|
||||
"""Job 生命周期状态。"""
|
||||
|
||||
PENDING = 'pending'
|
||||
RUNNING = 'running'
|
||||
SUCCEEDED = 'succeeded'
|
||||
FAILED = 'failed'
|
||||
DEAD = 'dead'
|
||||
@@ -1,50 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from app.api import admin, auth, departments, files, groups, integration, jobs
|
||||
from app.config import get_settings
|
||||
from app.database import SessionLocal
|
||||
from app.services.bootstrap_service import ensure_defaults
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
db = SessionLocal()
|
||||
try:
|
||||
ensure_defaults(db)
|
||||
yield
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
app = FastAPI(title=settings.app_name, lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.origins_list(),
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(auth.router, prefix=settings.api_prefix)
|
||||
app.include_router(departments.router, prefix=settings.api_prefix)
|
||||
app.include_router(groups.router, prefix=settings.api_prefix)
|
||||
app.include_router(files.router, prefix=settings.api_prefix)
|
||||
app.include_router(integration.router, prefix=settings.api_prefix)
|
||||
app.include_router(jobs.router, prefix=settings.api_prefix)
|
||||
app.include_router(admin.router, prefix=settings.api_prefix)
|
||||
app.mount("/storage", StaticFiles(directory=settings.data_root), name="storage")
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
def health() -> dict:
|
||||
return {"status": "ok"}
|
||||
+846
-189
File diff suppressed because it is too large.
Load diff
@@ -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,62 @@
|
||||
"""
|
||||
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 utc_iso(dt: datetime | None) -> str | None:
|
||||
"""将 naive UTC datetime 序列化为带 Z 后缀的 ISO 字符串,便于前端正确转本地时区。"""
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is not None:
|
||||
return dt.astimezone(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
|
||||
return dt.isoformat() + "Z"
|
||||
|
||||
|
||||
def ok(data: Any, *, request_id: str | None = None, status: int = 200):
|
||||
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
|
||||
@@ -1,105 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
user: dict
|
||||
|
||||
|
||||
class GroupCreateRequest(BaseModel):
|
||||
name: str
|
||||
description: str | None = None
|
||||
department_id: int
|
||||
|
||||
|
||||
class GroupUpdateRequest(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
department_id: int | None = None
|
||||
rename_dify: bool = False
|
||||
|
||||
|
||||
class BatchDownloadRequest(BaseModel):
|
||||
document_ids: list[int] = Field(default_factory=list)
|
||||
kind: str = "md"
|
||||
|
||||
|
||||
class BatchSyncRequest(BaseModel):
|
||||
document_ids: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
class UserCreateRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
full_name: str | None = None
|
||||
role: str = "user"
|
||||
primary_department_id: int
|
||||
accessible_department_ids: list[int] = Field(default_factory=list)
|
||||
|
||||
|
||||
class UserUpdateRequest(BaseModel):
|
||||
full_name: str | None = None
|
||||
role: str | None = None
|
||||
password: str | None = None
|
||||
is_active: bool | None = None
|
||||
primary_department_id: int | None = None
|
||||
accessible_department_ids: list[int] | None = None
|
||||
|
||||
|
||||
class DifyImportRequest(BaseModel):
|
||||
dataset_id: str
|
||||
remote_document_id: str
|
||||
group_id: int | None = None
|
||||
department_id: int | None = None
|
||||
knowledge_base_name: str | None = None
|
||||
|
||||
|
||||
class DepartmentCreateRequest(BaseModel):
|
||||
name: str
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class DepartmentUpdateRequest(BaseModel):
|
||||
name: str | None = None
|
||||
description: str | None = None
|
||||
|
||||
|
||||
class DepartmentDeleteRequest(BaseModel):
|
||||
target_department_id: int | None = None
|
||||
|
||||
|
||||
class SettingsUpdateRequest(BaseModel):
|
||||
dify_permission: str | None = None
|
||||
indexing_technique: str | None = None
|
||||
search_method: str | None = None
|
||||
doc_form: str | None = None
|
||||
embedding_model_provider: str | None = None
|
||||
embedding_model: str | None = None
|
||||
reranking_model_provider: str | None = None
|
||||
reranking_model: str | None = None
|
||||
top_k: int | None = None
|
||||
score_threshold_enabled: bool | None = None
|
||||
score_threshold: float | None = None
|
||||
|
||||
|
||||
class JobResponse(BaseModel):
|
||||
id: str
|
||||
job_type: str
|
||||
status: str
|
||||
progress: int
|
||||
message: str | None = None
|
||||
error: str | None = None
|
||||
created_at: datetime | None = None
|
||||
started_at: datetime | None = None
|
||||
finished_at: datetime | None = None
|
||||
result: dict | None = None
|
||||
@@ -0,0 +1,6 @@
|
||||
"""
|
||||
backend/app/schemas/__init__.py
|
||||
|
||||
用途:请求/响应 DTO 包(dataclass 或 Pydantic,非 FastAPI 专用)。
|
||||
逻辑:api 层解析入参、校验后传入 services;Wave 3 随 admin/user/kb 拆分落地。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/schemas/admin/__init__.py
|
||||
|
||||
用途:管理后台 DTO 包入口。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/schemas/admin/agents.py
|
||||
|
||||
用途:Agent 管理 API DTO。
|
||||
"""
|
||||
@@ -0,0 +1,5 @@
|
||||
"""
|
||||
backend/app/schemas/admin/settings.py
|
||||
|
||||
用途:系统设置 API DTO。
|
||||
"""
|
||||
Loaded 100 of 997 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user