Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
88fcf3c70b | ||
|
|
9838b77441 | ||
|
|
e457a66465 | ||
|
|
ec2c9eca6f | ||
|
|
6a26a4dba8 | ||
|
|
fc4631218b | ||
|
|
0d735def90 | ||
|
|
9203a90637 | ||
|
|
8023acd212 | ||
|
|
d100a39cf8 | ||
|
|
ffccf19ba2 | ||
|
|
e8255f5943 | ||
|
|
70f684b94a | ||
|
|
bc86720744 | ||
|
|
ceb49461e8 | ||
|
|
ea9a96b2fb | ||
|
|
49629aeb0f | ||
|
|
cd81911514 | ||
|
|
49c149eb3e | ||
|
|
729546a7b7 | ||
|
|
202d626a7a | ||
|
|
143e054d86 | ||
|
|
0a9bd6415d | ||
|
|
42de6c02d3 | ||
|
|
b2fa2688a3 | ||
|
|
1ee4c69dee | ||
|
|
2ebac99d43 | ||
|
|
c621f7696c | ||
|
|
db067085e4 | ||
|
|
6d39e474f5 | ||
|
|
a31735b689 | ||
|
|
5a147c4d85 | ||
|
|
c3f05ba96b | ||
|
|
918d4f1835 | ||
|
|
fc843905d1 | ||
|
|
f21216f81e | ||
|
|
0939aeb0d8 | ||
|
|
64205b72bd | ||
|
|
854793f3fe | ||
|
|
ffd3634302 | ||
|
|
5e7e5a8717 | ||
|
|
8b1efbedb9 | ||
|
|
c81717df30 | ||
|
|
f4e74f7b07 | ||
|
|
39ef8a49c9 | ||
|
|
50ccd31b84 | ||
|
|
348f0fdcfd | ||
|
|
c778f40fbc | ||
|
|
b89f9bafb6 | ||
|
|
dab04d4c3e | ||
|
|
f1b9b7c3a9 | ||
|
|
0d68048b8e | ||
|
|
8b5b0b49bf | ||
|
|
61acbe50a7 | ||
|
|
8bd66baa21 | ||
|
|
5bef77f86c | ||
|
|
37e08c83d8 | ||
|
|
2ce1aca023 | ||
|
|
99453aa52a | ||
|
|
fa965dd45b | ||
|
|
d54f51ddc3 | ||
|
|
fc694a8f43 | ||
|
|
c8ce77199e | ||
|
|
9ea49d7060 | ||
|
|
fd024c1c32 | ||
|
|
dfaa55b365 | ||
|
|
bf18a7ef1d | ||
|
|
6ce0942fef | ||
|
|
fa8f6990a7 | ||
|
|
2566ce53e4 | ||
|
|
ac4262cd75 | ||
|
|
090281835a | ||
|
|
76d5778c3b | ||
|
|
f72c1c9f0e | ||
|
|
95f3906779 | ||
|
|
91758ef2b4 | ||
|
|
3a22df736e | ||
|
|
0f3f40e735 | ||
|
|
56b6ea06a8 | ||
|
|
7a9c36d16b | ||
|
|
8846ce159f | ||
|
|
1164ae2e3c | ||
|
|
599475d4e2 | ||
|
|
09cd6fc3c7 | ||
|
|
60dd0c0f58 | ||
|
|
6261d2e1f3 | ||
|
|
9c036c825b | ||
|
|
bba6e6f221 | ||
|
|
c8054476c1 | ||
|
|
4a14960e01 | ||
|
|
f96684a614 | ||
|
|
af999d8a11 | ||
|
|
6a0a51313f | ||
|
|
9f5493185d | ||
|
|
4cd987eef6 | ||
|
|
19f43e8018 | ||
|
|
3f13bb5b46 | ||
|
|
eb0466245b | ||
|
|
ce80867d09 | ||
|
|
1921959fc1 | ||
|
|
d5e76dee36 | ||
|
|
b476b58a91 | ||
|
|
ca32191c77 | ||
|
|
7f1d5dfbcd | ||
|
|
7e4a2037d8 | ||
|
|
f434402530 | ||
|
|
1fc9976ca3 | ||
|
|
cafce5cfa9 | ||
|
|
a3420c5266 | ||
|
|
3b771fc0b6 | ||
|
|
0b083cfdbd | ||
|
|
53efa7e14e | ||
|
|
d6af566601 | ||
|
|
25876f94bd | ||
|
|
1cf8ff40bd | ||
|
|
70d7435b5f | ||
|
|
a451951e7a | ||
|
|
053ea392f2 | ||
|
|
1dc5a459b3 | ||
|
|
6e78c10171 | ||
|
|
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,119 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# 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
|
||||||
|
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/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||||
|
# RoHS / 货代等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||||
|
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||||
|
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||||
|
HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||||
|
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||||
|
|
||||||
|
SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8
|
||||||
|
|
||||||
|
# 文件存储(相对 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_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||||
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||||
|
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||||
|
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||||
|
|
||||||
|
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||||
|
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=900
|
||||||
|
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||||
|
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||||
|
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||||
|
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
|
||||||
|
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||||
|
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||||
|
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||||
|
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||||
|
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||||
|
|
||||||
|
# RPA 目录(相对 backend/ 根目录)
|
||||||
|
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
|
||||||
|
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
|
||||||
|
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
|
||||||
|
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
|
||||||
|
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||||
|
|
||||||
|
# 发货 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
|
||||||
|
|
||||||
|
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
|
||||||
|
FREIGHT_RPA_MOCK=false
|
||||||
|
# FREIGHT_RPA_POLL_SECONDS=3
|
||||||
|
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||||
|
|
||||||
|
# 设备维保助手后端工具调用密钥
|
||||||
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# 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=https://auth.well-trust.com
|
||||||
|
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||||
|
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||||
|
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||||
|
# 兜底 redirect_uri;实际 OAuth 以浏览器地址为准,Casdoor「hxops-prod」应用须登记例如:
|
||||||
|
# http://192.168.100.230:8881/casdoor-callback
|
||||||
|
# http://ai.well-trust.com:8881/casdoor-callback
|
||||||
|
CASDOOR_REDIRECT_URI=https://ai.well-trust.com/casdoor-callback
|
||||||
|
CASDOOR_SCOPE=openid profile email
|
||||||
|
CASDOOR_ORGANIZATION=organization_HX
|
||||||
|
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||||
|
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:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||||
|
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||||
|
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||||
|
|
||||||
|
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||||
|
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||||
|
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 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||||
|
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||||
|
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||||
|
HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||||
|
|
||||||
|
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||||
|
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||||
|
|
||||||
|
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||||
|
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||||
|
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||||
|
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||||
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||||
|
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
|
||||||
|
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
|
||||||
|
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
|
||||||
|
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
|
||||||
|
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||||
|
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||||
|
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||||
|
|
||||||
|
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||||
|
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||||
|
|
||||||
|
|
||||||
|
# 设备维保助手后端工具调用密钥
|
||||||
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
+162
@@ -0,0 +1,162 @@
|
|||||||
|
# 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=300
|
||||||
|
# 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 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
|
||||||
|
HXOPS_TOOLS_API_BASE=
|
||||||
|
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||||
|
HXOPS_PUBLIC_BASE_URL=
|
||||||
|
|
||||||
|
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
|
||||||
|
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
|
||||||
|
# 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=
|
||||||
|
|
||||||
|
# 固资履历共享盘
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||||
|
|
||||||
|
# 固资图片文档库
|
||||||
|
FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login
|
||||||
|
FIXED_ASSET_IMAGE_USERNAME=26040006
|
||||||
|
FIXED_ASSET_IMAGE_PASSWORD=26040006
|
||||||
|
FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
|
||||||
|
FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3
|
||||||
|
|
||||||
|
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
|
||||||
|
# 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置
|
||||||
|
FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过)
|
||||||
|
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 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||||
|
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
|
||||||
|
FREIGHT_RPA_MOCK=false
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# 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=https://autht.well-trust.com
|
||||||
|
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||||
|
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||||
|
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||||
|
# 兜底 redirect_uri;实际 OAuth 以浏览器地址为准,Casdoor「hxops-prod」应用须登记例如:
|
||||||
|
# http://192.168.100.192:8881/casdoor-callback
|
||||||
|
# http://ai.well-trust.com:8881/casdoor-callback
|
||||||
|
CASDOOR_REDIRECT_URI=https://ait.well-trust.com/casdoor-callback
|
||||||
|
CASDOOR_SCOPE=openid profile email
|
||||||
|
CASDOOR_ORGANIZATION=organization_HX
|
||||||
|
# Casdoor Providers → wecom:Name 字段;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:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||||
|
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||||
|
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||||
|
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||||
|
|
||||||
|
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||||
|
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||||
|
# 账号与 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/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||||
|
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||||
|
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||||
|
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||||
|
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||||
|
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||||
|
SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
|
||||||
|
|
||||||
|
# 文件存储(相对 backend/ 根目录)
|
||||||
|
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||||
|
|
||||||
|
# 解析与文本上限
|
||||||
|
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||||
|
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||||
|
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||||
|
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||||
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||||
|
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||||
|
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||||
|
|
||||||
|
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||||
|
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=900
|
||||||
|
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||||
|
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||||
|
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||||
|
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||||
|
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||||
|
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||||
|
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||||
|
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||||
|
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||||
|
|
||||||
|
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
|
||||||
|
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
|
||||||
|
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
|
||||||
|
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
|
||||||
|
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
|
||||||
|
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||||
|
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||||
|
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||||
|
# 两者皆无则告警只写日志、不会发企微
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||||
|
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||||
|
|
||||||
|
# 发货 Excel 模板(可选)
|
||||||
|
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||||
|
|
||||||
|
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||||
|
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||||
|
|
||||||
|
# AWS 库存列映射(可选 JSON 字符串)
|
||||||
|
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||||
|
|
||||||
|
# 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=
|
||||||
|
|
||||||
|
|
||||||
|
# 设备维保助手后端工具调用密钥
|
||||||
|
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||||
@@ -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
|
||||||
+88
@@ -0,0 +1,88 @@
|
|||||||
|
# Environments
|
||||||
|
#docs/
|
||||||
|
venv/
|
||||||
|
backend/venv/
|
||||||
|
backend/instance/
|
||||||
|
tmpwork/
|
||||||
|
env/
|
||||||
|
|
||||||
|
# .env
|
||||||
|
.venv
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
||||||
|
|
||||||
|
# Pytest / local temp
|
||||||
|
backend/.pytest_tmp/
|
||||||
|
.pytest_tmp/
|
||||||
|
*.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
|
||||||
|
.trae/*
|
||||||
|
.cursor/*
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
.cursorrules
|
||||||
|
|
||||||
|
# Runtime files
|
||||||
|
.run/
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# 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/
|
||||||
|
backend/data/fixed_assets/manifest.json
|
||||||
|
backend/data/shipping_notice/
|
||||||
|
backend/data/logs/
|
||||||
|
backend/data/logs/*.log
|
||||||
Vendored
+3
@@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"recommendations": ["ms-python.python", "ms-python.vscode-pylance"]
|
||||||
|
}
|
||||||
Vendored
+59
@@ -0,0 +1,59 @@
|
|||||||
|
{
|
||||||
|
// 后端 Python 虚拟环境(解释器路径供语言服务/调试使用)
|
||||||
|
"python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe",
|
||||||
|
// 关闭 Python 扩展在新建终端时自动 activate,避免与下方 PowerShell (HXOPS) 的 cd 钩子重复激活
|
||||||
|
"python.terminal.activateEnvironment": false,
|
||||||
|
"python.venvPath": "${workspaceFolder}/backend",
|
||||||
|
"python.venvFolders": [".venv"],
|
||||||
|
"github.copilot.chat.commitMessageGeneration.instructions": [
|
||||||
|
{
|
||||||
|
"text": "Generate Git commit messages in Simplified Chinese by default."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "Follow Conventional Commits format: <type>(<scope>): <subject>."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "Use English for type and scope; use Simplified Chinese for subject and body."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "Allowed types are feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "The subject must be imperative, no period at the end, and no longer than 100 Chinese characters."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "Avoid vague messages such as update, fix bug, or WIP."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"text": "When a body is useful, write concise Chinese bullet points describing concrete changes."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
|
||||||
|
// 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv
|
||||||
|
"terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)",
|
||||||
|
"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' }"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"js/ts.tsdk.path": "node_modules\\typescript\\lib"
|
||||||
|
}
|
||||||
+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,205 @@
|
|||||||
|
# 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/ # 权威文档(规范、上下文、流程、发布说明)
|
||||||
|
# features/ 业务域手册 · platform/ 平台设计 · prototype/ 产品原型
|
||||||
|
# convention/ · openapi/ · dify/ · refactor/
|
||||||
|
```
|
||||||
|
|
||||||
|
**约定**:
|
||||||
|
|
||||||
|
- **后端**:新逻辑优先放入 `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/core/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
|
||||||
|
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||||
|
|
||||||
|
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 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/README.md](docs/README.md) |
|
||||||
|
| 项目上下文 / 架构 / 数据模型 | [docs/project_context.md](docs/project_context.md) |
|
||||||
|
| 需求文档 | [docs/demand.md](docs/demand.md) |
|
||||||
|
| 技术架构文档 | [docs/tec.md](docs/tec.md) |
|
||||||
|
| 功能清单 | [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) |
|
||||||
|
| **业务域文档索引** | [docs/features/README.md](docs/features/README.md) |
|
||||||
|
| 货代发货通知 | [docs/features/shipping-notice/technical.md](docs/features/shipping-notice/technical.md) |
|
||||||
|
| 文件检核 | [docs/features/file-check/technical.md](docs/features/file-check/technical.md) |
|
||||||
|
| Agent 应用管理(设计) | [docs/platform/agent_application_management.md](platform/agent_application_management.md) |
|
||||||
|
| Agent 应用管理(实现) | [docs/platform/agent_application_management_implementation.md](platform/agent_application_management_implementation.md) |
|
||||||
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,36 +0,0 @@
|
|||||||
# hxops
|
|
||||||
|
|
||||||
#### Description
|
|
||||||
hxops
|
|
||||||
|
|
||||||
#### Software Architecture
|
|
||||||
Software architecture description
|
|
||||||
|
|
||||||
#### Installation
|
|
||||||
|
|
||||||
1. xxxx
|
|
||||||
2. xxxx
|
|
||||||
3. xxxx
|
|
||||||
|
|
||||||
#### Instructions
|
|
||||||
|
|
||||||
1. xxxx
|
|
||||||
2. xxxx
|
|
||||||
3. xxxx
|
|
||||||
|
|
||||||
#### Contribution
|
|
||||||
|
|
||||||
1. Fork the repository
|
|
||||||
2. Create Feat_xxx branch
|
|
||||||
3. Commit your code
|
|
||||||
4. Create Pull Request
|
|
||||||
|
|
||||||
|
|
||||||
#### Gitee Feature
|
|
||||||
|
|
||||||
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
|
|
||||||
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
|
|
||||||
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
|
|
||||||
4. The most valuable open source project [GVP](https://gitee.com/gvp)
|
|
||||||
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
|
|
||||||
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
|
||||||
@@ -35,3 +35,14 @@ hxops
|
|||||||
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
|
4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目
|
||||||
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
|
5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
|
||||||
6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
|
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
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# syntax=docker/dockerfile:1.4
|
||||||
|
ARG PYTHON_BASE_IMAGE=python:3.12-slim-bookworm
|
||||||
|
FROM ${PYTHON_BASE_IMAGE}
|
||||||
|
|
||||||
|
ARG APT_MIRROR=https://mirrors.aliyun.com
|
||||||
|
ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple
|
||||||
|
ARG PIP_EXTRA_INDEX_URL
|
||||||
|
ARG PIP_TIMEOUT=300
|
||||||
|
ARG PIP_RETRIES=15
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
|
||||||
|
--mount=type=cache,target=/var/lib/apt,sharing=locked \
|
||||||
|
set -eux; \
|
||||||
|
if [ -f /etc/apt/sources.list.d/debian.sources ]; then \
|
||||||
|
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list.d/debian.sources; \
|
||||||
|
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list.d/debian.sources; \
|
||||||
|
fi; \
|
||||||
|
if [ -f /etc/apt/sources.list ]; then \
|
||||||
|
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list; \
|
||||||
|
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list; \
|
||||||
|
fi; \
|
||||||
|
apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
libgl1 \
|
||||||
|
libglib2.0-0 \
|
||||||
|
libxcb1 \
|
||||||
|
libx11-6 \
|
||||||
|
libxext6 \
|
||||||
|
libnsl2 \
|
||||||
|
libreoffice-nogui \
|
||||||
|
fonts-noto-cjk \
|
||||||
|
curl \
|
||||||
|
ca-certificates \
|
||||||
|
gnupg \
|
||||||
|
unixodbc-dev \
|
||||||
|
&& (apt-get install -y --no-install-recommends libaio1 || apt-get install -y --no-install-recommends libaio1t64) \
|
||||||
|
&& if [ ! -e /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1 ] && [ -e /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1t64 ]; then ln -s /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1t64 /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH)/libaio.so.1; fi \
|
||||||
|
&& install -d -m 0755 /etc/apt/keyrings \
|
||||||
|
&& curl -fsSL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor -o /etc/apt/keyrings/microsoft-prod.gpg \
|
||||||
|
&& chmod a+r /etc/apt/keyrings/microsoft-prod.gpg \
|
||||||
|
&& echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/microsoft-prod.gpg] https://packages.microsoft.com/debian/12/prod bookworm main" > /etc/apt/sources.list.d/mssql-release.list \
|
||||||
|
&& apt-get update \
|
||||||
|
&& ACCEPT_EULA=Y apt-get install -y --no-install-recommends msodbcsql18 \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Install Python dependencies
|
||||||
|
COPY backend/requirements.txt backend/requirements-ocr.txt ./
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/pip \
|
||||||
|
set -eux; \
|
||||||
|
PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \
|
||||||
|
if [ -n "${PIP_INDEX_URL:-}" ]; then \
|
||||||
|
PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \
|
||||||
|
fi; \
|
||||||
|
if [ -n "${PIP_EXTRA_INDEX_URL:-}" ]; then \
|
||||||
|
PIP_ARGS="$PIP_ARGS --extra-index-url ${PIP_EXTRA_INDEX_URL}"; \
|
||||||
|
fi; \
|
||||||
|
pip install $PIP_ARGS -r requirements.txt && \
|
||||||
|
pip install $PIP_ARGS \
|
||||||
|
"$(grep '^opencv-python-headless' requirements-ocr.txt)" && \
|
||||||
|
pip install $PIP_ARGS --no-deps \
|
||||||
|
"$(grep '^rapidocr-onnxruntime' requirements-ocr.txt)" && \
|
||||||
|
pip install $PIP_ARGS \
|
||||||
|
pyclipper Shapely six onnxruntime && \
|
||||||
|
python -c "import cv2; from rapidocr_onnxruntime import RapidOCR; import networkx, openpyxl"
|
||||||
|
|
||||||
|
# Copy backend code and the Text2SQL schema required at runtime
|
||||||
|
COPY backend/ .
|
||||||
|
RUN mkdir -p /app/docs
|
||||||
|
COPY docs/(表+字段).md /app/docs/(表+字段).md
|
||||||
|
|
||||||
|
|
||||||
|
# Expose port 5000
|
||||||
|
EXPOSE 5000
|
||||||
|
|
||||||
|
# Start Gunicorn
|
||||||
|
# Using the config file we created earlier
|
||||||
|
CMD ["gunicorn", "-c", "deploy/gunicorn_config.py", "run:app"]
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
"""
|
||||||
|
backend/app/__init__.py
|
||||||
|
|
||||||
|
用途:应用工厂:创建 Flask 应用、挂载全局异常与响应处理。
|
||||||
|
依赖:app.extensions(db、migrate)、app.api.register_blueprints、app.core.config。
|
||||||
|
逻辑:create_app 初始化扩展后委托 api 层集中注册 Blueprint;启动时 load_context_adapters 注册 Dify 上下文 adapter;
|
||||||
|
并幂等补建 file-asset-cleanup 默认排程(覆盖空库先迁移后建用户)。
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from flask import Flask, jsonify, request, g
|
||||||
|
from flask_cors import CORS
|
||||||
|
from werkzeug.exceptions import HTTPException
|
||||||
|
|
||||||
|
from app.core.config.settings import config
|
||||||
|
from app.core.errors import AppError
|
||||||
|
from app.extensions import db, migrate
|
||||||
|
from app.core.response import error_payload, utc_iso_now
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
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.core.config.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) # 允许跨域
|
||||||
|
|
||||||
|
from app.api import register_blueprints
|
||||||
|
|
||||||
|
register_blueprints(app)
|
||||||
|
|
||||||
|
# Eagerly load persisted runtime settings so the very first request after
|
||||||
|
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||||
|
# 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.agent_runtime_context.bootstrap import load_context_adapters
|
||||||
|
load_context_adapters()
|
||||||
|
from app.services.agent_registry.handlers.bootstrap import load_handlers
|
||||||
|
load_handlers()
|
||||||
|
from app.services.chat.intent_route_registry import ensure_intent_routes_loaded
|
||||||
|
ensure_intent_routes_loaded()
|
||||||
|
from app.services.schedule.scheduler_service import start_scheduler
|
||||||
|
start_scheduler(app)
|
||||||
|
# 空库先迁移后建用户:启动补建 + User commit 钩子即时补建,消除无排程窗口
|
||||||
|
try:
|
||||||
|
from app.services.file_assets.cleanup_schedule import (
|
||||||
|
ensure_default_file_asset_cleanup_schedule,
|
||||||
|
register_file_asset_cleanup_schedule_hooks,
|
||||||
|
)
|
||||||
|
register_file_asset_cleanup_schedule_hooks()
|
||||||
|
ensure_default_file_asset_cleanup_schedule()
|
||||||
|
except Exception as exc: # pragma: no cover - 表未就绪时容忍
|
||||||
|
logger.warning('Failed to ensure file-asset-cleanup schedule: %s', exc)
|
||||||
|
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||||
|
FixedAssetsSnapshotService.start_worker(app)
|
||||||
|
|
||||||
|
@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):
|
||||||
|
"""统一业务异常 → JSON error_payload(API 层应 raise AppError 而非 jsonify error)。"""
|
||||||
|
_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
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/__init__.py
|
||||||
|
|
||||||
|
用途:集中注册所有 HTTP Blueprint。
|
||||||
|
依赖:各 api 子模块 blueprint(单体或分包 re-export)。
|
||||||
|
逻辑:create_app 唯一调用 register_blueprints(app);后续拆包只改本文件 import 来源。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import Flask
|
||||||
|
|
||||||
|
|
||||||
|
def register_blueprints(app: Flask) -> None:
|
||||||
|
"""
|
||||||
|
注册全部 HTTP Blueprint,保持对外 url_prefix 与 Wave 0 之前一致。
|
||||||
|
核心逻辑:集中管理路由挂载点;后续 api/user、api/chat 等分包迁移时仅改本函数 import 来源。
|
||||||
|
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.integration import integration_bp
|
||||||
|
from app.api.internal_jobs import internal_jobs_bp
|
||||||
|
from app.api.maintenance import maintenance_bp
|
||||||
|
from app.api.speech import speech_bp
|
||||||
|
from app.api.training import training_admin_bp, training_user_bp
|
||||||
|
from app.api.agent_runtime_context_tools import agent_runtime_context_bp
|
||||||
|
|
||||||
|
# [STEP 2] 已分包骨架(Wave 3:kb、schedule 等)
|
||||||
|
from app.api.kb import knowledge_base_bp
|
||||||
|
from app.api.schedule import schedule_admin_bp
|
||||||
|
from app.api.workspace import (
|
||||||
|
workspace_announcements_bp,
|
||||||
|
workspace_file_check_bp,
|
||||||
|
workspace_schedule_bp,
|
||||||
|
workspace_shipping_notice_bp,
|
||||||
|
)
|
||||||
|
from app.api.tools import file_check_bp, maintenance_tool_bp, shipping_notice_bp
|
||||||
|
from app.api.files import files_bp
|
||||||
|
|
||||||
|
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||||
|
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||||
|
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||||
|
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||||
|
app.register_blueprint(training_user_bp, url_prefix='/api/user')
|
||||||
|
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||||
|
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||||
|
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||||
|
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||||
|
app.register_blueprint(workspace_announcements_bp, url_prefix='/api/workspace')
|
||||||
|
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
|
||||||
|
app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace')
|
||||||
|
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
|
||||||
|
app.register_blueprint(maintenance_bp, url_prefix='/api/maintenance')
|
||||||
|
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
|
||||||
|
app.register_blueprint(file_check_bp, url_prefix='/api/file-check')
|
||||||
|
app.register_blueprint(agent_runtime_context_bp, url_prefix='/api/agent-runtime-context')
|
||||||
|
app.register_blueprint(maintenance_tool_bp, url_prefix='/api/maintenance')
|
||||||
|
app.register_blueprint(speech_bp, url_prefix='/api/speech')
|
||||||
|
app.register_blueprint(training_admin_bp, url_prefix='/api/admin')
|
||||||
|
app.register_blueprint(files_bp, url_prefix='/api/files')
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/__init__.py
|
||||||
|
|
||||||
|
用途:管理后台 Blueprint 入口(Wave 3 分包)。
|
||||||
|
依赖:admin/blueprint.py 及各子模块路由。
|
||||||
|
逻辑:import 子模块注册路由;register_blueprints 从本包 import admin_bp。
|
||||||
|
"""
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
|
||||||
|
import app.api.admin.dashboard # noqa: F401
|
||||||
|
import app.api.admin.departments # noqa: F401
|
||||||
|
import app.api.admin.agents # noqa: F401
|
||||||
|
import app.api.admin.guides # noqa: F401
|
||||||
|
import app.api.admin.quick_questions # noqa: F401
|
||||||
|
import app.api.admin.faq_candidates # noqa: F401
|
||||||
|
import app.api.admin.reports # noqa: F401
|
||||||
|
import app.api.admin.database # noqa: F401
|
||||||
|
import app.api.admin.permissions # noqa: F401
|
||||||
|
import app.api.admin.users # noqa: F401
|
||||||
|
import app.api.admin.wecom # noqa: F401
|
||||||
|
import app.api.admin.announcements # noqa: F401
|
||||||
|
|
||||||
|
__all__ = ['admin_bp']
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/agents.py
|
||||||
|
|
||||||
|
用途:管理后台 Agent CRUD、连通性测试、权限绑定 API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/agent_service、core.response.ok。
|
||||||
|
逻辑:/agents* 路由;统一 success/data/request_id envelope。
|
||||||
|
"""
|
||||||
|
from flask import g, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.core.response import ok
|
||||||
|
from app.services.admin import agent_service
|
||||||
|
|
||||||
|
|
||||||
|
def _request_id() -> str | None:
|
||||||
|
return getattr(g, 'request_id', None)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/schema', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_agent_registry_schema():
|
||||||
|
"""返回 Admin Agent Registry 权威 schema(平台枚举、Catalog、handler_config schema)。"""
|
||||||
|
from app.services.agent_registry.admin_schema import build_agent_registry_schema
|
||||||
|
|
||||||
|
return ok(build_agent_registry_schema(), request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/infer-content-profile', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def infer_agent_content_profile():
|
||||||
|
"""根据 intent_routes 推断 content_profile(Admin 表单建议,不参与运行时)。"""
|
||||||
|
from app.services.agent_registry.content_profiles import infer_content_profile_from_intent_routes
|
||||||
|
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
routes = data.get('intent_routes') if isinstance(data.get('intent_routes'), list) else []
|
||||||
|
profile = infer_content_profile_from_intent_routes(routes)
|
||||||
|
return ok({'content_profile': profile}, request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/type-catalog', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_agent_type_catalog():
|
||||||
|
"""返回 Admin 应用类型 Catalog 下拉列表。"""
|
||||||
|
from app.services.agent_registry.catalog import list_type_catalog
|
||||||
|
|
||||||
|
return ok(list_type_catalog(), request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/content-profiles', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_agent_content_profiles():
|
||||||
|
"""返回 Admin 可选 content_profile 及默认文案模板。"""
|
||||||
|
from app.services.agent_registry.content_profiles import list_content_profiles
|
||||||
|
|
||||||
|
return ok(list_content_profiles(), request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/intent-routes', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_agent_intent_routes():
|
||||||
|
"""返回 Admin 可选 Intent route 注册表(前端表单动态选项)。"""
|
||||||
|
from app.services.chat.intent_route_registry import list_chat_intent_route_definitions
|
||||||
|
|
||||||
|
return ok(list_chat_intent_route_definitions(), request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_agents():
|
||||||
|
"""返回全部 Agent 列表。"""
|
||||||
|
return ok(agent_service.list_agents(), request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def create_agent():
|
||||||
|
"""创建 Agent。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
payload = agent_service.create_agent(data)
|
||||||
|
return ok(payload, request_id=_request_id(), status=201)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/<int:id>', methods=['PUT'])
|
||||||
|
@require_admin
|
||||||
|
def update_agent(id: int):
|
||||||
|
"""更新 Agent。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
agent_service.update_agent(id, data)
|
||||||
|
return ok({'status': 'ok'}, request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/<int:id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_agent(id: int):
|
||||||
|
"""删除 Agent。"""
|
||||||
|
agent_service.delete_agent(id)
|
||||||
|
return ok({'status': 'ok'}, request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/<int:id>/test', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def test_agent(id: int):
|
||||||
|
"""测试 Agent 连通性。"""
|
||||||
|
payload = agent_service.test_agent_connectivity(id)
|
||||||
|
return ok(payload, request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def update_agent_permissions(id: int):
|
||||||
|
"""设置 Agent 授权用户列表。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
user_ids = data.get('user_ids', [])
|
||||||
|
agent_service.update_agent_permissions(id, user_ids)
|
||||||
|
return ok({'status': 'ok'}, request_id=_request_id())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/agents/<int:id>/training-question-bank/import-pdf', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def import_training_question_bank_from_pdf(id: int):
|
||||||
|
"""
|
||||||
|
从已上传的培训试题 PDF 解析题库。
|
||||||
|
|
||||||
|
用途:给 Agent 管理表单提供“从试题 PDF 导入题库”入口,返回结构化题目供前端回填并继续人工微调。
|
||||||
|
"""
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
payload = agent_service.import_training_question_bank_from_pdf(
|
||||||
|
agent_id=id,
|
||||||
|
guide_id=data.get('guide_id'),
|
||||||
|
)
|
||||||
|
return ok(payload, request_id=_request_id())
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/announcements.py
|
||||||
|
|
||||||
|
用途:管理后台公告 CRUD API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/announcement_service。
|
||||||
|
逻辑:/announcements* 路由;工作台只读见 api/workspace/announcements.py。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import announcement_service
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/announcements', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_announcements():
|
||||||
|
"""列出全部公告(含 is_active)。"""
|
||||||
|
return jsonify(announcement_service.list_announcements())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/announcements', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def create_announcement():
|
||||||
|
"""创建公告。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
payload = announcement_service.create_announcement(data)
|
||||||
|
return jsonify(payload), 201
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/announcements/<int:id>', methods=['PUT'])
|
||||||
|
@require_admin
|
||||||
|
def update_announcement(id: int):
|
||||||
|
"""更新公告。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(announcement_service.update_announcement(id, data))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/announcements/<int:id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_announcement(id: int):
|
||||||
|
"""删除公告。"""
|
||||||
|
return jsonify(announcement_service.delete_announcement(id))
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/blueprint.py
|
||||||
|
|
||||||
|
用途:管理后台 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||||
|
依赖:Flask Blueprint。
|
||||||
|
逻辑:dashboard、departments、users、wecom 等子模块在此 bp 上注册路由;__init__ 导出 admin_bp。
|
||||||
|
"""
|
||||||
|
from flask import Blueprint
|
||||||
|
|
||||||
|
admin_bp = Blueprint('admin', __name__)
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/dashboard.py
|
||||||
|
|
||||||
|
用途:管理后台仪表盘 API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/dashboard_service。
|
||||||
|
逻辑:/dashboard* 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import dashboard_service
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/dashboard/summary', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def dashboard_summary():
|
||||||
|
"""
|
||||||
|
管理后台仪表盘概览(供 Dashboard 页单次请求)。
|
||||||
|
GET /api/admin/dashboard/summary
|
||||||
|
"""
|
||||||
|
return jsonify(dashboard_service.compute_dashboard_summary())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/dashboard/badges', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def dashboard_badges():
|
||||||
|
"""
|
||||||
|
管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。
|
||||||
|
GET /api/admin/dashboard/badges
|
||||||
|
"""
|
||||||
|
return jsonify(dashboard_service.compute_dashboard_badges())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/dashboard', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def dashboard_stats():
|
||||||
|
"""
|
||||||
|
仪表盘统计(遗留接口;新代码请用 /dashboard/summary 与 /dashboard/badges)。
|
||||||
|
GET /api/admin/dashboard
|
||||||
|
"""
|
||||||
|
return jsonify(dashboard_service.compute_legacy_dashboard_stats())
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/database.py
|
||||||
|
|
||||||
|
用途:管理后台数据表浏览 API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/database_admin_service。
|
||||||
|
逻辑:/database/* 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import database_admin_service
|
||||||
|
|
||||||
|
|
||||||
|
def _query_params() -> dict[str, str]:
|
||||||
|
return {k: str(v) for k, v in request.args.items()}
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/database/<table>', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_table_data(table: str):
|
||||||
|
"""浏览指定表数据(最多 100 行)。"""
|
||||||
|
return jsonify(database_admin_service.get_table_data(table, _query_params()))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/database/chat_logs/batch-delete', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def batch_delete_chat_logs():
|
||||||
|
"""批量删除 chat_logs。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(database_admin_service.batch_delete_chat_logs(data.get('ids', [])))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/database/<table>/count', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_table_count(table: str):
|
||||||
|
"""返回表行数。"""
|
||||||
|
return jsonify(database_admin_service.get_table_count(table, _query_params()))
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/departments.py
|
||||||
|
|
||||||
|
用途:管理后台部门 CRUD API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/department_service。
|
||||||
|
逻辑:/departments* 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import department_service
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/departments', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_departments():
|
||||||
|
"""返回全部部门列表。"""
|
||||||
|
return jsonify(department_service.list_departments())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/departments', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def create_department():
|
||||||
|
"""创建部门。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
payload = department_service.create_department(data)
|
||||||
|
return jsonify(payload), 201
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||||
|
@require_admin
|
||||||
|
def update_department(id: int):
|
||||||
|
"""更新部门。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
department_service.update_department(id, data)
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/departments/<int:id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_department(id: int):
|
||||||
|
"""删除部门。"""
|
||||||
|
department_service.delete_department(id)
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/faq_candidates.py
|
||||||
|
|
||||||
|
用途:热点 FAQ 候选管理 API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/faq_service。
|
||||||
|
逻辑:/faq-candidates* 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import faq_service
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/faq-candidates', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_faq_candidates():
|
||||||
|
"""列出 PostgreSQL 热点 FAQ 候选。"""
|
||||||
|
agent_id = request.args.get('agent_id', type=int)
|
||||||
|
return jsonify(faq_service.list_faq_candidates(agent_id=agent_id))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/faq-candidates/refresh', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def refresh_faq_candidates():
|
||||||
|
"""手动触发离线热点聚合。"""
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
agent_id = data.get('agent_id')
|
||||||
|
dry_run = bool(data.get('dry_run'))
|
||||||
|
if agent_id is not None:
|
||||||
|
agent_id = int(agent_id)
|
||||||
|
return jsonify(faq_service.refresh_faq_candidates(agent_id=agent_id, dry_run=dry_run))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/faq-candidates/promote', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def promote_faq_candidate():
|
||||||
|
"""将热点候选晋升为 QuickQuestion。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(faq_service.promote_faq_candidate(data))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/faq-candidates/dismiss', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def dismiss_faq_candidate():
|
||||||
|
"""忽略热点 FAQ 候选。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
agent_id = data.get('agent_id')
|
||||||
|
q_norm = str(data.get('q_norm') or '')
|
||||||
|
return jsonify(faq_service.dismiss_faq_candidate(agent_id=int(agent_id), q_norm=q_norm))
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/guides.py
|
||||||
|
|
||||||
|
用途:Agent 引导资料 API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/guide_service。
|
||||||
|
逻辑:/guides* 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import guide_service
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/guides/upload', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def upload_guide():
|
||||||
|
"""上传引导文件至 MinIO。"""
|
||||||
|
file = request.files.get('file')
|
||||||
|
return jsonify(guide_service.upload_guide_file(file))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/guides', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def create_guide():
|
||||||
|
"""创建引导记录。"""
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
current_user = get_current_user()
|
||||||
|
payload = guide_service.create_guide(data, created_by_id=getattr(current_user, 'id', None))
|
||||||
|
return jsonify(payload)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/guides', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_guides():
|
||||||
|
"""列出引导资料,可按 agent_id 过滤。"""
|
||||||
|
agent_id_raw = request.args.get('agent_id')
|
||||||
|
agent_id = int(agent_id_raw) if agent_id_raw else None
|
||||||
|
return jsonify(guide_service.list_guides(agent_id=agent_id))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/guides/<int:id>', methods=['PUT'])
|
||||||
|
@require_admin
|
||||||
|
def update_guide(id: int):
|
||||||
|
"""更新引导元数据。"""
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
guide_service.update_guide(id, data)
|
||||||
|
return jsonify({'success': True})
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/guides/<int:id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_guide(id: int):
|
||||||
|
"""删除引导及 MinIO 文件。"""
|
||||||
|
guide_service.delete_guide(id)
|
||||||
|
return jsonify({'success': True})
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/permissions.py
|
||||||
|
|
||||||
|
用途:管理后台权限批量更新与权限申请审批 API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/permission_service。
|
||||||
|
逻辑:/permissions/*、/permission-requests/*、/users/<id>/permissions 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import permission_service
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/permissions/batch', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def batch_update_permissions():
|
||||||
|
"""批量更新用户 Agent 权限(add / remove / set)。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(permission_service.batch_update_permissions(data))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:id>/permissions', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def update_user_permissions(id: int):
|
||||||
|
"""将指定用户的 Agent 权限重置为请求体 agent_ids。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(permission_service.update_user_permissions(id, data))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/permission-requests', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_permission_requests():
|
||||||
|
"""列出全部权限申请。"""
|
||||||
|
return jsonify(permission_service.list_permission_requests())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/permission-requests/<int:id>/approve', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def approve_request(id: int):
|
||||||
|
"""批准权限申请。"""
|
||||||
|
return jsonify(permission_service.approve_permission_request(id))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/permission-requests/<int:id>/reject', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def reject_request(id: int):
|
||||||
|
"""拒绝权限申请。"""
|
||||||
|
return jsonify(permission_service.reject_permission_request(id))
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/quick_questions.py
|
||||||
|
|
||||||
|
用途:全局常用问题 CRUD API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/faq_service。
|
||||||
|
逻辑:/quick-questions* 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import faq_service
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/quick-questions', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_quick_questions():
|
||||||
|
"""列出全局常用问题,可选 stale_only 过滤。"""
|
||||||
|
stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'}
|
||||||
|
return jsonify(faq_service.list_quick_questions(stale_only=stale_only))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/quick-questions', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def create_quick_question():
|
||||||
|
"""创建全局常用问题。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
payload = faq_service.create_quick_question(data)
|
||||||
|
return jsonify(payload), 201
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/quick-questions/<int:id>', methods=['PUT'])
|
||||||
|
@require_admin
|
||||||
|
def update_quick_question(id: int):
|
||||||
|
"""更新全局常用问题。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
faq_service.update_quick_question(id, data)
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/quick-questions/<int:id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_quick_question(id: int):
|
||||||
|
"""删除全局常用问题。"""
|
||||||
|
faq_service.delete_quick_question(id)
|
||||||
|
return jsonify({'status': 'ok'})
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/reports.py
|
||||||
|
|
||||||
|
用途:管理后台报表 API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/report_service。
|
||||||
|
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import report_service
|
||||||
|
|
||||||
|
|
||||||
|
def _query_params() -> dict[str, str]:
|
||||||
|
return {k: str(v) for k, v in request.args.items()}
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/reports/usage', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def usage_report():
|
||||||
|
"""聊天使用分析报表(支持时间范围 range=7d|30d|90d|180d|365d)。"""
|
||||||
|
try:
|
||||||
|
user_page = int(request.args.get('user_page', 1))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
user_page = 1
|
||||||
|
try:
|
||||||
|
user_page_size = int(request.args.get('user_page_size', 10))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
user_page_size = 10
|
||||||
|
range_key = request.args.get('range')
|
||||||
|
return jsonify(
|
||||||
|
report_service.build_usage_report(
|
||||||
|
user_page=user_page,
|
||||||
|
user_page_size=user_page_size,
|
||||||
|
range_key=range_key,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/reports/applications', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def applications_report():
|
||||||
|
"""
|
||||||
|
应用运营报表:按应用聚合使用 / 权限 / 评分。
|
||||||
|
Query: range, status, usage, q, sort, order, page, page_size。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
page = int(request.args.get('page', 1))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
page = 1
|
||||||
|
try:
|
||||||
|
page_size = int(request.args.get('page_size', 20))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
page_size = 20
|
||||||
|
return jsonify(
|
||||||
|
report_service.build_application_report(
|
||||||
|
range_key=request.args.get('range'),
|
||||||
|
status=request.args.get('status'),
|
||||||
|
usage=request.args.get('usage'),
|
||||||
|
q=request.args.get('q'),
|
||||||
|
sort=request.args.get('sort'),
|
||||||
|
order=request.args.get('order'),
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/reports/feedback', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def feedback_report():
|
||||||
|
"""反馈评分分布报表。"""
|
||||||
|
return jsonify(report_service.build_feedback_report())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/reports/general-feedbacks', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_general_feedbacks_report():
|
||||||
|
"""通用反馈列表。"""
|
||||||
|
return jsonify(report_service.list_general_feedbacks_report(_query_params()))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/reports/general-feedbacks/count', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def count_general_feedbacks_report():
|
||||||
|
"""通用反馈计数。"""
|
||||||
|
return jsonify(report_service.count_general_feedbacks_report(_query_params()))
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/users.py
|
||||||
|
|
||||||
|
用途:管理后台用户 CRUD API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/user_service、core.auth.jwt。
|
||||||
|
逻辑:/users* 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.auth.jwt import get_current_user as _get_auth_user
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import user_service
|
||||||
|
|
||||||
|
|
||||||
|
def _query_params() -> dict[str, str]:
|
||||||
|
return {k: str(v) for k, v in request.args.items()}
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/users', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_users():
|
||||||
|
"""列出管理端用户(支持分页与筛选)。"""
|
||||||
|
result = user_service.list_users(_query_params())
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/users', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def create_user():
|
||||||
|
"""创建用户并同步 Casdoor。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
payload = user_service.create_user(data)
|
||||||
|
return jsonify(payload), 201
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:id>', methods=['PUT'])
|
||||||
|
@require_admin
|
||||||
|
def update_user(id: int):
|
||||||
|
"""更新用户资料;有 password 时同步 Casdoor 改密。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(user_service.update_user(id, data))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/users/cleanup-rejected', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def cleanup_rejected_users():
|
||||||
|
"""批量删除 status=rejected 的用户。"""
|
||||||
|
return jsonify(user_service.cleanup_rejected_users())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/users/batch-delete', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def batch_delete_users():
|
||||||
|
"""批量删除用户(排除当前登录管理员)。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
current_user = _get_auth_user()
|
||||||
|
current_user_id = current_user.id if current_user else None
|
||||||
|
return jsonify(user_service.batch_delete_users(data.get('user_ids', []), current_user_id=current_user_id))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_user(id: int):
|
||||||
|
"""删除单个用户。"""
|
||||||
|
current_user = _get_auth_user()
|
||||||
|
current_user_id = current_user.id if current_user else None
|
||||||
|
return jsonify(user_service.delete_user(id, current_user_id=current_user_id))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:id>/approve', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def approve_user(id: int):
|
||||||
|
"""审批通过用户。"""
|
||||||
|
return jsonify(user_service.approve_user(id))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/users/<int:id>/reject', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def reject_user(id: int):
|
||||||
|
"""拒绝用户注册。"""
|
||||||
|
return jsonify(user_service.reject_user(id))
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/admin/wecom.py
|
||||||
|
|
||||||
|
用途:管理后台企微绑定、配置与诊断 API(薄路由层)。
|
||||||
|
依赖:admin.blueprint、services/admin/wecom_admin_service。
|
||||||
|
逻辑:/wecom/* 路由。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.admin.blueprint import admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.admin import wecom_admin_service
|
||||||
|
|
||||||
|
|
||||||
|
def _query_params() -> dict[str, str]:
|
||||||
|
return {k: str(v) for k, v in request.args.items()}
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/debug-user-by-code', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def debug_wecom_user_by_code():
|
||||||
|
"""通过 OAuth code 诊断企微用户匹配结果。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(wecom_admin_service.debug_user_by_code(data.get('code')))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/bindings', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def list_wecom_bindings():
|
||||||
|
"""分页列出企微绑定。"""
|
||||||
|
return jsonify(wecom_admin_service.list_bindings(_query_params()))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/bind', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def bind_wecom_user():
|
||||||
|
"""管理员手动绑定企微账号。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(wecom_admin_service.bind_user(data))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/unbind', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def unbind_wecom_user():
|
||||||
|
"""管理员解绑企微账号。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(wecom_admin_service.unbind_user(data))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/provision', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def provision_wecom_user():
|
||||||
|
"""创建/更新用户并绑定企微、分配权限。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
payload, status_code = wecom_admin_service.provision_user(data)
|
||||||
|
return jsonify(payload), status_code
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/login-audits', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_wecom_login_audits():
|
||||||
|
"""查询登录审计(企微/密码等来源)。"""
|
||||||
|
return jsonify(wecom_admin_service.list_login_audits(_query_params()))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT'])
|
||||||
|
@require_admin
|
||||||
|
def wecom_notify_settings():
|
||||||
|
"""读取或更新企微通知配置。"""
|
||||||
|
if request.method == 'GET':
|
||||||
|
return jsonify(wecom_admin_service.serialize_notify_settings())
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(wecom_admin_service.update_notify_settings(data))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT'])
|
||||||
|
@require_admin
|
||||||
|
def wecom_system_settings():
|
||||||
|
"""读取或更新企微 OAuth 系统配置。"""
|
||||||
|
if request.method == 'GET':
|
||||||
|
return jsonify(wecom_admin_service.serialize_system_settings())
|
||||||
|
data = request.get_json() or {}
|
||||||
|
return jsonify(wecom_admin_service.update_system_settings(data))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/integration-manifest', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def wecom_integration_manifest():
|
||||||
|
"""返回企微集成 manifest(回调 URL、OAuth 端点等)。"""
|
||||||
|
return jsonify(
|
||||||
|
wecom_admin_service.integration_manifest(
|
||||||
|
host_url=request.host_url,
|
||||||
|
host=request.host,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/notify-metrics', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def wecom_notify_metrics():
|
||||||
|
"""企微通知发送/打开率指标(近 30 天)。"""
|
||||||
|
return jsonify(wecom_admin_service.notify_metrics())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/binding-stats', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def wecom_binding_stats():
|
||||||
|
"""活跃用户企微绑定统计。"""
|
||||||
|
return jsonify(wecom_admin_service.binding_stats())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/wecom/sync-userids', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def sync_wecom_userids_admin():
|
||||||
|
"""从 OA 按工号同步 users.wecom_userid。"""
|
||||||
|
data = request.get_json() or {}
|
||||||
|
apply = bool(data.get('apply'))
|
||||||
|
return jsonify(wecom_admin_service.sync_userids(apply=apply))
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/agent_runtime_context_tools.py
|
||||||
|
|
||||||
|
用途:暴露 agent_runtime_context 只读 Tool API,供 Dify Chatflow 解析 HXOPS 上下文。
|
||||||
|
依赖:app.core.errors、agent_runtime_context.parser/openapi_spec、shipping_notice.tool_api_url。
|
||||||
|
逻辑:OpenAPI 文档接口放行;parse 工具复用 Authorization Bearer / X-Integration-Key 鉴权,不推进业务状态。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import Blueprint, current_app, jsonify, request
|
||||||
|
|
||||||
|
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError
|
||||||
|
from app.services.agent_runtime_context.openapi_spec import build_agent_runtime_context_openapi_spec
|
||||||
|
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||||
|
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||||
|
|
||||||
|
agent_runtime_context_bp = Blueprint("agent_runtime_context_tools", __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_tool_auth() -> None:
|
||||||
|
"""
|
||||||
|
校验 agent_runtime_context Tool API 鉴权 Header。
|
||||||
|
|
||||||
|
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;Dify 请求 parse 工具时由 before_request 自动触发。
|
||||||
|
|
||||||
|
核心逻辑:只接受 Authorization Bearer 或 X-Integration-Key,复用 INTEGRATION_API_KEY 作为平台工具密钥。
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ServiceUnavailableError: 未配置 INTEGRATION_API_KEY。
|
||||||
|
UnauthorizedError: 缺少或传入错误鉴权。
|
||||||
|
"""
|
||||||
|
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||||
|
if not configured:
|
||||||
|
raise ServiceUnavailableError("INTEGRATION_API_KEY is not configured", code="missing_auth")
|
||||||
|
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||||
|
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||||
|
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||||
|
if configured in {token, integration_key}:
|
||||||
|
return
|
||||||
|
if not token and not integration_key:
|
||||||
|
raise UnauthorizedError("missing_auth")
|
||||||
|
raise UnauthorizedError("invalid_auth")
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_error_code(exc: AppError) -> str:
|
||||||
|
"""
|
||||||
|
归一化 Tool API 错误码。
|
||||||
|
|
||||||
|
核心逻辑:保持与 shipping/file-check Tool API 的 ok:false 响应风格一致,便于 Dify 侧统一处理。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
exc: 业务异常。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tool 侧错误码。
|
||||||
|
"""
|
||||||
|
message = str(exc.message or "").strip()
|
||||||
|
if message in {"missing_auth", "invalid_auth"}:
|
||||||
|
return message
|
||||||
|
if exc.code == "AUTH.UNAUTHORIZED":
|
||||||
|
return "invalid_auth"
|
||||||
|
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||||
|
return "missing_auth"
|
||||||
|
return exc.code
|
||||||
|
|
||||||
|
|
||||||
|
@agent_runtime_context_bp.errorhandler(AppError)
|
||||||
|
def _handle_tool_app_error(exc: AppError):
|
||||||
|
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
|
||||||
|
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||||
|
|
||||||
|
|
||||||
|
@agent_runtime_context_bp.before_request
|
||||||
|
def _verify_tool_access():
|
||||||
|
"""
|
||||||
|
对上下文解析 Tool 做统一 Header 鉴权。
|
||||||
|
|
||||||
|
核心逻辑:OpenAPI 导入文档无需鉴权;parse 工具必须携带平台 Tool Key。
|
||||||
|
"""
|
||||||
|
if request.path.endswith("/openapi.json"):
|
||||||
|
return None
|
||||||
|
_require_tool_auth()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@agent_runtime_context_bp.route("/tools/openapi.json", methods=["GET"])
|
||||||
|
def openapi_spec():
|
||||||
|
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||||
|
return jsonify(build_agent_runtime_context_openapi_spec(resolve_tool_api_base_url()))
|
||||||
|
|
||||||
|
|
||||||
|
@agent_runtime_context_bp.route("/tools/parse", methods=["POST"])
|
||||||
|
def parse_context_tool():
|
||||||
|
"""
|
||||||
|
解析 agent_runtime_context 的白名单字段。
|
||||||
|
|
||||||
|
【AI 触发时机】:Dify 需要读取 HXOPS session/task/batch/run_purpose/state_hint 等上下文字段时调用;
|
||||||
|
不用于推进业务状态。
|
||||||
|
"""
|
||||||
|
payload = request.get_json(silent=True) or {}
|
||||||
|
return jsonify(
|
||||||
|
parse_agent_runtime_context(
|
||||||
|
payload.get("agent_runtime_context"),
|
||||||
|
payload.get("paths"),
|
||||||
|
)
|
||||||
|
)
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/agents.py
|
||||||
|
|
||||||
|
用途:普通用户可见的 Agent 列表与 AgentGuide 静态资源。
|
||||||
|
依赖:app.core.auth.jwt、models、minio_service、agent_registry.serialization。
|
||||||
|
逻辑:按当前用户 RBAC 返回可访问 Agent;列表统一 serialize_agent_for_user_list(结构化列为准)。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import mimetypes
|
||||||
|
import re
|
||||||
|
from flask import Blueprint, Response, jsonify, request, send_from_directory, stream_with_context
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import UnauthorizedError
|
||||||
|
from app.models import Agent, User, AgentGuide
|
||||||
|
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||||
|
from app.services.minio_service import minio_service
|
||||||
|
|
||||||
|
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||||
|
agents_bp = Blueprint('agents', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_agent_row(agent: Agent, *, visible_agent_ids: set[int] | None = None) -> dict:
|
||||||
|
payload = serialize_agent_list_item(agent)
|
||||||
|
if not bool(getattr(agent, 'is_aggregate', False)):
|
||||||
|
return payload
|
||||||
|
from app.services.agent_directory import serialize_directory_members
|
||||||
|
|
||||||
|
members = serialize_directory_members(agent.id, active_only=True)
|
||||||
|
if visible_agent_ids is not None:
|
||||||
|
members = [member for member in members if int(member.get('id') or 0) in visible_agent_ids]
|
||||||
|
if members:
|
||||||
|
payload['directory_members'] = members
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||||
|
"""返回用户可见的完整 Agent ORM 行(含 Registry 结构化列)。"""
|
||||||
|
if user.role == 'admin':
|
||||||
|
return (
|
||||||
|
db.session.query(Agent)
|
||||||
|
.filter(Agent.is_active.is_(True))
|
||||||
|
.order_by(Agent.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
return [agent for agent in user.agents if agent.is_active]
|
||||||
|
|
||||||
|
|
||||||
|
@agents_bp.route('', methods=['GET'])
|
||||||
|
def list_user_agents():
|
||||||
|
"""
|
||||||
|
获取当前用户可见的 Agent 列表
|
||||||
|
用途:Workspace 页面展示应用网格、聊天侧栏 Agent 切换
|
||||||
|
"""
|
||||||
|
user: User = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError()
|
||||||
|
|
||||||
|
agents = _list_active_agents_for_user(user)
|
||||||
|
visible_agent_ids = {agent.id for agent in agents}
|
||||||
|
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
|
||||||
|
|
||||||
|
@agents_bp.route('/<int:agent_id>/guides', methods=['GET'])
|
||||||
|
def list_agent_guides(agent_id):
|
||||||
|
"""
|
||||||
|
获取指定应用的新手指南列表 (需登录)
|
||||||
|
用途:客户端 Chat 界面点击新手指南
|
||||||
|
"""
|
||||||
|
get_current_user() # 确保已登录
|
||||||
|
|
||||||
|
if agent_id == 0:
|
||||||
|
generic_agent = (
|
||||||
|
db.session.query(Agent)
|
||||||
|
.filter_by(agent_code='generic', is_active=True)
|
||||||
|
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if generic_agent:
|
||||||
|
agent_id = generic_agent.id
|
||||||
|
else:
|
||||||
|
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,
|
||||||
|
'guide_usage': g.guide_usage,
|
||||||
|
'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 列表 (无需登录)
|
||||||
|
用途:登录页面展示
|
||||||
|
"""
|
||||||
|
agents = (
|
||||||
|
db.session.query(Agent)
|
||||||
|
.filter(Agent.is_active.is_(True))
|
||||||
|
.order_by(Agent.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
visible_agent_ids = {agent.id for agent in agents}
|
||||||
|
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
|
||||||
|
|
||||||
|
def _parse_byte_range(range_header: str, file_size: int) -> tuple[int, int] | None:
|
||||||
|
"""
|
||||||
|
解析浏览器单段字节范围请求。
|
||||||
|
|
||||||
|
用途:iOS Safari/企业微信播放 MP4 时依赖 Range 请求,本函数将请求转换为闭区间。
|
||||||
|
参数约束:仅接受单个 bytes 范围;无效或越界范围返回 None。
|
||||||
|
"""
|
||||||
|
match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header.strip())
|
||||||
|
if not match or file_size <= 0:
|
||||||
|
return None
|
||||||
|
start_text, end_text = match.groups()
|
||||||
|
if not start_text and not end_text:
|
||||||
|
return None
|
||||||
|
if start_text:
|
||||||
|
start = int(start_text)
|
||||||
|
end = int(end_text) if end_text else file_size - 1
|
||||||
|
else:
|
||||||
|
suffix_length = int(end_text)
|
||||||
|
if suffix_length <= 0:
|
||||||
|
return None
|
||||||
|
start = max(file_size - suffix_length, 0)
|
||||||
|
end = file_size - 1
|
||||||
|
if start >= file_size or end < start:
|
||||||
|
return None
|
||||||
|
return start, min(end, file_size - 1)
|
||||||
|
|
||||||
|
|
||||||
|
def _stream_minio_guide_file(filename: str) -> Response:
|
||||||
|
"""
|
||||||
|
以同源流式响应返回 MinIO 指南文件。
|
||||||
|
|
||||||
|
用途:消除生产 HTTPS 页面加载 HTTP MinIO 地址的混合内容问题,并支持 iOS 所需的 206 响应。
|
||||||
|
参数约束:filename 为系统生成的 MinIO 对象名;响应流结束后必须释放连接。
|
||||||
|
"""
|
||||||
|
stat = minio_service.stat_file(filename)
|
||||||
|
file_size = int(stat.size)
|
||||||
|
content_type = stat.content_type or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
|
||||||
|
requested_range = request.headers.get('Range', '').strip()
|
||||||
|
byte_range = _parse_byte_range(requested_range, file_size) if requested_range else None
|
||||||
|
if requested_range and byte_range is None:
|
||||||
|
return Response(status=416, headers={'Content-Range': f'bytes */{file_size}'})
|
||||||
|
|
||||||
|
start, end = byte_range or (0, file_size - 1)
|
||||||
|
content_length = end - start + 1
|
||||||
|
source = minio_service.open_file_stream(filename, offset=start, length=content_length)
|
||||||
|
|
||||||
|
def generate():
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
chunk = source.read(64 * 1024)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
yield chunk
|
||||||
|
finally:
|
||||||
|
source.close()
|
||||||
|
source.release_conn()
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
'Accept-Ranges': 'bytes',
|
||||||
|
'Content-Length': str(content_length),
|
||||||
|
'Cache-Control': 'private, max-age=3600',
|
||||||
|
}
|
||||||
|
status = 206 if byte_range else 200
|
||||||
|
if byte_range:
|
||||||
|
headers['Content-Range'] = f'bytes {start}-{end}/{file_size}'
|
||||||
|
return Response(stream_with_context(generate()), status=status, headers=headers, content_type=content_type)
|
||||||
|
|
||||||
|
|
||||||
|
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
|
||||||
|
def serve_guide_file(filename):
|
||||||
|
"""
|
||||||
|
返回本地或 MinIO 中的指南文件。
|
||||||
|
|
||||||
|
用途:为 PDF、图片和培训视频提供统一同源地址;本地文件沿用 Flask 条件响应,MinIO 文件支持 Range。
|
||||||
|
参数约束:filename 仅用于系统指南存储目录或 MinIO 指南桶,不接受任意外部路径。
|
||||||
|
"""
|
||||||
|
local_directory = os.path.join(os.getcwd(), 'data', 'agent-guides')
|
||||||
|
if os.path.isfile(os.path.join(local_directory, filename)):
|
||||||
|
return send_from_directory(local_directory, filename, conditional=True)
|
||||||
|
return _stream_minio_guide_file(filename)
|
||||||
|
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,162 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/chat_turns.py
|
||||||
|
|
||||||
|
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||||||
|
依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。
|
||||||
|
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from flask import Response, g, request, stream_with_context
|
||||||
|
|
||||||
|
from app.core.decorators import require_agent_permission
|
||||||
|
from app.core.errors import AppError, ValidationError
|
||||||
|
from app.services.chat.turn_runtime import ChatTurnRuntime
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_turn_body_and_files() -> tuple[dict, list]:
|
||||||
|
"""
|
||||||
|
解析 Chat Turn 请求体;multipart 时从 form 字段读取 JSON 与 files。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(body, uploads) — uploads 为 Werkzeug FileStorage 列表,JSON 请求时为空。
|
||||||
|
"""
|
||||||
|
content_type = str(request.content_type or "")
|
||||||
|
if "multipart/form-data" in content_type:
|
||||||
|
input_raw = request.form.get("input") or "{}"
|
||||||
|
try:
|
||||||
|
input_data = json.loads(input_raw)
|
||||||
|
except json.JSONDecodeError as exc:
|
||||||
|
raise ValidationError("input must be valid JSON") from exc
|
||||||
|
context_raw = request.form.get("context") or "{}"
|
||||||
|
try:
|
||||||
|
context_data = json.loads(context_raw) if context_raw else {}
|
||||||
|
except json.JSONDecodeError as exc:
|
||||||
|
raise ValidationError("context must be valid JSON") from exc
|
||||||
|
agent_id = request.form.get("agent_id") or request.form.get("agentId")
|
||||||
|
conversation_id = request.form.get("conversation_id") or request.form.get("conversationId")
|
||||||
|
body: dict = {
|
||||||
|
"agent_id": agent_id,
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
"input": input_data if isinstance(input_data, dict) else {},
|
||||||
|
"context": context_data if isinstance(context_data, dict) else {},
|
||||||
|
}
|
||||||
|
uploads = request.files.getlist("files")
|
||||||
|
if not uploads:
|
||||||
|
single = request.files.get("file")
|
||||||
|
if single:
|
||||||
|
uploads = [single]
|
||||||
|
return body, uploads
|
||||||
|
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
return body if isinstance(body, dict) else {}, []
|
||||||
|
|
||||||
|
|
||||||
|
def _stage_upload_files(uploads: list) -> list[dict]:
|
||||||
|
"""将 multipart 文件读入内存 staged 结构,供 handler 构造 FileStorage。"""
|
||||||
|
staged: list[dict] = []
|
||||||
|
for upload in uploads:
|
||||||
|
if upload is None:
|
||||||
|
continue
|
||||||
|
data = upload.read() or b""
|
||||||
|
if not data:
|
||||||
|
continue
|
||||||
|
staged.append({
|
||||||
|
"filename": str(getattr(upload, "filename", None) or "upload"),
|
||||||
|
"content_type": str(getattr(upload, "content_type", None) or ""),
|
||||||
|
"data": data,
|
||||||
|
})
|
||||||
|
return staged
|
||||||
|
|
||||||
|
|
||||||
|
def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
|
||||||
|
"""
|
||||||
|
将 multipart 附件写入 Turn input.payload。
|
||||||
|
|
||||||
|
- shipping.create_batch_from_notices:预检 notice_items
|
||||||
|
- shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节
|
||||||
|
"""
|
||||||
|
if not uploads:
|
||||||
|
return
|
||||||
|
input_block = body.get("input") if isinstance(body.get("input"), dict) else {}
|
||||||
|
action_type = str(input_block.get("action_type") or input_block.get("actionType") or "").strip()
|
||||||
|
payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {}
|
||||||
|
payload = dict(payload)
|
||||||
|
|
||||||
|
if action_type == "shipping.create_batch_from_notices":
|
||||||
|
from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch
|
||||||
|
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||||
|
|
||||||
|
temp_request_id = uuid.uuid4().hex
|
||||||
|
try:
|
||||||
|
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||||
|
finally:
|
||||||
|
cleanup_temp_notice_uploads(temp_request_id)
|
||||||
|
if not notice_items:
|
||||||
|
raise ValidationError(
|
||||||
|
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
|
||||||
|
details={"file_summary": file_summary},
|
||||||
|
)
|
||||||
|
payload["notice_items"] = notice_items
|
||||||
|
payload["file_summary"] = file_summary
|
||||||
|
conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip()
|
||||||
|
if conversation_id:
|
||||||
|
payload["conversation_id"] = conversation_id
|
||||||
|
elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
|
||||||
|
staged = _stage_upload_files(uploads)
|
||||||
|
if not staged:
|
||||||
|
raise ValidationError("file is required")
|
||||||
|
payload["_staged_files"] = staged
|
||||||
|
else:
|
||||||
|
return
|
||||||
|
|
||||||
|
input_block["payload"] = payload
|
||||||
|
input_block["type"] = input_block.get("type") or "upload_followup"
|
||||||
|
body["input"] = input_block
|
||||||
|
|
||||||
|
|
||||||
|
def register_chat_turn_routes(chat_bp) -> None:
|
||||||
|
"""将 Chat Turn 路由注册到 chat Blueprint。"""
|
||||||
|
|
||||||
|
@chat_bp.route('/turns/stream', methods=['POST'])
|
||||||
|
@require_agent_permission
|
||||||
|
def chat_turns_stream():
|
||||||
|
"""
|
||||||
|
统一 Chat Turn SSE 接口。
|
||||||
|
|
||||||
|
核心逻辑:解析 action/form_submit/upload_followup;multipart 时预检附件并注入 payload,
|
||||||
|
经 ChatTurnRuntime 路由至 action handler,返回 run.started / step.* / message.* / run.completed。
|
||||||
|
"""
|
||||||
|
user = getattr(g, 'current_user', None)
|
||||||
|
agent = getattr(g, 'current_agent', None)
|
||||||
|
if user is None or agent is None:
|
||||||
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||||
|
|
||||||
|
body, uploads = _parse_turn_body_and_files()
|
||||||
|
request_id = uuid.uuid4().hex[:12]
|
||||||
|
# [STEP 1] multipart 附件必须在返回 SSE 前读完;生成器延迟执行时 request.files 可能已关闭。
|
||||||
|
if uploads:
|
||||||
|
_inject_multipart_upload_payload(body, uploads)
|
||||||
|
|
||||||
|
def relay_stream():
|
||||||
|
yield from ChatTurnRuntime.stream(
|
||||||
|
user=user,
|
||||||
|
agent=agent,
|
||||||
|
body=body,
|
||||||
|
request_id=request_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
return Response(
|
||||||
|
stream_with_context(relay_stream()),
|
||||||
|
mimetype='text/event-stream',
|
||||||
|
headers={
|
||||||
|
'Cache-Control': 'no-cache',
|
||||||
|
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||||
|
'Connection': 'keep-alive',
|
||||||
|
'X-Accel-Buffering': 'no',
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,562 @@
|
|||||||
|
"""
|
||||||
|
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.core.errors import (
|
||||||
|
AppError,
|
||||||
|
ConflictError,
|
||||||
|
NotFoundError,
|
||||||
|
ServiceUnavailableError,
|
||||||
|
UnauthorizedError,
|
||||||
|
ValidationError,
|
||||||
|
)
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
|
||||||
|
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hxops_user_facing_base_url
|
||||||
|
from app.services.schedule import _build_srm_conn_str
|
||||||
|
from app.services.schedule.query_service import get_run, serialize_run
|
||||||
|
from app.services.schedule.srm_service import _fetch_records
|
||||||
|
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||||
|
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||||
|
|
||||||
|
try:
|
||||||
|
import pyodbc # type: ignore
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
pyodbc = None
|
||||||
|
|
||||||
|
|
||||||
|
file_check_bp = Blueprint("file_check_tools", __name__)
|
||||||
|
|
||||||
|
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
|
||||||
|
_RUN_START_LOCK = threading.Lock()
|
||||||
|
_TASK_LOCK_KEY_BASE = 8700000000
|
||||||
|
|
||||||
|
|
||||||
|
def _download_token_secret() -> str:
|
||||||
|
"""
|
||||||
|
Excel 下载 JWT 签名密钥。
|
||||||
|
|
||||||
|
核心逻辑:与 Dify Tool API Key 分离,仅用 SECRET_KEY,避免 API Key 未配置时浏览器下载失败。
|
||||||
|
"""
|
||||||
|
return str(current_app.config.get("SECRET_KEY") or "default-secret").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_download_token(token: str | None) -> dict | None:
|
||||||
|
normalized = str(token or "").strip()
|
||||||
|
if not normalized:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
import jwt
|
||||||
|
|
||||||
|
payload = jwt.decode(normalized, _download_token_secret(), algorithms=["HS256"])
|
||||||
|
return payload if isinstance(payload, dict) else None
|
||||||
|
except Exception as exc:
|
||||||
|
current_app.logger.warning("[file-check-tool] download token validation failed: %s", exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _require_tool_auth() -> None:
|
||||||
|
"""
|
||||||
|
校验 Tool API 访问权限。
|
||||||
|
|
||||||
|
核心逻辑:Excel 下载仅校验 query token(浏览器场景);其余端点校验 Dify/RPA 的 Tool API Key。
|
||||||
|
"""
|
||||||
|
# [STEP 1] 浏览器 Excel 下载:JWT token 独立于 Tool API Key
|
||||||
|
if request.path.endswith("/excel"):
|
||||||
|
query_token = str(request.args.get("token") or "").strip()
|
||||||
|
if query_token:
|
||||||
|
if _decode_download_token(query_token):
|
||||||
|
return
|
||||||
|
raise UnauthorizedError("invalid_auth")
|
||||||
|
|
||||||
|
# [STEP 2] Dify / RPA 服务端调用
|
||||||
|
configured = str(
|
||||||
|
current_app.config.get("FILE_CHECK_TOOL_API_KEY")
|
||||||
|
or current_app.config.get("INTEGRATION_API_KEY")
|
||||||
|
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()
|
||||||
|
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||||
|
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||||
|
if configured in {api_token, integration_key}:
|
||||||
|
return
|
||||||
|
if not api_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 == "data_source_unavailable":
|
||||||
|
return "data_source_unavailable"
|
||||||
|
if exc.code == "AUTH.UNAUTHORIZED":
|
||||||
|
return "invalid_auth"
|
||||||
|
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||||
|
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:
|
||||||
|
"""用户可见下载链基地址;与 Dify 调 Tool API 的内网基地址分离。"""
|
||||||
|
return resolve_hxops_user_facing_base_url()
|
||||||
|
|
||||||
|
|
||||||
|
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, _download_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_tool_run_binding import (
|
||||||
|
_has_ambiguous_pending_turns,
|
||||||
|
bind_schedule_run,
|
||||||
|
)
|
||||||
|
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
|
||||||
|
|
||||||
|
turn_id = str(data.get("hxops_turn_id") or "").strip()
|
||||||
|
session_id = str(data.get("hxops_session_id") or "").strip() or None
|
||||||
|
user_message = str(data.get("user_message") or "").strip() or None
|
||||||
|
bound = bind_schedule_run(
|
||||||
|
schedule_run_id=int(run.id),
|
||||||
|
turn_id=turn_id or None,
|
||||||
|
session_id=session_id,
|
||||||
|
user_message=user_message,
|
||||||
|
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||||
|
bind_source='tool_start',
|
||||||
|
)
|
||||||
|
ambiguous = _has_ambiguous_pending_turns(
|
||||||
|
session_id=session_id,
|
||||||
|
user_message=user_message,
|
||||||
|
schedule_task_id=int(run.schedule_task_id) if run.schedule_task_id else None,
|
||||||
|
)
|
||||||
|
if bound or (not ambiguous and (turn_id or session_id)):
|
||||||
|
merge_chat_log_bind_context(run, data)
|
||||||
|
if bound and turn_id:
|
||||||
|
attach_run_to_turn(turn_id, int(run.id))
|
||||||
|
|
||||||
|
|
||||||
|
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 _raise_data_source_unavailable(task: ScheduleTask, exc: Exception) -> None:
|
||||||
|
"""
|
||||||
|
将检核预检阶段的数据源连接/配置错误转为 Tool API 503。
|
||||||
|
|
||||||
|
核心逻辑:ODBC/SQL Server 不可用时返回 data_source_unavailable,避免 Dify 收到 500 后显示 maximum retries。
|
||||||
|
"""
|
||||||
|
current_app.logger.warning(
|
||||||
|
"[file-check-tool] precheck data source unavailable task_id=%s error=%s",
|
||||||
|
task.id,
|
||||||
|
exc,
|
||||||
|
exc_info=True,
|
||||||
|
)
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"检核数据源不可用,请检查排程 SQL 配置、SRM_SQLSERVER_* 环境变量及本机 ODBC 驱动",
|
||||||
|
code="data_source_unavailable",
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _precheck_no_data(task: ScheduleTask) -> dict | None:
|
||||||
|
"""
|
||||||
|
启动前预检当前任务是否存在待检资料。
|
||||||
|
|
||||||
|
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
|
||||||
|
避免创建空批次并向 ChatLog 回写 run_id。数据源连接失败时抛 503 data_source_unavailable。
|
||||||
|
"""
|
||||||
|
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
|
||||||
|
|
||||||
|
try:
|
||||||
|
if cfg.data_source and not cfg.data_source.is_empty():
|
||||||
|
conn_str = cfg.data_source.build_connection_string()
|
||||||
|
else:
|
||||||
|
conn_str = _build_srm_conn_str()
|
||||||
|
rows = _fetch_records(conn_str, cfg.fetch_sql)
|
||||||
|
except RuntimeError as exc:
|
||||||
|
_raise_data_source_unavailable(task, exc)
|
||||||
|
except Exception as exc:
|
||||||
|
if pyodbc is not None and isinstance(exc, pyodbc.Error):
|
||||||
|
_raise_data_source_unavailable(task, exc)
|
||||||
|
raise
|
||||||
|
|
||||||
|
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"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
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()))
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/files/__init__.py
|
||||||
|
|
||||||
|
用途:平台级文件资产 API 包入口。
|
||||||
|
依赖:files.assets。
|
||||||
|
逻辑:register_blueprints 挂载 /api/files。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from app.api.files.assets import files_bp
|
||||||
|
|
||||||
|
__all__ = ['files_bp']
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/files/assets.py
|
||||||
|
|
||||||
|
用途:通用文件资产上传、查询、删除与受控下载 API。
|
||||||
|
依赖:file_assets.service、app.core.auth.jwt、app.core.response。
|
||||||
|
逻辑:薄路由鉴权与参数校验;storage_key 不向前端返回。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
|
||||||
|
from flask import Blueprint, g, request, send_file
|
||||||
|
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import UnauthorizedError
|
||||||
|
from app.core.response import ok
|
||||||
|
from app.services.file_assets.service import (
|
||||||
|
delete_temporary_asset,
|
||||||
|
get_asset_for_user,
|
||||||
|
read_asset_bytes,
|
||||||
|
serialize_asset_public,
|
||||||
|
upload_file_asset,
|
||||||
|
)
|
||||||
|
|
||||||
|
files_bp = Blueprint('files', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_user():
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@files_bp.route('/assets', methods=['POST'])
|
||||||
|
def upload_asset():
|
||||||
|
"""上传文件并创建 FileAsset。"""
|
||||||
|
user = _require_user()
|
||||||
|
upload = request.files.get('file')
|
||||||
|
if not upload:
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
|
||||||
|
raise ValidationError('file is required')
|
||||||
|
if not upload.filename:
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
|
||||||
|
raise ValidationError('file is required')
|
||||||
|
data = upload_file_asset(user_id=user.id, upload=upload)
|
||||||
|
return ok(data, request_id=getattr(g, 'request_id', None), status=201)
|
||||||
|
|
||||||
|
|
||||||
|
@files_bp.route('/assets/<asset_no>', methods=['GET'])
|
||||||
|
def get_asset(asset_no: str):
|
||||||
|
"""查询当前用户的文件资产元数据。"""
|
||||||
|
user = _require_user()
|
||||||
|
asset = get_asset_for_user(asset_no, user.id)
|
||||||
|
return ok(serialize_asset_public(asset), request_id=getattr(g, 'request_id', None))
|
||||||
|
|
||||||
|
|
||||||
|
@files_bp.route('/assets/<asset_no>', methods=['DELETE'])
|
||||||
|
def delete_asset(asset_no: str):
|
||||||
|
"""逻辑删除未引用的临时资产。"""
|
||||||
|
user = _require_user()
|
||||||
|
delete_temporary_asset(asset_no=asset_no, user_id=user.id)
|
||||||
|
return ok({'deleted': True}, request_id=getattr(g, 'request_id', None))
|
||||||
|
|
||||||
|
|
||||||
|
@files_bp.route('/assets/<asset_no>/download', methods=['GET'])
|
||||||
|
def download_asset(asset_no: str):
|
||||||
|
"""鉴权后流式下载文件内容。"""
|
||||||
|
user = _require_user()
|
||||||
|
asset = get_asset_for_user(asset_no, user.id)
|
||||||
|
data = read_asset_bytes(asset)
|
||||||
|
return send_file(
|
||||||
|
io.BytesIO(data),
|
||||||
|
mimetype=asset.mime_type or 'application/octet-stream',
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=asset.original_filename,
|
||||||
|
)
|
||||||
@@ -0,0 +1,312 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/integration.py
|
||||||
|
文件用途:知识库外部集成查询接口
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
from pathlib import Path
|
||||||
|
from flask import Blueprint, abort, current_app, jsonify, request, send_file
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlalchemy.orm import joinedload
|
||||||
|
from app import db
|
||||||
|
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||||
|
from app.core.errors import (
|
||||||
|
AppError,
|
||||||
|
ConflictError,
|
||||||
|
ForbiddenError,
|
||||||
|
NotFoundError,
|
||||||
|
ServiceUnavailableError,
|
||||||
|
UnauthorizedError,
|
||||||
|
ValidationError,
|
||||||
|
raise_for_status,
|
||||||
|
)
|
||||||
|
from app.services.integration_api import IntegrationApiService
|
||||||
|
integration_bp = Blueprint('integration', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _integration_token_secret() -> str:
|
||||||
|
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||||
|
return configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_integration_token(token: str | None) -> dict | None:
|
||||||
|
normalized_token = str(token or '').strip()
|
||||||
|
if not normalized_token:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
import jwt
|
||||||
|
payload = jwt.decode(
|
||||||
|
normalized_token,
|
||||||
|
_integration_token_secret(),
|
||||||
|
algorithms=['HS256'],
|
||||||
|
)
|
||||||
|
return payload if isinstance(payload, dict) else None
|
||||||
|
except Exception as e:
|
||||||
|
current_app.logger.warning(f"Integration API token validation failed: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _build_download_url(document_id: int, *, kind: str, version_id: int | None = None) -> str:
|
||||||
|
base_url = _integration_base_url()
|
||||||
|
url = f'{base_url}/api/integration/files/{document_id}/download?kind={kind}'
|
||||||
|
if version_id is not None:
|
||||||
|
url += f'&version_id={version_id}'
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
def _version_query():
|
||||||
|
return (
|
||||||
|
db.session.query(KbDocumentVersion)
|
||||||
|
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||||
|
.filter(KbDocument.is_deleted.is_(False))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_requested_version(file_id: int) -> tuple[KbDocumentVersion | None, KbDocument | None]:
|
||||||
|
requested_version_id = request.args.get('version_id', type=int)
|
||||||
|
token_payload = _decode_integration_token(request.args.get('token'))
|
||||||
|
if isinstance(token_payload, dict):
|
||||||
|
token_version_id = token_payload.get('version_id')
|
||||||
|
if token_version_id is not None:
|
||||||
|
try:
|
||||||
|
requested_version_id = int(token_version_id)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
current_app.logger.warning(
|
||||||
|
'Integration API token carried invalid version_id: %r',
|
||||||
|
token_version_id,
|
||||||
|
)
|
||||||
|
dataset_id = str(token_payload.get('dataset_id') or '').strip()
|
||||||
|
remote_document_id = str(token_payload.get('remote_document_id') or '').strip()
|
||||||
|
if dataset_id and remote_document_id:
|
||||||
|
record = (
|
||||||
|
db.session.query(KbDifySyncRecord)
|
||||||
|
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||||
|
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||||
|
.options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document))
|
||||||
|
.filter(
|
||||||
|
KbDocument.is_deleted.is_(False),
|
||||||
|
KbDocument.id == file_id,
|
||||||
|
KbDifySyncRecord.dataset_id == dataset_id,
|
||||||
|
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||||
|
)
|
||||||
|
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if record and record.document_version and record.document_version.document:
|
||||||
|
return record.document_version, record.document_version.document
|
||||||
|
|
||||||
|
if requested_version_id is not None:
|
||||||
|
version = (
|
||||||
|
_version_query()
|
||||||
|
.filter(
|
||||||
|
KbDocumentVersion.id == requested_version_id,
|
||||||
|
KbDocumentVersion.document_id == file_id,
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if version:
|
||||||
|
return version, version.document
|
||||||
|
|
||||||
|
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||||
|
if not document:
|
||||||
|
return None, None
|
||||||
|
return _current_version(document), document
|
||||||
|
|
||||||
|
def _require_integration_key():
|
||||||
|
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||||
|
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||||
|
|
||||||
|
if not configured:
|
||||||
|
|
||||||
|
raise ServiceUnavailableError('INTEGRATION_API_KEY is not configured')
|
||||||
|
|
||||||
|
if configured == incoming:
|
||||||
|
return None
|
||||||
|
|
||||||
|
token = request.args.get('token')
|
||||||
|
if token and _decode_integration_token(token):
|
||||||
|
return None
|
||||||
|
|
||||||
|
raise UnauthorizedError('Unauthorized')
|
||||||
|
|
||||||
|
|
||||||
|
def _integration_base_url() -> str:
|
||||||
|
request_origin = IntegrationApiService._request_origin_url()
|
||||||
|
if request_origin:
|
||||||
|
return request_origin
|
||||||
|
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||||
|
if explicit:
|
||||||
|
return explicit
|
||||||
|
return request.host_url.rstrip('/')
|
||||||
|
|
||||||
|
def _kb_storage_root() -> Path:
|
||||||
|
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||||
|
root.mkdir(parents=True, exist_ok=True)
|
||||||
|
return root
|
||||||
|
|
||||||
|
def _resolve_storage_path(path_value: str | None) -> Path | None:
|
||||||
|
if not path_value:
|
||||||
|
return None
|
||||||
|
raw_path = Path(str(path_value))
|
||||||
|
candidate = (raw_path if raw_path.is_absolute() else (_kb_storage_root() / raw_path)).resolve()
|
||||||
|
root = _kb_storage_root()
|
||||||
|
try:
|
||||||
|
candidate.relative_to(root)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||||
|
versions = list(getattr(document, 'versions', []) or [])
|
||||||
|
if not versions:
|
||||||
|
return None
|
||||||
|
return next((item for item in versions if item.is_current), versions[0])
|
||||||
|
|
||||||
|
def _document_query():
|
||||||
|
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
|
||||||
|
|
||||||
|
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
|
||||||
|
version = version or _current_version(document)
|
||||||
|
if not version:
|
||||||
|
abort(404, description='No current version found.')
|
||||||
|
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
|
||||||
|
source_download_url = _build_download_url(document.id, kind='source', version_id=version.id)
|
||||||
|
markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None
|
||||||
|
return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}}
|
||||||
|
|
||||||
|
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
|
||||||
|
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||||
|
|
||||||
|
def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: int | None=None, file_name: str | None=None) -> list[dict]:
|
||||||
|
normalized_file_name = str(file_name or '').strip().lower()
|
||||||
|
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||||
|
if knowledge_base_id is not None:
|
||||||
|
query = query.filter(KbDocument.group_id == knowledge_base_id)
|
||||||
|
if department_id is not None:
|
||||||
|
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
|
||||||
|
documents = query.all()
|
||||||
|
payload = []
|
||||||
|
for document in documents:
|
||||||
|
version = _current_version(document)
|
||||||
|
if not version:
|
||||||
|
continue
|
||||||
|
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
|
||||||
|
if normalized_file_name and normalized_file_name not in normalized_name and (normalized_file_name not in document.title.lower()):
|
||||||
|
continue
|
||||||
|
payload.append(_serialize_integration_document(document, version=version))
|
||||||
|
return payload
|
||||||
|
|
||||||
|
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||||||
|
if kind == 'source':
|
||||||
|
path = _resolve_storage_path(version.source_file_path)
|
||||||
|
if path is None:
|
||||||
|
raise NotFoundError('File not found on disk.')
|
||||||
|
filename = version.source_file_name or f'document-{version.document_id}'
|
||||||
|
return (path, filename)
|
||||||
|
preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path)
|
||||||
|
if not preferred:
|
||||||
|
abort(409, description='Markdown not ready.')
|
||||||
|
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||||
|
return (preferred, filename)
|
||||||
|
|
||||||
|
@integration_bp.before_request
|
||||||
|
def _verify_integration_access():
|
||||||
|
result = _require_integration_key()
|
||||||
|
if result is not None:
|
||||||
|
return result
|
||||||
|
return None
|
||||||
|
|
||||||
|
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
|
||||||
|
def get_file_detail(file_id: int):
|
||||||
|
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||||
|
if not document:
|
||||||
|
raise NotFoundError('Document not found.')
|
||||||
|
return jsonify(_serialize_integration_document(document))
|
||||||
|
|
||||||
|
@integration_bp.route('/knowledge-bases', methods=['GET'])
|
||||||
|
def list_knowledge_bases():
|
||||||
|
department_id = request.args.get('department_id', type=int)
|
||||||
|
q = str(request.args.get('q') or '').strip()
|
||||||
|
document_counts = db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count')).filter(KbDocument.is_deleted.is_(False)).group_by(KbDocument.group_id).subquery()
|
||||||
|
query = db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count')).outerjoin(document_counts, document_counts.c.group_id == KbGroup.id).filter(KbGroup.is_active.is_(True)).order_by(KbGroup.name.asc())
|
||||||
|
if department_id is not None:
|
||||||
|
query = query.filter(KbGroup.department_id == department_id)
|
||||||
|
if q:
|
||||||
|
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
|
||||||
|
rows = query.all()
|
||||||
|
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
|
||||||
|
|
||||||
|
@integration_bp.route('/files', methods=['GET'])
|
||||||
|
def list_files():
|
||||||
|
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
|
||||||
|
department_id = request.args.get('department_id', type=int)
|
||||||
|
file_name = request.args.get('file_name')
|
||||||
|
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, department_id=department_id, file_name=file_name)})
|
||||||
|
|
||||||
|
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
|
||||||
|
def list_files_for_knowledge_base(knowledge_base_id: int):
|
||||||
|
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, file_name=request.args.get('file_name'))})
|
||||||
|
|
||||||
|
@integration_bp.route('/dify-file', methods=['GET'])
|
||||||
|
def get_file_detail_by_dify():
|
||||||
|
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
|
||||||
|
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
|
||||||
|
if not remote_document_id:
|
||||||
|
raise ValidationError('remote_document_id is required')
|
||||||
|
record_query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id == remote_document_id).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||||
|
if dataset_id:
|
||||||
|
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
|
||||||
|
record = record_query.first()
|
||||||
|
version = record.document_version if record else None
|
||||||
|
document = version.document if version else None
|
||||||
|
if not document:
|
||||||
|
raise NotFoundError('No local file mapping found for the given Dify document.')
|
||||||
|
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
|
||||||
|
|
||||||
|
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
||||||
|
def resolve_files_by_dify():
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
items = data.get('items') if isinstance(data.get('items'), list) else []
|
||||||
|
if not items:
|
||||||
|
return jsonify({'data': []})
|
||||||
|
remote_ids = sorted({str(item.get('remote_document_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()})
|
||||||
|
dataset_ids = sorted({str(item.get('dataset_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()})
|
||||||
|
if not remote_ids:
|
||||||
|
return jsonify({'data': []})
|
||||||
|
query = db.session.query(KbDifySyncRecord).join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id).join(KbDocument, KbDocument.id == KbDocumentVersion.document_id).options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id.in_(remote_ids)).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||||
|
if dataset_ids:
|
||||||
|
query = query.filter(KbDifySyncRecord.dataset_id.in_(dataset_ids) | KbDifySyncRecord.dataset_id.is_(None))
|
||||||
|
records = query.all()
|
||||||
|
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
|
||||||
|
records_by_remote: dict[str, KbDifySyncRecord] = {}
|
||||||
|
for record in records:
|
||||||
|
key = (record.dataset_id, record.remote_document_id)
|
||||||
|
records_by_key.setdefault(key, record)
|
||||||
|
records_by_remote.setdefault(record.remote_document_id, record)
|
||||||
|
payload = []
|
||||||
|
for item in items:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
requested_dataset_id = str(item.get('dataset_id') or '').strip() or None
|
||||||
|
requested_remote_document_id = str(item.get('remote_document_id') or '').strip()
|
||||||
|
if not requested_remote_document_id:
|
||||||
|
continue
|
||||||
|
record = records_by_key.get((requested_dataset_id, requested_remote_document_id))
|
||||||
|
if record is None and requested_dataset_id is None:
|
||||||
|
record = records_by_remote.get(requested_remote_document_id)
|
||||||
|
version = record.document_version if record else None
|
||||||
|
document = version.document if version else None
|
||||||
|
payload.append({'request': {'dataset_id': requested_dataset_id, 'remote_document_id': requested_remote_document_id}, 'found': bool(document), 'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None})
|
||||||
|
return jsonify({'data': payload})
|
||||||
|
|
||||||
|
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
||||||
|
def download_file(file_id: int):
|
||||||
|
kind = str(request.args.get('kind') or 'md').strip().lower()
|
||||||
|
version, document = _resolve_requested_version(file_id)
|
||||||
|
if not document:
|
||||||
|
raise NotFoundError('Document not found.')
|
||||||
|
if not version:
|
||||||
|
raise NotFoundError('No version found.')
|
||||||
|
path, filename = _resolve_download_path(version, kind)
|
||||||
|
if not path.exists():
|
||||||
|
raise NotFoundError('File not found on disk.')
|
||||||
|
return send_file(path, as_attachment=True, download_name=filename)
|
||||||
@@ -0,0 +1,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,204 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/internal_jobs.py
|
||||||
|
|
||||||
|
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
|
||||||
|
依赖:job_registry、schedule_contract、scheduler_service。
|
||||||
|
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import traceback
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from flask import Blueprint, jsonify, request
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||||
|
from app.services.schedule.job_registry import get_platform_job, run_platform_job
|
||||||
|
from app.services.schedule.schedule_contract import normalize_job_key
|
||||||
|
from app.services.schedule.scheduler_service import _generate_run_no
|
||||||
|
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||||
|
apply_deferred_schedule_run_state,
|
||||||
|
recover_stale_awaiting_rpa_schedule_runs,
|
||||||
|
should_defer_schedule_run_finalization,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
|
||||||
|
"""
|
||||||
|
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
|
||||||
|
Raises:
|
||||||
|
ValidationError: 非 platform_job 或 platform_api_path 不匹配
|
||||||
|
"""
|
||||||
|
if task.schedule_type != 'platform_job':
|
||||||
|
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
|
||||||
|
task_key = normalize_job_key(task.platform_api_path)
|
||||||
|
if task_key != job_key:
|
||||||
|
raise ValidationError(
|
||||||
|
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
|
||||||
|
f"does not match job key '{job_key}'"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
|
||||||
|
"""
|
||||||
|
解析或创建 ScheduleTask / ScheduleRun。
|
||||||
|
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
|
||||||
|
run_no 查询限定 schedule_task_id,避免跨任务写入。
|
||||||
|
"""
|
||||||
|
schedule_task_id = data.get('schedule_task_id')
|
||||||
|
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
|
||||||
|
if task:
|
||||||
|
_assert_task_matches_job_key(task, job_key)
|
||||||
|
else:
|
||||||
|
task = (
|
||||||
|
ScheduleTask.query.filter(
|
||||||
|
ScheduleTask.platform_api_path == job_key,
|
||||||
|
ScheduleTask.schedule_type == 'platform_job',
|
||||||
|
)
|
||||||
|
.order_by(ScheduleTask.id.desc())
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
|
||||||
|
|
||||||
|
run_no = str(data.get('run_no') or '').strip()
|
||||||
|
run = None
|
||||||
|
if run_no:
|
||||||
|
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
|
||||||
|
if not run:
|
||||||
|
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||||
|
if foreign and foreign.schedule_task_id != task.id:
|
||||||
|
raise ValidationError(
|
||||||
|
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
|
||||||
|
f"not {task.id}"
|
||||||
|
)
|
||||||
|
if not run:
|
||||||
|
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()
|
||||||
|
return task, run
|
||||||
|
|
||||||
|
|
||||||
|
def _finalize_run(
|
||||||
|
run: ScheduleRun,
|
||||||
|
*,
|
||||||
|
total_count: int,
|
||||||
|
success_count: int,
|
||||||
|
failed_count: int,
|
||||||
|
skipped_count: int,
|
||||||
|
step_logs: list | None,
|
||||||
|
) -> None:
|
||||||
|
"""写入 run 汇总字段并 commit。"""
|
||||||
|
run.status = (
|
||||||
|
'success' if failed_count == 0
|
||||||
|
else 'failed' if success_count == 0
|
||||||
|
else 'partial_failed'
|
||||||
|
)
|
||||||
|
run.total_count = total_count
|
||||||
|
run.success_count = success_count
|
||||||
|
run.failed_count = failed_count
|
||||||
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||||
|
def run_internal_job(name: str):
|
||||||
|
"""
|
||||||
|
执行已注册平台 Job。
|
||||||
|
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
|
||||||
|
"""
|
||||||
|
key = normalize_job_key(name)
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
|
||||||
|
if not get_platform_job(key):
|
||||||
|
raise NotFoundError(f"Unknown platform job: {name}")
|
||||||
|
|
||||||
|
task, run = _resolve_schedule_task_and_run(key, data)
|
||||||
|
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||||
|
try:
|
||||||
|
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
|
||||||
|
key, task, run, data,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
run.status = 'failed'
|
||||||
|
run.error_message = str(exc)
|
||||||
|
run.finished_at = datetime.utcnow()
|
||||||
|
db.session.commit()
|
||||||
|
raise AppError(
|
||||||
|
code='SYSTEM.HTTP_ERROR',
|
||||||
|
message=str(exc),
|
||||||
|
http_status=500,
|
||||||
|
details={
|
||||||
|
'traceback': traceback.format_exc(),
|
||||||
|
'summary': {
|
||||||
|
'total_count': 0,
|
||||||
|
'success_count': 0,
|
||||||
|
'failed_count': 0,
|
||||||
|
'skipped_count': 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if should_defer_schedule_run_finalization(task, step_logs):
|
||||||
|
apply_deferred_schedule_run_state(
|
||||||
|
run,
|
||||||
|
task,
|
||||||
|
total_count=total_count,
|
||||||
|
success_count=success_count,
|
||||||
|
failed_count=failed_count,
|
||||||
|
skipped_count=skipped_count,
|
||||||
|
details=details,
|
||||||
|
errors=errors,
|
||||||
|
step_logs=step_logs,
|
||||||
|
)
|
||||||
|
return jsonify({
|
||||||
|
'summary': {
|
||||||
|
'total_count': total_count,
|
||||||
|
'success_count': success_count,
|
||||||
|
'failed_count': failed_count,
|
||||||
|
'skipped_count': skipped_count,
|
||||||
|
},
|
||||||
|
'details': details,
|
||||||
|
'errors': errors,
|
||||||
|
'step_logs': step_logs,
|
||||||
|
'awaiting_rpa_callback': True,
|
||||||
|
})
|
||||||
|
|
||||||
|
_finalize_run(
|
||||||
|
run,
|
||||||
|
total_count=total_count,
|
||||||
|
success_count=success_count,
|
||||||
|
failed_count=failed_count,
|
||||||
|
skipped_count=skipped_count,
|
||||||
|
step_logs=step_logs,
|
||||||
|
)
|
||||||
|
return jsonify({
|
||||||
|
'summary': {
|
||||||
|
'total_count': total_count,
|
||||||
|
'success_count': success_count,
|
||||||
|
'failed_count': failed_count,
|
||||||
|
'skipped_count': skipped_count,
|
||||||
|
},
|
||||||
|
'details': details,
|
||||||
|
'errors': errors,
|
||||||
|
'step_logs': step_logs,
|
||||||
|
})
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/kb/__init__.py
|
||||||
|
|
||||||
|
用途:知识库管理 Blueprint 入口(Wave 3 分包)。
|
||||||
|
依赖:kb/blueprint.py、common、dify、groups、documents、jobs。
|
||||||
|
逻辑:import 子模块注册路由;register_blueprints 从本包 import knowledge_base_bp。
|
||||||
|
"""
|
||||||
|
from app.api.kb.blueprint import knowledge_base_bp
|
||||||
|
|
||||||
|
import app.api.kb.common # noqa: F401
|
||||||
|
import app.api.kb.dify # noqa: F401
|
||||||
|
import app.api.kb.groups # noqa: F401
|
||||||
|
import app.api.kb.documents # noqa: F401
|
||||||
|
import app.api.kb.jobs # noqa: F401
|
||||||
|
|
||||||
|
__all__ = ['knowledge_base_bp']
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/kb/blueprint.py
|
||||||
|
|
||||||
|
用途:知识库 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||||
|
依赖:Flask Blueprint。
|
||||||
|
逻辑:kb/dify、groups、documents、jobs 等子模块在此 bp 上注册路由;__init__ 导出 knowledge_base_bp。
|
||||||
|
"""
|
||||||
|
from flask import Blueprint
|
||||||
|
|
||||||
|
knowledge_base_bp = Blueprint('knowledge_base', __name__)
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/kb/common.py
|
||||||
|
|
||||||
|
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览)。
|
||||||
|
依赖:app.core.*、models、services/kb/storage、edkb_system。
|
||||||
|
逻辑:dify/groups/documents/jobs 子模块共用;存储读写见 services/kb/storage。
|
||||||
|
"""
|
||||||
|
from flask import current_app
|
||||||
|
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import UnauthorizedError
|
||||||
|
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||||
|
from app.services.kb.markdown import (
|
||||||
|
markdown_unavailable_message,
|
||||||
|
resolve_markdown_read_path,
|
||||||
|
resolve_markdown_write_path,
|
||||||
|
serialize_markdown_payload,
|
||||||
|
)
|
||||||
|
from app.services.kb.storage import (
|
||||||
|
kb_storage_root,
|
||||||
|
resolve_storage_path,
|
||||||
|
safe_upload_filename,
|
||||||
|
save_upload,
|
||||||
|
)
|
||||||
|
|
||||||
|
def require_user():
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError()
|
||||||
|
return user
|
||||||
|
|
||||||
|
def run_db_read(label: str, loader):
|
||||||
|
try:
|
||||||
|
return loader()
|
||||||
|
except (OperationalError, DatabaseError) as exc:
|
||||||
|
current_app.logger.warning('[kb] transient db error during %s, retry with reconnect: %s', label, exc)
|
||||||
|
db.session.rollback()
|
||||||
|
db.session.remove()
|
||||||
|
try:
|
||||||
|
db.engine.dispose()
|
||||||
|
except Exception:
|
||||||
|
current_app.logger.warning('[kb] failed to dispose engine during %s recovery', label, exc_info=True)
|
||||||
|
return loader()
|
||||||
|
|
||||||
|
def serialize_group(group: KbGroup, document_count: int=0):
|
||||||
|
return {'id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||||
|
|
||||||
|
def serialize_document(doc: KbDocument):
|
||||||
|
latest_version = current_version(doc)
|
||||||
|
return {'id': doc.id, 'group_id': doc.group_id, 'title': doc.title, 'description': doc.description, 'status': doc.status, 'source_type': doc.source_type, 'created_at': doc.created_at.isoformat() if doc.created_at else None, 'updated_at': doc.updated_at.isoformat() if doc.updated_at else None, 'version_count': len(doc.versions) if getattr(doc, 'versions', None) else 0, 'latest_version': serialize_version(latest_version) if latest_version else None}
|
||||||
|
|
||||||
|
def serialize_version(version: KbDocumentVersion | None):
|
||||||
|
if version is None:
|
||||||
|
return None
|
||||||
|
return {'id': version.id, 'document_id': version.document_id, 'version_no': version.version_no, 'status': version.status, 'is_current': version.is_current, 'source_file_name': version.source_file_name, 'source_file_ext': version.source_file_ext, 'source_file_size': version.source_file_size, 'sha256': version.sha256, 'cleaned_file_path': version.cleaned_file_path, 'cleaned_preview_path': version.cleaned_preview_path, 'error_message': version.error_message, 'created_at': version.created_at.isoformat() if version.created_at else None}
|
||||||
|
|
||||||
|
def serialize_sync_record(record: KbDifySyncRecord):
|
||||||
|
return {'id': record.id, 'group_id': record.group_id, 'document_id': record.document_id, 'document_version_id': record.document_version_id, 'dataset_id': record.dataset_id, 'dataset_name': record.dataset_name, 'remote_document_id': record.remote_document_id, 'remote_document_name': record.remote_document_name, 'status': record.status, 'sync_hash': record.sync_hash, 'error_message': record.error_message, 'synced_at': record.synced_at.isoformat() if record.synced_at else None, 'updated_at': record.updated_at.isoformat() if record.updated_at else None}
|
||||||
|
|
||||||
|
def current_version(document: KbDocument | None) -> KbDocumentVersion | None:
|
||||||
|
versions = list(getattr(document, 'versions', []) or [])
|
||||||
|
if not versions:
|
||||||
|
return None
|
||||||
|
return next((item for item in versions if item.is_current), versions[0])
|
||||||
|
|
||||||
|
|
||||||
|
def next_version_no(document: KbDocument) -> int:
|
||||||
|
versions = list(getattr(document, 'versions', []) or [])
|
||||||
|
if not versions:
|
||||||
|
return 1
|
||||||
|
return max((item.version_no for item in versions)) + 1
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/kb/dify.py
|
||||||
|
|
||||||
|
用途:知识库 Dify 连接配置与健康检查 API。
|
||||||
|
依赖:kb.blueprint、knowledge_cleaning.settings_service。
|
||||||
|
逻辑:管理员读写 Dify 设置;GET /dify/health 探测远端 dataset。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app.api.kb.blueprint import knowledge_base_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.knowledge_cleaning.settings_service import (
|
||||||
|
get_kb_dify_health_payload,
|
||||||
|
get_kb_dify_settings,
|
||||||
|
save_kb_dify_settings,
|
||||||
|
)
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/dify/settings', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_dify_settings():
|
||||||
|
payload = get_kb_dify_settings()
|
||||||
|
return jsonify(payload)
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/dify/settings', methods=['PATCH'])
|
||||||
|
@require_admin
|
||||||
|
def update_dify_settings():
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
payload = save_kb_dify_settings(data)
|
||||||
|
return jsonify(payload)
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/dify/health', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_dify_health():
|
||||||
|
payload = get_kb_dify_health_payload()
|
||||||
|
if payload['dify_api_configured'] and payload['dify_base_url']:
|
||||||
|
try:
|
||||||
|
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||||
|
datasets = KbDifySyncService().list_datasets()
|
||||||
|
payload['api']['reachable'] = True
|
||||||
|
payload['api']['dataset_count'] = len(datasets)
|
||||||
|
except Exception as exc:
|
||||||
|
payload['api']['error'] = str(exc)
|
||||||
|
else:
|
||||||
|
payload['api']['error'] = 'Dify 连接尚未配置'
|
||||||
|
return jsonify(payload)
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/kb/documents.py
|
||||||
|
|
||||||
|
用途:知识库文档版本、Markdown、上传/清洗/同步 API(薄路由层)。
|
||||||
|
依赖:kb.blueprint、kb.common、services/kb/document_service。
|
||||||
|
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service。
|
||||||
|
"""
|
||||||
|
from flask import jsonify, request, send_file
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.api.kb.blueprint import knowledge_base_bp
|
||||||
|
from app.api.kb.common import require_user, serialize_document, serialize_sync_record, serialize_version
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.services.kb import document_service
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/documents/<int:document_id>/versions', methods=['GET'])
|
||||||
|
def list_document_versions(document_id: int):
|
||||||
|
require_user()
|
||||||
|
versions = document_service.list_document_versions(document_id)
|
||||||
|
return jsonify([serialize_version(item) for item in versions])
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/document-versions/<int:version_id>/source-file', methods=['GET'])
|
||||||
|
def get_document_version_source_file(version_id: int):
|
||||||
|
require_user()
|
||||||
|
source_path, filename = document_service.resolve_source_file_path(version_id)
|
||||||
|
as_attachment = str(request.args.get('download') or '').strip() == '1'
|
||||||
|
return send_file(source_path, as_attachment=as_attachment, download_name=filename)
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/documents/<int:document_id>/sync-records', methods=['GET'])
|
||||||
|
def list_document_sync_records(document_id: int):
|
||||||
|
require_user()
|
||||||
|
records = document_service.list_sync_records(document_id)
|
||||||
|
return jsonify([serialize_sync_record(item) for item in records])
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['GET'])
|
||||||
|
def get_document_markdown(document_id: int):
|
||||||
|
require_user()
|
||||||
|
return jsonify(document_service.read_markdown(document_id))
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/documents/<int:document_id>/markdown', methods=['PATCH'])
|
||||||
|
def update_document_markdown(document_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
payload = document_service.update_markdown(
|
||||||
|
document_id,
|
||||||
|
data.get('content'),
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(payload)
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/documents/<int:document_id>/upload', methods=['POST'])
|
||||||
|
def upload_document_version(document_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
uploaded = request.files.get('file')
|
||||||
|
payload = document_service.upload_new_version(
|
||||||
|
document_id,
|
||||||
|
uploaded,
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
return jsonify(payload), 201
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/documents/<int:document_id>/clean', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def submit_document_clean(document_id: int):
|
||||||
|
current_user = get_current_user()
|
||||||
|
payload, status_code = document_service.submit_clean(
|
||||||
|
document_id,
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
return jsonify(payload), status_code
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/documents/<int:document_id>/sync', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def sync_document(document_id: int):
|
||||||
|
current_user = get_current_user()
|
||||||
|
payload = document_service.submit_sync(
|
||||||
|
document_id,
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
return jsonify(payload), 202
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['PATCH'])
|
||||||
|
def update_document(document_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
document = document_service.update_metadata(
|
||||||
|
document_id,
|
||||||
|
data,
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(serialize_document(document))
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['DELETE'])
|
||||||
|
def delete_document(document_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
result = document_service.delete_document(
|
||||||
|
document_id,
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
return jsonify(result)
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/kb/groups.py
|
||||||
|
|
||||||
|
用途:知识库分组 CRUD、组内文档列表与路径批量上传 API(薄路由)。
|
||||||
|
依赖:kb.blueprint、kb.common、services/kb/path_upload_service、services/kb/job_lifecycle。
|
||||||
|
逻辑:/groups* 与 /path-upload-jobs*;业务编排委托 path_upload_service。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import jsonify, request
|
||||||
|
from sqlalchemy import func
|
||||||
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.api.kb.blueprint import knowledge_base_bp
|
||||||
|
from app.api.kb.common import require_user, run_db_read, serialize_document, serialize_group
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.core.errors import NotFoundError, ValidationError
|
||||||
|
from app.models import KbDocument, KbGroup, KbJob
|
||||||
|
from app.services.kb import path_upload_service
|
||||||
|
from app.services.kb.job_lifecycle import cancel_active_kb_jobs_for_group, serialize_job
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/groups', methods=['GET'])
|
||||||
|
def list_groups():
|
||||||
|
require_user()
|
||||||
|
document_counts = (
|
||||||
|
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
|
||||||
|
.filter(KbDocument.is_deleted.is_(False))
|
||||||
|
.group_by(KbDocument.group_id)
|
||||||
|
.subquery()
|
||||||
|
)
|
||||||
|
rows = run_db_read(
|
||||||
|
'list_groups',
|
||||||
|
lambda: db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
|
||||||
|
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
|
||||||
|
.filter(KbGroup.is_active.is_(True))
|
||||||
|
.order_by(KbGroup.updated_at.desc(), KbGroup.id.desc())
|
||||||
|
.all(),
|
||||||
|
)
|
||||||
|
return jsonify([serialize_group(group, document_count) for group, document_count in rows])
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/groups', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def create_group():
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
name = str(data.get('name') or '').strip()
|
||||||
|
description = str(data.get('description') or '').strip() or None
|
||||||
|
department_id = data.get('department_id')
|
||||||
|
if not name:
|
||||||
|
raise ValidationError('name is required')
|
||||||
|
existing_query = db.session.query(KbGroup).filter(KbGroup.name == name, KbGroup.is_active.is_(True))
|
||||||
|
if department_id is None:
|
||||||
|
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||||
|
else:
|
||||||
|
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||||
|
if existing_query.first():
|
||||||
|
raise ValidationError('知识库分组已存在')
|
||||||
|
current_user = get_current_user()
|
||||||
|
group = KbGroup(
|
||||||
|
name=name,
|
||||||
|
description=description,
|
||||||
|
department_id=department_id,
|
||||||
|
created_by_id=getattr(current_user, 'id', None),
|
||||||
|
updated_by_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
db.session.add(group)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(serialize_group(group, 0)), 201
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['PATCH'])
|
||||||
|
@require_admin
|
||||||
|
def update_group(group_id: int):
|
||||||
|
group = db.session.get(KbGroup, group_id)
|
||||||
|
if not group or not group.is_active:
|
||||||
|
raise NotFoundError('知识库分组不存在')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
name = str(data.get('name') or group.name).strip()
|
||||||
|
description = data.get('description')
|
||||||
|
department_id = data.get('department_id', group.department_id)
|
||||||
|
if not name:
|
||||||
|
raise ValidationError('name is required')
|
||||||
|
existing_query = db.session.query(KbGroup).filter(
|
||||||
|
KbGroup.id != group.id,
|
||||||
|
KbGroup.name == name,
|
||||||
|
KbGroup.is_active.is_(True),
|
||||||
|
)
|
||||||
|
if department_id is None:
|
||||||
|
existing_query = existing_query.filter(KbGroup.department_id.is_(None))
|
||||||
|
else:
|
||||||
|
existing_query = existing_query.filter(KbGroup.department_id == department_id)
|
||||||
|
if existing_query.first():
|
||||||
|
raise ValidationError('知识库分组已存在')
|
||||||
|
current_user = get_current_user()
|
||||||
|
group.name = name
|
||||||
|
group.description = str(description).strip() or None if description is not None else None
|
||||||
|
group.department_id = department_id
|
||||||
|
group.updated_by_id = getattr(current_user, 'id', None)
|
||||||
|
db.session.commit()
|
||||||
|
document_count = db.session.query(func.count(KbDocument.id)).filter(
|
||||||
|
KbDocument.group_id == group.id,
|
||||||
|
KbDocument.is_deleted.is_(False),
|
||||||
|
).scalar()
|
||||||
|
return jsonify(serialize_group(group, document_count))
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/groups/<int:group_id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_group(group_id: int):
|
||||||
|
group = db.session.get(KbGroup, group_id)
|
||||||
|
if not group or not group.is_active:
|
||||||
|
raise NotFoundError('知识库分组不存在')
|
||||||
|
current_user = get_current_user()
|
||||||
|
group.is_active = False
|
||||||
|
group.updated_by_id = getattr(current_user, 'id', None)
|
||||||
|
cancel_active_kb_jobs_for_group(group.id, '知识库分组已删除,后台任务已取消')
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'ok': True, 'id': group_id})
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['GET'])
|
||||||
|
def list_group_files(group_id: int):
|
||||||
|
require_user()
|
||||||
|
group = run_db_read('get_group_for_files', lambda: db.session.get(KbGroup, group_id))
|
||||||
|
if not group or not group.is_active:
|
||||||
|
raise NotFoundError('Knowledge base group not found')
|
||||||
|
documents = run_db_read(
|
||||||
|
'list_group_files',
|
||||||
|
lambda: db.session.query(KbDocument)
|
||||||
|
.options(joinedload(KbDocument.versions))
|
||||||
|
.filter(KbDocument.group_id == group_id, KbDocument.is_deleted.is_(False))
|
||||||
|
.order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||||
|
.all(),
|
||||||
|
)
|
||||||
|
return jsonify([serialize_document(doc) for doc in documents])
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/groups/<int:group_id>/files', methods=['POST'])
|
||||||
|
def create_group_file(group_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
path_upload_service.require_active_group(group_id)
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
title = str(data.get('title') or '').strip()
|
||||||
|
description = str(data.get('description') or '').strip() or None
|
||||||
|
status = str(data.get('status') or 'draft').strip() or 'draft'
|
||||||
|
if not title:
|
||||||
|
raise ValidationError('title is required')
|
||||||
|
existing = (
|
||||||
|
db.session.query(KbDocument)
|
||||||
|
.options(joinedload(KbDocument.versions))
|
||||||
|
.filter(KbDocument.group_id == group_id, KbDocument.title == title)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if existing and not existing.is_deleted:
|
||||||
|
raise ValidationError('当前分组下已存在同名文档')
|
||||||
|
if existing and existing.is_deleted:
|
||||||
|
existing.is_deleted = False
|
||||||
|
existing.description = description
|
||||||
|
existing.status = status
|
||||||
|
existing.updated_by_id = getattr(current_user, 'id', None)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(serialize_document(existing)), 201
|
||||||
|
document = KbDocument(
|
||||||
|
group_id=group_id,
|
||||||
|
title=title,
|
||||||
|
description=description,
|
||||||
|
status=status,
|
||||||
|
source_type='manual',
|
||||||
|
created_by_id=getattr(current_user, 'id', None),
|
||||||
|
updated_by_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
db.session.add(document)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(serialize_document(document)), 201
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/groups/<int:group_id>/path-upload-jobs', methods=['POST'])
|
||||||
|
def create_path_upload_job(group_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
path_upload_service.require_active_group(group_id)
|
||||||
|
job, reused = path_upload_service.create_path_upload_job(
|
||||||
|
group_id,
|
||||||
|
request.get_json(silent=True) or {},
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
payload = serialize_job(job)
|
||||||
|
if reused:
|
||||||
|
payload['reused_existing'] = True
|
||||||
|
payload['message'] = payload.get('message') or '检测到未完成的路径上传任务,已自动续传'
|
||||||
|
return jsonify(payload)
|
||||||
|
return jsonify(payload), 201
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['POST'])
|
||||||
|
def upload_path_job_file(job_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
job = path_upload_service.require_path_upload_job(job_id)
|
||||||
|
try:
|
||||||
|
job = path_upload_service.upload_path_job_file(
|
||||||
|
job,
|
||||||
|
file_storage=request.files.get('file'),
|
||||||
|
relative_path_raw=request.form.get('relative_path'),
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValidationError(str(exc)) from exc
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(serialize_job(job)), 201
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files/fail', methods=['POST'])
|
||||||
|
def mark_path_job_file_failed(job_id: int):
|
||||||
|
require_user()
|
||||||
|
job = path_upload_service.require_path_upload_job(job_id)
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
original_name = str(data.get('original_name') or '').strip() or None
|
||||||
|
relative_path_raw = str(data.get('relative_path') or '').strip()
|
||||||
|
error_message = str(data.get('error') or '路径文件上传失败').strip() or '路径文件上传失败'
|
||||||
|
try:
|
||||||
|
job = path_upload_service.mark_path_job_file_failed(
|
||||||
|
job,
|
||||||
|
relative_path_raw=relative_path_raw,
|
||||||
|
original_name=original_name,
|
||||||
|
error_message=error_message,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValidationError(str(exc)) from exc
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify(serialize_job(job))
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/finalize', methods=['POST'])
|
||||||
|
def finalize_path_upload_job(job_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
job = path_upload_service.require_path_upload_job(job_id)
|
||||||
|
job, status_code = path_upload_service.finalize_path_upload_job(
|
||||||
|
job,
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
refreshed = db.session.get(KbJob, job.id)
|
||||||
|
response_payload = serialize_job(refreshed or job)
|
||||||
|
if status_code == 202:
|
||||||
|
response_payload['queue_result'] = 'inline_per_file'
|
||||||
|
response_payload['accepted'] = True
|
||||||
|
return jsonify(response_payload), status_code
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['DELETE'])
|
||||||
|
def delete_path_job_file(job_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
job = path_upload_service.require_path_upload_job(job_id)
|
||||||
|
relative_path_raw = str(request.args.get('relative_path') or '').strip()
|
||||||
|
if not relative_path_raw:
|
||||||
|
raise ValidationError('relative_path is required')
|
||||||
|
try:
|
||||||
|
job, document_deleted, relative_path = path_upload_service.delete_path_job_file(
|
||||||
|
job,
|
||||||
|
relative_path_raw=relative_path_raw,
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValidationError(str(exc)) from exc
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({
|
||||||
|
'ok': True,
|
||||||
|
'job': serialize_job(job),
|
||||||
|
'document_deleted': document_deleted,
|
||||||
|
'relative_path': relative_path,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/retry-failed', methods=['POST'])
|
||||||
|
def retry_failed_path_upload_job(job_id: int):
|
||||||
|
current_user = require_user()
|
||||||
|
source_job = path_upload_service.require_path_upload_job(job_id)
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
requested_paths = data.get('relative_paths') or []
|
||||||
|
if not isinstance(requested_paths, list):
|
||||||
|
requested_paths = []
|
||||||
|
retry_job = path_upload_service.retry_failed_path_upload_job(
|
||||||
|
source_job,
|
||||||
|
relative_paths=requested_paths,
|
||||||
|
user_id=getattr(current_user, 'id', None),
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
refreshed = db.session.get(KbJob, retry_job.id)
|
||||||
|
return jsonify(serialize_job(refreshed or retry_job)), 201
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/kb/jobs.py
|
||||||
|
|
||||||
|
用途:知识库后台任务 API(列表、手动触发);序列化/取消 helper 来自 services/kb/job_lifecycle。
|
||||||
|
依赖:kb.blueprint、kb.common、app.jobs、services/kb/job_lifecycle。
|
||||||
|
逻辑:注册 /jobs 路由。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import jsonify
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.api.kb.blueprint import knowledge_base_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.core.errors import NotFoundError, ValidationError
|
||||||
|
from app.jobs import enqueue_kb_job
|
||||||
|
from app.models import KbDocumentVersion, KbJob
|
||||||
|
from app.services.kb.job_lifecycle import serialize_job
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/jobs', methods=['GET'])
|
||||||
|
def list_jobs():
|
||||||
|
"""
|
||||||
|
返回最近 50 条 KbJob(登录用户可见)。
|
||||||
|
核心逻辑:只读查询,经 run_db_read 处理瞬态 DB 错误。
|
||||||
|
"""
|
||||||
|
from app.api.kb.common import require_user, run_db_read
|
||||||
|
|
||||||
|
require_user()
|
||||||
|
jobs = run_db_read(
|
||||||
|
'list_jobs',
|
||||||
|
lambda: db.session.query(KbJob)
|
||||||
|
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
|
||||||
|
.limit(50)
|
||||||
|
.all(),
|
||||||
|
)
|
||||||
|
return jsonify([serialize_job(job) for job in jobs])
|
||||||
|
|
||||||
|
|
||||||
|
@knowledge_base_bp.route('/jobs/<int:job_id>/run', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def run_job(job_id: int):
|
||||||
|
"""
|
||||||
|
管理员手动将 clean/sync_dify 任务重新提交后台执行。
|
||||||
|
核心逻辑:重置 queued 状态后 enqueue_kb_job;已在队列中则 202 返回 already_queued。
|
||||||
|
"""
|
||||||
|
job = db.session.get(KbJob, job_id)
|
||||||
|
if not job:
|
||||||
|
raise NotFoundError('任务不存在')
|
||||||
|
|
||||||
|
if job.job_type not in ('clean', 'sync_dify'):
|
||||||
|
raise ValidationError('当前仅支持手动执行 clean 或 sync_dify 任务')
|
||||||
|
|
||||||
|
if job.status in ('queued', 'running'):
|
||||||
|
refreshed = db.session.get(KbJob, job_id)
|
||||||
|
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||||
|
payload['accepted'] = True
|
||||||
|
payload['queue_result'] = 'already_queued'
|
||||||
|
payload['run_result'] = '任务已在后台处理中'
|
||||||
|
return jsonify(payload), 202
|
||||||
|
|
||||||
|
version = db.session.get(KbDocumentVersion, job.document_version_id) if job.document_version_id else None
|
||||||
|
|
||||||
|
if job.job_type == 'clean':
|
||||||
|
if not version:
|
||||||
|
raise NotFoundError('关联文档版本不存在')
|
||||||
|
job.status = 'queued'
|
||||||
|
job.progress = 0
|
||||||
|
job.started_at = None
|
||||||
|
job.finished_at = None
|
||||||
|
job.error_message = None
|
||||||
|
job.message = '等待清洗任务执行'
|
||||||
|
version.status = 'uploaded'
|
||||||
|
version.error_message = None
|
||||||
|
if version.document:
|
||||||
|
version.document.status = 'uploaded'
|
||||||
|
else:
|
||||||
|
if not version:
|
||||||
|
raise NotFoundError('关联文档版本不存在')
|
||||||
|
job.status = 'queued'
|
||||||
|
job.progress = 0
|
||||||
|
job.started_at = None
|
||||||
|
job.finished_at = None
|
||||||
|
job.error_message = None
|
||||||
|
job.message = '等待同步到 Dify'
|
||||||
|
if version.status in ('failed', 'ready', 'synced'):
|
||||||
|
version.error_message = None
|
||||||
|
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
_enqueued, queue_result = enqueue_kb_job(job.id)
|
||||||
|
refreshed = db.session.get(KbJob, job_id)
|
||||||
|
payload = serialize_job(refreshed) if refreshed else {'id': job_id}
|
||||||
|
payload['accepted'] = True
|
||||||
|
payload['queue_result'] = queue_result
|
||||||
|
payload['run_result'] = '任务已提交后台异步执行'
|
||||||
|
return jsonify(payload), 202
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/knowledge_base.py
|
||||||
|
|
||||||
|
用途:知识库 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||||
|
依赖:app.api.kb。
|
||||||
|
逻辑:旧 import 路径仍可用;新代码请用 app.api.kb。
|
||||||
|
"""
|
||||||
|
from app.api.kb import knowledge_base_bp
|
||||||
|
|
||||||
|
__all__ = ['knowledge_base_bp']
|
||||||
@@ -0,0 +1,231 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/maintenance.py
|
||||||
|
|
||||||
|
用途:设备维保助手 HTTP API,当前提供设备台账配置与 Excel 导入能力。
|
||||||
|
依赖:JWT 当前用户、maintenance_ledger_service、Flask Blueprint/send_file。
|
||||||
|
逻辑:查询接口面向会话与面板复用;写入/导入接口先做角色校验,再委托 service。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from io import BytesIO
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from flask import Blueprint, g, jsonify, request, send_file
|
||||||
|
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||||
|
from app.services.maintenance_ledger_service import (
|
||||||
|
build_import_template,
|
||||||
|
create_device,
|
||||||
|
get_device,
|
||||||
|
import_devices_from_excel,
|
||||||
|
list_devices,
|
||||||
|
update_device,
|
||||||
|
_parse_date,
|
||||||
|
)
|
||||||
|
from app.services.maintenance_record_service import (
|
||||||
|
build_records_import_template,
|
||||||
|
build_records_export,
|
||||||
|
create_record,
|
||||||
|
delete_record,
|
||||||
|
get_record,
|
||||||
|
import_records_from_excel,
|
||||||
|
list_records,
|
||||||
|
update_record,
|
||||||
|
)
|
||||||
|
|
||||||
|
maintenance_bp = Blueprint('maintenance', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_user():
|
||||||
|
"""确保当前请求存在登录用户。"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _require_ledger_admin():
|
||||||
|
"""
|
||||||
|
校验设备维保管理权限。
|
||||||
|
Returns:
|
||||||
|
当前用户对象。
|
||||||
|
Raises:
|
||||||
|
ForbiddenError: 当前角色不允许写入台账或维修记录。
|
||||||
|
"""
|
||||||
|
user = _require_user()
|
||||||
|
if getattr(user, 'role', None) not in {'admin', 'maintenance_manager'}:
|
||||||
|
raise ForbiddenError('Maintenance manager privilege required')
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _record_list_filters_from_request() -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
从请求参数解析维修记录列表/导出共用的筛选条件。
|
||||||
|
核心逻辑:兼容 snake_case 与 camelCase 报修日期参数;日期非法时抛出 ValidationError。
|
||||||
|
"""
|
||||||
|
report_date_from = _parse_date(
|
||||||
|
request.args.get('report_date_from') or request.args.get('reportDateFrom'),
|
||||||
|
'reportDateFrom',
|
||||||
|
)
|
||||||
|
report_date_to = _parse_date(
|
||||||
|
request.args.get('report_date_to') or request.args.get('reportDateTo'),
|
||||||
|
'reportDateTo',
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
'keyword': request.args.get('keyword'),
|
||||||
|
'device_code': request.args.get('device_code') or request.args.get('deviceCode'),
|
||||||
|
'status': request.args.get('status'),
|
||||||
|
'report_date_from': report_date_from,
|
||||||
|
'report_date_to': report_date_to,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/ledger/devices', methods=['GET'])
|
||||||
|
def list_ledger_devices():
|
||||||
|
"""查询设备台账列表,供 Agent 查询结果与右侧台账配置面板使用。"""
|
||||||
|
_require_user()
|
||||||
|
result = list_devices(
|
||||||
|
keyword=request.args.get('keyword'),
|
||||||
|
status=request.args.get('status'),
|
||||||
|
page=request.args.get('page', type=int) or 1,
|
||||||
|
page_size=request.args.get('page_size', type=int) or 20,
|
||||||
|
)
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['GET'])
|
||||||
|
def get_ledger_device(device_id: int):
|
||||||
|
"""读取设备台账详情。"""
|
||||||
|
_require_user()
|
||||||
|
return jsonify(get_device(device_id))
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/ledger/devices', methods=['POST'])
|
||||||
|
def create_ledger_device():
|
||||||
|
"""新增设备台账,仅固定管理角色可用。"""
|
||||||
|
user = _require_ledger_admin()
|
||||||
|
payload = request.get_json() or {}
|
||||||
|
return jsonify(create_device(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/ledger/devices/<int:device_id>', methods=['PUT'])
|
||||||
|
def update_ledger_device(device_id: int):
|
||||||
|
"""更新设备台账,仅固定管理角色可用。"""
|
||||||
|
user = _require_ledger_admin()
|
||||||
|
payload = request.get_json() or {}
|
||||||
|
return jsonify(update_device(device_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/ledger/import-template', methods=['GET'])
|
||||||
|
def download_ledger_import_template():
|
||||||
|
"""下载设备台账 Excel 导入模板。"""
|
||||||
|
_require_ledger_admin()
|
||||||
|
return send_file(
|
||||||
|
BytesIO(build_import_template()),
|
||||||
|
as_attachment=True,
|
||||||
|
download_name='maintenance_devices_import_template.xlsx',
|
||||||
|
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/ledger/import', methods=['POST'])
|
||||||
|
def import_ledger_devices():
|
||||||
|
"""上传 Excel 模板并批量新增/更新设备台账。"""
|
||||||
|
user = _require_ledger_admin()
|
||||||
|
upload = request.files.get('file')
|
||||||
|
if not upload:
|
||||||
|
raise ValidationError('file is required')
|
||||||
|
result = import_devices_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/records', methods=['GET'])
|
||||||
|
def list_maintenance_records():
|
||||||
|
"""查询设备维修记录,供 Agent 会话查询和结果卡片使用。"""
|
||||||
|
_require_user()
|
||||||
|
filters = _record_list_filters_from_request()
|
||||||
|
result = list_records(
|
||||||
|
keyword=filters['keyword'],
|
||||||
|
device_code=filters['device_code'],
|
||||||
|
status=filters['status'],
|
||||||
|
report_date_from=filters['report_date_from'],
|
||||||
|
report_date_to=filters['report_date_to'],
|
||||||
|
page=request.args.get('page', type=int) or 1,
|
||||||
|
page_size=request.args.get('page_size', type=int) or 20,
|
||||||
|
)
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/records/<int:record_id>', methods=['GET'])
|
||||||
|
def get_maintenance_record(record_id: int):
|
||||||
|
"""读取设备维修记录详情。"""
|
||||||
|
_require_user()
|
||||||
|
return jsonify(get_record(record_id))
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/records/export', methods=['GET'])
|
||||||
|
def export_maintenance_records():
|
||||||
|
"""按当前筛选条件导出设备维修记录 Excel。"""
|
||||||
|
_require_ledger_admin()
|
||||||
|
filters = _record_list_filters_from_request()
|
||||||
|
data = build_records_export(
|
||||||
|
keyword=filters['keyword'],
|
||||||
|
device_code=filters['device_code'],
|
||||||
|
status=filters['status'],
|
||||||
|
report_date_from=filters['report_date_from'],
|
||||||
|
report_date_to=filters['report_date_to'],
|
||||||
|
)
|
||||||
|
return send_file(
|
||||||
|
BytesIO(data),
|
||||||
|
as_attachment=True,
|
||||||
|
download_name='maintenance_records.xlsx',
|
||||||
|
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/records/import-template', methods=['GET'])
|
||||||
|
def download_records_import_template():
|
||||||
|
"""下载维修记录 Excel 导入模板。"""
|
||||||
|
_require_ledger_admin()
|
||||||
|
return send_file(
|
||||||
|
BytesIO(build_records_import_template()),
|
||||||
|
as_attachment=True,
|
||||||
|
download_name='maintenance_record_history_template.xls',
|
||||||
|
mimetype='application/vnd.ms-excel',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/records/import', methods=['POST'])
|
||||||
|
def import_maintenance_records():
|
||||||
|
"""上传 Excel 模板并批量新增维修记录。"""
|
||||||
|
user = _require_ledger_admin()
|
||||||
|
upload = request.files.get('file')
|
||||||
|
if not upload:
|
||||||
|
raise ValidationError('file is required')
|
||||||
|
result = import_records_from_excel(upload, operator=user, request_id=getattr(g, 'request_id', None))
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/records', methods=['POST'])
|
||||||
|
def create_maintenance_record():
|
||||||
|
"""新增设备维修记录,仅固定管理角色可用。"""
|
||||||
|
user = _require_ledger_admin()
|
||||||
|
payload = request.get_json() or {}
|
||||||
|
return jsonify(create_record(payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/records/<int:record_id>', methods=['PUT'])
|
||||||
|
def update_maintenance_record(record_id: int):
|
||||||
|
"""更新设备维修记录,仅固定管理角色可用。"""
|
||||||
|
user = _require_ledger_admin()
|
||||||
|
payload = request.get_json() or {}
|
||||||
|
return jsonify(update_record(record_id, payload, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_bp.route('/records/<int:record_id>', methods=['DELETE'])
|
||||||
|
def delete_maintenance_record(record_id: int):
|
||||||
|
"""删除设备维修记录,仅固定管理角色可用。"""
|
||||||
|
user = _require_ledger_admin()
|
||||||
|
return jsonify(delete_record(record_id, operator=user, request_id=getattr(g, 'request_id', None)))
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/maintenance_tools.py
|
||||||
|
|
||||||
|
用途:设备维保助手 Dify Tool API,只开放只读查询工具。
|
||||||
|
依赖:maintenance_chat_service、maintenance_record_service、OpenAPI 构建、Tool API 基地址解析。
|
||||||
|
逻辑:Dify 复杂问法调用本蓝图查询设备台账/维修记录;明确查询仍由 chat.py 本地直答,写操作仍走 HXOPS 管理面板。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import Blueprint, current_app, jsonify, request
|
||||||
|
from sqlalchemy import or_
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||||
|
from app.models import MaintenanceRecord
|
||||||
|
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
||||||
|
from app.services.maintenance_chat_service import build_device_query_result
|
||||||
|
from app.services.maintenance_record_service import serialize_record
|
||||||
|
from app.services.maintenance_tools.openapi_spec import build_maintenance_openapi_spec
|
||||||
|
|
||||||
|
maintenance_tool_bp = Blueprint("maintenance_tools", __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_tool_auth() -> None:
|
||||||
|
"""
|
||||||
|
校验设备维保 Tool API 鉴权。
|
||||||
|
AI 触发时机:Dify Tool 调用本蓝图时由 before_request 自动执行,不是给 LLM 直接调用的业务工具。
|
||||||
|
"""
|
||||||
|
configured = str(
|
||||||
|
current_app.config.get("MAINTENANCE_TOOL_API_KEY")
|
||||||
|
or current_app.config.get("INTEGRATION_API_KEY")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
if not configured:
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
"MAINTENANCE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured",
|
||||||
|
code="missing_auth",
|
||||||
|
)
|
||||||
|
|
||||||
|
bearer = str(request.headers.get("Authorization") or "").strip()
|
||||||
|
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
||||||
|
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
||||||
|
if configured in {token, integration_key}:
|
||||||
|
return
|
||||||
|
if not token and not integration_key:
|
||||||
|
raise UnauthorizedError("missing_auth")
|
||||||
|
raise UnauthorizedError("invalid_auth")
|
||||||
|
|
||||||
|
|
||||||
|
def _tool_error_code(exc: AppError) -> str:
|
||||||
|
"""把 AppError 归一成 Dify Tool 侧可读错误码。"""
|
||||||
|
message = str(exc.message or "").strip()
|
||||||
|
if message in {"missing_auth", "invalid_auth"}:
|
||||||
|
return message
|
||||||
|
if exc.code == "AUTH.UNAUTHORIZED":
|
||||||
|
return "invalid_auth"
|
||||||
|
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
||||||
|
return "missing_auth"
|
||||||
|
if exc.code == "VALIDATION.INVALID_PARAM":
|
||||||
|
return message or "invalid_request"
|
||||||
|
return exc.code
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_tool_bp.errorhandler(AppError)
|
||||||
|
def _handle_tool_app_error(exc: AppError):
|
||||||
|
"""Tool API 统一错误响应。"""
|
||||||
|
return jsonify({"ok": False, "error_code": _tool_error_code(exc), "message": exc.message}), exc.http_status
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_tool_bp.before_request
|
||||||
|
def _verify_tool_access():
|
||||||
|
"""除 OpenAPI 文档外,所有 Tool 调用必须携带有效服务级 token。"""
|
||||||
|
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
|
||||||
|
return None
|
||||||
|
_require_tool_auth()
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _payload() -> dict:
|
||||||
|
"""读取 JSON 请求体。"""
|
||||||
|
return request.get_json(silent=True) or {}
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_text(value) -> str:
|
||||||
|
return str(value or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_tool_bp.route("/tools/openapi.json", methods=["GET"])
|
||||||
|
def openapi_spec():
|
||||||
|
"""返回 Dify 导入用的 OpenAPI JSON。"""
|
||||||
|
return jsonify(build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_tool_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
|
||||||
|
def openapi_dify_yaml():
|
||||||
|
"""返回 Dify 导入用的 OpenAPI YAML。"""
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
body = yaml.safe_dump(
|
||||||
|
build_maintenance_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()),
|
||||||
|
allow_unicode=True,
|
||||||
|
sort_keys=False,
|
||||||
|
)
|
||||||
|
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_tool_bp.route("/tools/query_device", methods=["POST"])
|
||||||
|
def query_device():
|
||||||
|
"""按设备编号或名称查询设备台账,并可带出最近维修记录。"""
|
||||||
|
data = _payload()
|
||||||
|
keyword = _clean_text(data.get("keyword"))
|
||||||
|
if not keyword:
|
||||||
|
raise ValidationError("keyword is required")
|
||||||
|
include_records = bool(data.get("include_records", True))
|
||||||
|
record_limit = max(0, min(20, int(data.get("record_limit") or 5)))
|
||||||
|
result = build_device_query_result(keyword, include_records=include_records, record_limit=record_limit)
|
||||||
|
return jsonify({"ok": True, **result})
|
||||||
|
|
||||||
|
|
||||||
|
@maintenance_tool_bp.route("/tools/query_records", methods=["POST"])
|
||||||
|
def query_records():
|
||||||
|
"""按设备编号/名称和状态查询维修记录。"""
|
||||||
|
data = _payload()
|
||||||
|
keyword = _clean_text(data.get("keyword"))
|
||||||
|
if not keyword:
|
||||||
|
raise ValidationError("keyword is required")
|
||||||
|
status = _clean_text(data.get("status"))
|
||||||
|
limit = max(1, min(50, int(data.get("limit") or 10)))
|
||||||
|
|
||||||
|
query = db.session.query(MaintenanceRecord)
|
||||||
|
like = f"%{keyword}%"
|
||||||
|
query = query.filter(
|
||||||
|
or_(
|
||||||
|
MaintenanceRecord.device_code.ilike(like),
|
||||||
|
MaintenanceRecord.device_name.ilike(like),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if status:
|
||||||
|
query = query.filter(MaintenanceRecord.repair_status == status)
|
||||||
|
rows = query.order_by(MaintenanceRecord.report_date.desc(), MaintenanceRecord.id.desc()).limit(limit).all()
|
||||||
|
return jsonify({
|
||||||
|
"ok": True,
|
||||||
|
"matched": bool(rows),
|
||||||
|
"keyword": keyword,
|
||||||
|
"items": [serialize_record(item) for item in rows],
|
||||||
|
"totalReturned": len(rows),
|
||||||
|
})
|
||||||
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/schedule/__init__.py
|
||||||
|
|
||||||
|
用途:排程管理 Blueprint 入口(Wave 3 分包)。
|
||||||
|
依赖:schedule/blueprint.py、config、tasks、runs、platform_tasks。
|
||||||
|
逻辑:import 子模块注册路由;register_blueprints 从本包 import schedule_admin_bp。
|
||||||
|
"""
|
||||||
|
from app.api.schedule.blueprint import schedule_admin_bp
|
||||||
|
|
||||||
|
import app.api.schedule.common # noqa: F401
|
||||||
|
import app.api.schedule.config # noqa: F401
|
||||||
|
import app.api.schedule.tasks # noqa: F401
|
||||||
|
import app.api.schedule.runs # noqa: F401
|
||||||
|
import app.api.schedule.platform_tasks # noqa: F401
|
||||||
|
import app.api.schedule.rpa_workers # noqa: F401
|
||||||
|
|
||||||
|
__all__ = ['schedule_admin_bp']
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/schedule/blueprint.py
|
||||||
|
|
||||||
|
用途:排程管理 API 共享 Blueprint(Wave 3 分包后各子模块共用)。
|
||||||
|
依赖:Flask Blueprint。
|
||||||
|
逻辑:config/tasks/runs 子模块在此 bp 上注册路由;__init__ 导出 schedule_admin_bp。
|
||||||
|
"""
|
||||||
|
from flask import Blueprint
|
||||||
|
|
||||||
|
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/schedule/common.py
|
||||||
|
|
||||||
|
用途:排程 API 共享序列化 helper。
|
||||||
|
依赖:models、services/schedule/query_service。
|
||||||
|
逻辑:config/tasks 子模块导出任务配置 JSON 时共用。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||||
|
from app.services.schedule.query_service import serialize_task
|
||||||
|
from app.services.schedule.serialization import safe_json_value
|
||||||
|
|
||||||
|
|
||||||
|
def serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||||
|
"""
|
||||||
|
将 ScheduleTaskConfig ORM 转为 API 响应 dict。
|
||||||
|
核心逻辑:扁平化 data_source / external_api 嵌套结构。
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
'row_id_key': cfg_model.row_id_key or 'id',
|
||||||
|
'log_prefix': cfg_model.log_prefix or '',
|
||||||
|
'base_fetch_sql': cfg_model.base_fetch_sql or '',
|
||||||
|
'fetch_where_conditions': cfg_model.fetch_where_conditions or '',
|
||||||
|
'fetch_order_by': cfg_model.fetch_order_by or '',
|
||||||
|
'writeback_sql': cfg_model.writeback_sql or '',
|
||||||
|
'detail_sql': cfg_model.detail_sql or '',
|
||||||
|
'alias_order': cfg_model.alias_order or [],
|
||||||
|
'detail_alias_order': cfg_model.detail_alias_order or [],
|
||||||
|
'header_labels': cfg_model.header_labels or {},
|
||||||
|
'data_source': {
|
||||||
|
'db_type': cfg_model.ds_db_type or 'sqlserver',
|
||||||
|
'host': cfg_model.ds_host or '',
|
||||||
|
'port': cfg_model.ds_port or '',
|
||||||
|
'database': cfg_model.ds_database or '',
|
||||||
|
'username': cfg_model.ds_username or '',
|
||||||
|
'password': cfg_model.ds_password or '',
|
||||||
|
'driver': cfg_model.ds_driver or '',
|
||||||
|
'encrypt': cfg_model.ds_encrypt or '',
|
||||||
|
'trust_cert': cfg_model.ds_trust_cert or '',
|
||||||
|
},
|
||||||
|
'external_api': {
|
||||||
|
'url': cfg_model.api_url or '',
|
||||||
|
'method': cfg_model.api_method or 'POST',
|
||||||
|
'headers': cfg_model.api_headers or {},
|
||||||
|
'body_template': cfg_model.api_body_template or '',
|
||||||
|
},
|
||||||
|
'dify_system_prompt': cfg_model.dify_system_prompt or '',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||||
|
"""组装单条排程导出 JSON(含 config 快照)。"""
|
||||||
|
payload = serialize_task(task)
|
||||||
|
payload['config'] = serialize_task_config(cfg_model) if cfg_model else None
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ['safe_json_value', 'serialize_task_config', 'serialize_task_for_export']
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/schedule/config.py
|
||||||
|
|
||||||
|
用途:排程任务 SQL/数据源配置 API 与测试接口(薄路由层)。
|
||||||
|
依赖:schedule.blueprint、schedule.common、schedule_contract、services/schedule/*。
|
||||||
|
逻辑:/schedule-config/* 路由;配置更新仅允许 data_pipeline 任务修改 data_source_type。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import jsonify, request
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.api.schedule.blueprint import schedule_admin_bp
|
||||||
|
from app.api.schedule.common import serialize_task_config
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.core.errors import NotFoundError, ValidationError
|
||||||
|
from app.models import ScheduleTask, ScheduleTaskConfig
|
||||||
|
from app.services.schedule.schedule_contract import (
|
||||||
|
SCHEDULE_TYPE_DATA_PIPELINE,
|
||||||
|
apply_schedule_contract_to_payload,
|
||||||
|
platform_job_allows_config,
|
||||||
|
)
|
||||||
|
from app.services.schedule.sql_config import upsert_schedule_task_config
|
||||||
|
from app.services.schedule.sql_preview_service import preview_fetch_sql
|
||||||
|
from app.services.schedule.test_run_service import execute_test_run
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_schedule_task_config(task_id: int):
|
||||||
|
"""返回排程任务关联的 SQL/数据源配置。"""
|
||||||
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||||
|
if not cfg_model:
|
||||||
|
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
||||||
|
return jsonify({'data_source_type': task.data_source_type, 'config': serialize_task_config(cfg_model)})
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
||||||
|
@require_admin
|
||||||
|
def update_schedule_task_config(task_id: int):
|
||||||
|
"""
|
||||||
|
更新排程 data_source_type 与 ScheduleTaskConfig。
|
||||||
|
核心逻辑:仅 data_pipeline 允许改 data_source_type;platform_job 禁止经此接口绕过契约。
|
||||||
|
"""
|
||||||
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
try:
|
||||||
|
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE:
|
||||||
|
if 'data_source_type' in data:
|
||||||
|
raise ValidationError(
|
||||||
|
'data_source_type can only be updated for data_pipeline schedules; '
|
||||||
|
'use schedule task PATCH for platform_job'
|
||||||
|
)
|
||||||
|
elif 'data_source_type' in data:
|
||||||
|
contract = apply_schedule_contract_to_payload({
|
||||||
|
'schedule_type': task.schedule_type,
|
||||||
|
'data_source_type': data.get('data_source_type'),
|
||||||
|
'platform_api_path': task.platform_api_path,
|
||||||
|
})
|
||||||
|
task.data_source_type = contract['data_source_type']
|
||||||
|
|
||||||
|
config_data = data.get('config', data)
|
||||||
|
if isinstance(config_data, dict) and config_data:
|
||||||
|
# platform_job 仅白名单且 enabled 的任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
|
||||||
|
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
|
||||||
|
raise ValidationError(
|
||||||
|
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
|
||||||
|
)
|
||||||
|
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||||
|
db.session.commit()
|
||||||
|
cfg_model = task.config
|
||||||
|
if cfg_model is None:
|
||||||
|
with db.session.no_autoflush:
|
||||||
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||||
|
return jsonify({
|
||||||
|
'data_source_type': task.data_source_type,
|
||||||
|
'config': serialize_task_config(cfg_model) if cfg_model else None,
|
||||||
|
})
|
||||||
|
except ValidationError:
|
||||||
|
db.session.rollback()
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
db.session.rollback()
|
||||||
|
raise ValidationError(str(exc))
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def test_schedule_sql(task_id: int):
|
||||||
|
"""预览抓取 SQL 执行结果(最多 100 行)。"""
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
return jsonify(preview_fetch_sql(task_id, data))
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def test_schedule_run(task_id: int):
|
||||||
|
"""同步执行小规模排程测试跑(默认 3 条),可选 KB 同步。"""
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
payload = execute_test_run(
|
||||||
|
task_id,
|
||||||
|
data,
|
||||||
|
triggered_by_user_id=getattr(get_current_user(), 'id', None),
|
||||||
|
)
|
||||||
|
return jsonify(payload)
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/schedule/platform_tasks.py
|
||||||
|
|
||||||
|
用途:平台任务契约 API(任务定义 + 动态选项),供前端 DynamicTaskParamsForm 通用渲染。
|
||||||
|
依赖:schedule.blueprint、job_registry(任务契约中心)、job_options(options_source 分发)。
|
||||||
|
逻辑:/platform-tasks/definitions 下发 params_schema(仅 enabled);/platform-tasks/options 按 source 返回统一选项;
|
||||||
|
前端不再按任务硬编码 UI,红框参数区完全由 schema 决定。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from flask import request
|
||||||
|
|
||||||
|
from app.api.schedule.blueprint import schedule_admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.core.errors import ValidationError
|
||||||
|
from app.core.response import ok
|
||||||
|
from app.services.schedule.job_options import list_job_options
|
||||||
|
from app.services.schedule.job_registry import list_platform_jobs
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/platform-tasks/definitions', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_platform_task_definitions():
|
||||||
|
"""
|
||||||
|
返回全部启用平台任务的完整契约(展示信息 + params_schema + defaults)。
|
||||||
|
核心逻辑:直接序列化 job_registry 注册项;前端选择任务后按 params_schema 渲染参数表单。
|
||||||
|
"""
|
||||||
|
return ok([
|
||||||
|
{
|
||||||
|
'task_type': job.key,
|
||||||
|
'label': job.label,
|
||||||
|
'label_key': job.label_key or None,
|
||||||
|
'description': job.description,
|
||||||
|
'description_key': job.description_key or None,
|
||||||
|
'category': job.category,
|
||||||
|
'enabled': job.enabled,
|
||||||
|
'params_schema': list(job.params_schema),
|
||||||
|
'defaults': job.defaults,
|
||||||
|
}
|
||||||
|
for job in list_platform_jobs()
|
||||||
|
if job.enabled
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/platform-tasks/options', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_platform_task_options():
|
||||||
|
"""
|
||||||
|
按 options_source 返回动态选项(统一 {label, value, description?})。
|
||||||
|
核心逻辑:source 参数分发到 job_options 登记的 provider;前端不感知数据来源。
|
||||||
|
"""
|
||||||
|
source = str(request.args.get('source') or '').strip()
|
||||||
|
if not source:
|
||||||
|
raise ValidationError('source is required')
|
||||||
|
try:
|
||||||
|
options = list_job_options(source)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValidationError(str(exc))
|
||||||
|
return ok(options)
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/schedule/rpa_workers.py
|
||||||
|
|
||||||
|
用途:管理端查询货代库存 RPA Worker 在线状态与就绪摘要。
|
||||||
|
依赖:schedule.blueprint、rpa_worker_heartbeat.serialize_rpa_worker_status。
|
||||||
|
逻辑:ScheduleWorkbenchPanel 在库存 RPA 排程工作台展示 worker 心跳状态。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.api.schedule.blueprint import schedule_admin_bp
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.core.response import ok
|
||||||
|
from app.services.shipping_notice.rpa_worker_heartbeat import serialize_rpa_worker_status
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/rpa-workers/status', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_rpa_workers_status():
|
||||||
|
"""
|
||||||
|
返回库存 RPA Worker 心跳摘要(在线/离线、最后心跳时间、就绪原因)。
|
||||||
|
核心逻辑:读取 Redis/内存心跳并与当前环境、trigger 目录比对。
|
||||||
|
"""
|
||||||
|
return ok(serialize_rpa_worker_status())
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/schedule/runs.py
|
||||||
|
|
||||||
|
用途:排程运行触发与运行记录查询 API。
|
||||||
|
依赖:schedule.blueprint、services/schedule/query_service、scheduler_service。
|
||||||
|
逻辑:/schedules/<id>/run、/schedules/<id>/runs、/schedule-runs/* 路由。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
from datetime import datetime
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from flask import current_app, jsonify, request, send_file
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.api.schedule.blueprint import schedule_admin_bp
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.core.errors import ConflictError, NotFoundError
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
from app.services.schedule.query_service import get_run, list_runs, serialize_run
|
||||||
|
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
||||||
|
from app.services.schedule.shipping_inventory_rpa_archive import resolve_inventory_raw_zip_download
|
||||||
|
from app.services.schedule.shipping_inventory_rpa_finalize import recover_stale_awaiting_rpa_schedule_runs
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def run_schedule(task_id: int):
|
||||||
|
"""
|
||||||
|
手动触发排程后台执行。
|
||||||
|
核心逻辑:创建 running ScheduleRun → 守护线程内 run_task_now。
|
||||||
|
"""
|
||||||
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||||
|
user = get_current_user()
|
||||||
|
existing = (
|
||||||
|
db.session.query(ScheduleRun)
|
||||||
|
.filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running')
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if existing:
|
||||||
|
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||||
|
run = ScheduleRun(
|
||||||
|
run_no=_generate_run_no(),
|
||||||
|
schedule_task_id=task.id,
|
||||||
|
trigger_type='manual',
|
||||||
|
triggered_by_user_id=getattr(user, 'id', None),
|
||||||
|
started_at=datetime.utcnow(),
|
||||||
|
status='running',
|
||||||
|
)
|
||||||
|
db.session.add(run)
|
||||||
|
db.session.commit()
|
||||||
|
app = current_app._get_current_object()
|
||||||
|
run_id = run.id
|
||||||
|
|
||||||
|
def _background():
|
||||||
|
with app.app_context():
|
||||||
|
t = db.session.get(ScheduleTask, task_id)
|
||||||
|
r = db.session.get(ScheduleRun, run_id)
|
||||||
|
if not t or not r:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
||||||
|
except Exception as exc:
|
||||||
|
try:
|
||||||
|
r = db.session.get(ScheduleRun, run_id)
|
||||||
|
if r and r.status == 'running':
|
||||||
|
r.status = 'failed'
|
||||||
|
r.error_message = str(exc)
|
||||||
|
r.finished_at = datetime.utcnow()
|
||||||
|
db.session.commit()
|
||||||
|
except Exception:
|
||||||
|
db.session.rollback()
|
||||||
|
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||||
|
|
||||||
|
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||||
|
t.start()
|
||||||
|
fresh = db.session.get(ScheduleRun, run_id)
|
||||||
|
return jsonify(serialize_run(fresh))
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_schedule_runs(task_id: int):
|
||||||
|
"""按任务 ID 分页/过滤返回运行记录。"""
|
||||||
|
status = str(request.args.get('status') or '').strip() or None
|
||||||
|
limit = int(request.args.get('limit') or 100)
|
||||||
|
started_after = None
|
||||||
|
started_before = None
|
||||||
|
sa = request.args.get('started_after')
|
||||||
|
sb = request.args.get('started_before')
|
||||||
|
if sa:
|
||||||
|
try:
|
||||||
|
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
if sb:
|
||||||
|
try:
|
||||||
|
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
return jsonify(
|
||||||
|
list_runs(
|
||||||
|
task_id=task_id,
|
||||||
|
status=status,
|
||||||
|
started_after=started_after,
|
||||||
|
started_before=started_before,
|
||||||
|
limit=limit,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_schedule_run(run_id: int):
|
||||||
|
"""返回单条运行记录详情。"""
|
||||||
|
run = get_run(run_id)
|
||||||
|
if not run:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
return jsonify(serialize_run(run))
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_schedule_run_excel(run_id: int):
|
||||||
|
"""下载运行结果 Excel 附件。"""
|
||||||
|
run = get_run(run_id)
|
||||||
|
if not run:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
if not run.excel_file_data:
|
||||||
|
raise NotFoundError('Excel not found')
|
||||||
|
buf = BytesIO(run.excel_file_data)
|
||||||
|
return send_file(
|
||||||
|
buf,
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=run.excel_file_name or 'result.xlsx',
|
||||||
|
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/inventory-raw-zip', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_schedule_run_inventory_raw_zip(run_id: int):
|
||||||
|
"""下载库存 RPA 排程 run 的原始库存 Excel 打包(ZIP + manifest)。"""
|
||||||
|
run = get_run(run_id)
|
||||||
|
if not run:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
zip_path, file_name = resolve_inventory_raw_zip_download(run)
|
||||||
|
return send_file(
|
||||||
|
zip_path,
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=file_name,
|
||||||
|
mimetype='application/zip',
|
||||||
|
)
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/schedule/tasks.py
|
||||||
|
|
||||||
|
用途:排程任务 CRUD、导入导出、启用/禁用 API。
|
||||||
|
依赖:schedule.blueprint、schedule.common、services/schedule/*。
|
||||||
|
逻辑:/schedules* 路由(不含 run 触发与运行记录);job_params 归一化与切换重置
|
||||||
|
由 scheduler_service.create_task/update_task 唯一兜底;本层只做请求校验与
|
||||||
|
ValueError→ValidationError 映射。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from flask import Response, jsonify, request
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.api.schedule.blueprint import schedule_admin_bp
|
||||||
|
from app.api.schedule.common import serialize_task_for_export
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.decorators import require_admin
|
||||||
|
from app.core.errors import NotFoundError, ValidationError
|
||||||
|
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||||
|
from app.services.schedule.query_service import list_tasks, serialize_task
|
||||||
|
from app.services.schedule.import_service import import_schedules_from_payload
|
||||||
|
from app.services.schedule.schedule_contract import (
|
||||||
|
apply_schedule_contract_to_payload,
|
||||||
|
assert_schedule_config_writable,
|
||||||
|
)
|
||||||
|
from app.services.schedule.scheduler_service import create_task, update_task
|
||||||
|
from app.services.schedule.sql_config import upsert_schedule_task_config
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_schedules():
|
||||||
|
"""返回全部排程任务列表。"""
|
||||||
|
return jsonify(list_tasks())
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedule/platform-jobs', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_platform_jobs():
|
||||||
|
"""
|
||||||
|
返回 Job Registry 已启用平台任务列表,供前端下拉动态加载。
|
||||||
|
与 /platform-tasks/definitions 一致:只返回 enabled=True,避免下拉可选却无参数定义。
|
||||||
|
"""
|
||||||
|
from app.services.schedule.job_registry import list_platform_jobs
|
||||||
|
|
||||||
|
return jsonify([
|
||||||
|
{
|
||||||
|
'key': job.key,
|
||||||
|
'label_key': job.label_key or None,
|
||||||
|
'label': job.label,
|
||||||
|
'description': job.description,
|
||||||
|
'enabled': job.enabled,
|
||||||
|
}
|
||||||
|
for job in list_platform_jobs()
|
||||||
|
if job.enabled
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def export_schedule(task_id: int):
|
||||||
|
"""导出单条排程任务及配置为 JSON 文件。"""
|
||||||
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||||
|
payload = {
|
||||||
|
'schema_version': 1,
|
||||||
|
'exported_at': datetime.utcnow().isoformat(),
|
||||||
|
'schedules': [serialize_task_for_export(task, cfg_model)],
|
||||||
|
}
|
||||||
|
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||||
|
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||||
|
return Response(
|
||||||
|
body,
|
||||||
|
mimetype='application/json; charset=utf-8',
|
||||||
|
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def import_schedules():
|
||||||
|
"""批量导入排程 JSON(按 schedule_no upsert)。"""
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
user = get_current_user()
|
||||||
|
result = import_schedules_from_payload(
|
||||||
|
data.get('schedules'),
|
||||||
|
actor_id=getattr(user, 'id', None),
|
||||||
|
)
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def post_schedule():
|
||||||
|
"""创建排程任务。"""
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
user = get_current_user()
|
||||||
|
schedule_type = str(data.get('schedule_type') or 'data_pipeline')
|
||||||
|
data_source_type = data.get('data_source_type')
|
||||||
|
platform_api_path = data.get('platform_api_path')
|
||||||
|
config_data = data.get('config')
|
||||||
|
if config_data is not None and not isinstance(config_data, dict):
|
||||||
|
raise ValidationError('config must be a JSON object')
|
||||||
|
if schedule_type.strip().lower() == 'data_pipeline' and data_source_type in (None, ''):
|
||||||
|
data_source_type = 'database'
|
||||||
|
try:
|
||||||
|
# [STEP 1] 契约与 config 写入权限预校验(失败不落库);job_params 由 create_task 归一化
|
||||||
|
contract = apply_schedule_contract_to_payload({
|
||||||
|
'schedule_type': schedule_type,
|
||||||
|
'data_source_type': data_source_type,
|
||||||
|
'platform_api_path': platform_api_path,
|
||||||
|
})
|
||||||
|
assert_schedule_config_writable(
|
||||||
|
schedule_type=contract['schedule_type'],
|
||||||
|
platform_api_path=contract['platform_api_path'],
|
||||||
|
config=config_data,
|
||||||
|
)
|
||||||
|
task = create_task(
|
||||||
|
name=str(data.get('name') or '').strip(),
|
||||||
|
schedule_type=schedule_type,
|
||||||
|
owner_user_id=int(data.get('owner_user_id')),
|
||||||
|
cron_expr=str(data.get('cron_expr') or '').strip(),
|
||||||
|
schedule_timezone=data.get('schedule_timezone'),
|
||||||
|
wait_seconds=int(data.get('wait_seconds') or 0),
|
||||||
|
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
|
||||||
|
platform_api_path=str(platform_api_path).strip() if platform_api_path else None,
|
||||||
|
data_source_type=str(data_source_type) if data_source_type is not None else None,
|
||||||
|
job_params=data.get('job_params'),
|
||||||
|
notify_user_ids_json=data.get('notify_user_ids_json')
|
||||||
|
if isinstance(data.get('notify_user_ids_json'), list)
|
||||||
|
else [],
|
||||||
|
notify_enabled=bool(data.get('notify_enabled', True)),
|
||||||
|
enabled=bool(data.get('enabled', True)),
|
||||||
|
kb_sync_enabled=bool(data.get('kb_sync_enabled', False)),
|
||||||
|
kb_group_id=int(data.get('kb_group_id')) if data.get('kb_group_id') not in (None, '', 0, '0') else None,
|
||||||
|
actor_id=getattr(user, 'id', None),
|
||||||
|
commit=not config_data,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValidationError(str(exc))
|
||||||
|
if config_data:
|
||||||
|
try:
|
||||||
|
upsert_schedule_task_config(task.id, config_data, commit=False)
|
||||||
|
if not task.dify_agent_id:
|
||||||
|
cfg_model = task.config
|
||||||
|
if cfg_model is None:
|
||||||
|
with db.session.no_autoflush:
|
||||||
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
||||||
|
if cfg_model and cfg_model.dify_system_prompt:
|
||||||
|
cfg_model.dify_system_prompt = None
|
||||||
|
db.session.commit()
|
||||||
|
except Exception:
|
||||||
|
db.session.rollback()
|
||||||
|
raise
|
||||||
|
db.session.refresh(task)
|
||||||
|
return jsonify(serialize_task(task)), 201
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def get_schedule(task_id: int):
|
||||||
|
"""返回单条排程任务详情。"""
|
||||||
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
return jsonify(serialize_task(task))
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||||
|
@require_admin
|
||||||
|
def patch_schedule(task_id: int):
|
||||||
|
"""更新排程任务字段与关联配置。"""
|
||||||
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
user = get_current_user()
|
||||||
|
config_data = data.get('config')
|
||||||
|
if config_data is not None and not isinstance(config_data, dict):
|
||||||
|
raise ValidationError('config must be a JSON object')
|
||||||
|
try:
|
||||||
|
# [STEP 1] 契约与 config 预校验;job_params 重置/归一化由 update_task 唯一兜底
|
||||||
|
contract = apply_schedule_contract_to_payload({
|
||||||
|
'schedule_type': data.get('schedule_type', task.schedule_type),
|
||||||
|
'data_source_type': data.get('data_source_type', task.data_source_type),
|
||||||
|
'platform_api_path': data.get('platform_api_path', task.platform_api_path),
|
||||||
|
})
|
||||||
|
assert_schedule_config_writable(
|
||||||
|
schedule_type=contract['schedule_type'],
|
||||||
|
platform_api_path=contract['platform_api_path'],
|
||||||
|
config=config_data,
|
||||||
|
)
|
||||||
|
task = update_task(
|
||||||
|
task,
|
||||||
|
payload=data,
|
||||||
|
actor_id=getattr(user, 'id', None),
|
||||||
|
commit=not config_data,
|
||||||
|
)
|
||||||
|
if config_data:
|
||||||
|
upsert_schedule_task_config(task_id, config_data, commit=False)
|
||||||
|
if not task.dify_agent_id:
|
||||||
|
cfg_model = task.config
|
||||||
|
if cfg_model is None:
|
||||||
|
with db.session.no_autoflush:
|
||||||
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||||
|
if cfg_model and cfg_model.dify_system_prompt:
|
||||||
|
cfg_model.dify_system_prompt = None
|
||||||
|
if config_data:
|
||||||
|
db.session.commit()
|
||||||
|
except ValueError as exc:
|
||||||
|
db.session.rollback()
|
||||||
|
raise ValidationError(str(exc))
|
||||||
|
except Exception:
|
||||||
|
db.session.rollback()
|
||||||
|
raise
|
||||||
|
return jsonify(serialize_task(task))
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||||
|
@require_admin
|
||||||
|
def delete_schedule(task_id: int):
|
||||||
|
"""删除排程任务及其运行记录;中断进行中的 run。"""
|
||||||
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.schedule.scheduler_service import request_cancel_run
|
||||||
|
|
||||||
|
running_runs = (
|
||||||
|
db.session.query(ScheduleRun)
|
||||||
|
.filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running')
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
for rr in running_runs:
|
||||||
|
request_cancel_run(rr.id)
|
||||||
|
rr.status = 'failed'
|
||||||
|
rr.error_message = '排程已被删除,执行中断'
|
||||||
|
rr.finished_at = datetime.utcnow()
|
||||||
|
if running_runs:
|
||||||
|
db.session.commit()
|
||||||
|
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||||
|
db.session.delete(task)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'ok': True})
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def enable_schedule(task_id: int):
|
||||||
|
"""
|
||||||
|
启用排程并重新计算 next_run_at。
|
||||||
|
核心逻辑:委托 enable_task 重新校验契约与 job_params,拒绝已停用 platform_job 重新入队。
|
||||||
|
"""
|
||||||
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.schedule.scheduler_service import enable_task
|
||||||
|
|
||||||
|
try:
|
||||||
|
task = enable_task(task)
|
||||||
|
except ValueError as exc:
|
||||||
|
db.session.rollback()
|
||||||
|
raise ValidationError(str(exc)) from exc
|
||||||
|
return jsonify(serialize_task(task))
|
||||||
|
|
||||||
|
|
||||||
|
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||||
|
@require_admin
|
||||||
|
def disable_schedule(task_id: int):
|
||||||
|
"""禁用排程并清空 next_run_at。"""
|
||||||
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
task.enabled = False
|
||||||
|
task.next_run_at = None
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'ok': True})
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/schedule_admin.py
|
||||||
|
|
||||||
|
用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。
|
||||||
|
依赖:app.api.schedule。
|
||||||
|
逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。
|
||||||
|
"""
|
||||||
|
from app.api.schedule import schedule_admin_bp
|
||||||
|
|
||||||
|
__all__ = ['schedule_admin_bp']
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
"""
|
||||||
|
api/shipping_notice_tools.py
|
||||||
|
|
||||||
|
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||||
|
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
|
||||||
|
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.errors import (
|
||||||
|
AppError,
|
||||||
|
NotFoundError,
|
||||||
|
ServiceUnavailableError,
|
||||||
|
UnauthorizedError,
|
||||||
|
ValidationError,
|
||||||
|
)
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
|
||||||
|
from app.services.shipping_notice.query_service import (
|
||||||
|
EXPORT_MIME_TYPE,
|
||||||
|
get_batch_by_no,
|
||||||
|
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.tool_common import switch_batch_focus
|
||||||
|
from app.services.shipping_notice.rpa_worker_heartbeat import record_rpa_worker_heartbeat
|
||||||
|
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
|
||||||
|
|
||||||
|
shipping_notice_bp = Blueprint("shipping_notice", __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_tool_auth() -> None:
|
||||||
|
"""
|
||||||
|
校验货代 Tool API 鉴权 Header。
|
||||||
|
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
|
||||||
|
|
||||||
|
核心逻辑:只接受 `Authorization: Bearer <token>` 或 `X-Integration-Key`。
|
||||||
|
货代专用 `SHIPPING_NOTICE_TOOL_API_KEY` 优先,未配置时回退 `INTEGRATION_API_KEY`;
|
||||||
|
未配置任何可用 key 时报服务不可用,缺失或错误时报未授权。
|
||||||
|
"""
|
||||||
|
configured = str(
|
||||||
|
current_app.config.get('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||||
|
or current_app.config.get('INTEGRATION_API_KEY')
|
||||||
|
or ''
|
||||||
|
).strip()
|
||||||
|
if not configured:
|
||||||
|
raise ServiceUnavailableError(
|
||||||
|
'SHIPPING_NOTICE_TOOL_API_KEY or INTEGRATION_API_KEY is not configured',
|
||||||
|
code='missing_auth',
|
||||||
|
)
|
||||||
|
bearer = str(request.headers.get('Authorization') or '').strip()
|
||||||
|
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
|
||||||
|
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||||
|
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 结构。"""
|
||||||
|
body: dict[str, object] = {'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}
|
||||||
|
if exc.details:
|
||||||
|
body['details'] = exc.details
|
||||||
|
return jsonify(body), exc.http_status
|
||||||
|
|
||||||
|
@shipping_notice_bp.before_request
|
||||||
|
def _verify_tool_access():
|
||||||
|
"""
|
||||||
|
对货代 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 触发时机】:仅供 Hxops 内部建单链路调用;不是 Dify 画布正式入口。
|
||||||
|
"""
|
||||||
|
return jsonify(shipping_tools.create_task(_payload()))
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
|
||||||
|
def tool_create_batch():
|
||||||
|
"""
|
||||||
|
创建或复用发货批次。
|
||||||
|
【AI 触发时机】:仅供 Hxops 内部建批链路调用;不是 Dify 画布正式入口。
|
||||||
|
"""
|
||||||
|
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, _created = shipping_tools.create_batch(payload)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
|
||||||
|
|
||||||
|
@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 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||||
|
"""
|
||||||
|
return jsonify(shipping_tools.ensure_inventory(_payload()))
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
|
||||||
|
def tool_auto_progress():
|
||||||
|
"""
|
||||||
|
自动推进任务。
|
||||||
|
【AI 触发时机】:仅供后端 orchestrator / worker 调用;不是 Dify 画布正式入口。
|
||||||
|
"""
|
||||||
|
return jsonify(shipping_tools.auto_progress(_payload()))
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
|
||||||
|
def tool_match_inventory():
|
||||||
|
"""
|
||||||
|
执行库存匹配。
|
||||||
|
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||||
|
"""
|
||||||
|
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/confirm_inventory_source', methods=['POST'])
|
||||||
|
def tool_confirm_inventory_source():
|
||||||
|
"""
|
||||||
|
确认库存查询来源(仅提交 source_code)。
|
||||||
|
【AI 触发时机】:用户在库存源人工检查点选择正式库存源后调用。
|
||||||
|
"""
|
||||||
|
return jsonify(shipping_tools.confirm_inventory_source(_payload()))
|
||||||
|
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
|
||||||
|
def tool_generate_shipment_excel():
|
||||||
|
"""
|
||||||
|
生成出货 Excel。
|
||||||
|
【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。
|
||||||
|
"""
|
||||||
|
return jsonify(shipping_tools.generate_excel(_payload()))
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
|
||||||
|
def tool_upload_to_freight():
|
||||||
|
"""
|
||||||
|
上传到货代系统或确认人工上传完成。
|
||||||
|
【AI 触发时机】:仅供后端主调度、内部恢复链路或人工上传收口调用;不是 Dify 画布正式入口。
|
||||||
|
"""
|
||||||
|
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:
|
||||||
|
raise ValidationError("batch_no is required")
|
||||||
|
batch = get_batch_by_no(batch_no)
|
||||||
|
if not batch:
|
||||||
|
raise NotFoundError("batch not found")
|
||||||
|
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
|
||||||
|
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已获取批次 {batch.batch_no} 状态', 'data': {**serialize_batch_summary(batch), 'focus_task': serialize_task_summary(focus_task) if focus_task else None, 'tasks': list_batch_task_summaries(batch)}})
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
|
||||||
|
def tool_switch_focus_task():
|
||||||
|
"""
|
||||||
|
切换批次当前焦点任务。
|
||||||
|
【AI 触发时机】:当前仅保留给 Hxops 内部切票能力;不属于 Dify 正式导出 Tool。
|
||||||
|
"""
|
||||||
|
payload = _payload()
|
||||||
|
batch_no = str(payload.get('batch_no') or '').strip()
|
||||||
|
task_no = str(payload.get('task_no') or payload.get('target_task_no') or '').strip()
|
||||||
|
if not batch_no or not task_no:
|
||||||
|
raise ValidationError("batch_no and task_no are required")
|
||||||
|
batch = get_batch_by_no(batch_no)
|
||||||
|
if not batch:
|
||||||
|
raise NotFoundError("batch not found")
|
||||||
|
task = get_task_in_batch(batch_no, task_no)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError("task not found in batch")
|
||||||
|
switch_batch_focus(
|
||||||
|
batch,
|
||||||
|
task,
|
||||||
|
source="tool_api",
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||||
|
def rpa_worker_heartbeat():
|
||||||
|
"""
|
||||||
|
RPA Worker 心跳上报。
|
||||||
|
核心逻辑:校验 payload 后写入 Redis/内存;供触发库存 RPA 前就绪检查使用。
|
||||||
|
"""
|
||||||
|
payload = _payload()
|
||||||
|
try:
|
||||||
|
worker = record_rpa_worker_heartbeat(payload)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ValidationError(str(exc))
|
||||||
|
except ServiceUnavailableError:
|
||||||
|
raise
|
||||||
|
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||||
|
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
|
||||||
|
def rpa_inventory_ready():
|
||||||
|
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
|
||||||
|
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/rpa/inventory-batch-ready', methods=['POST'])
|
||||||
|
def rpa_inventory_batch_ready():
|
||||||
|
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
|
||||||
|
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||||
|
def repair_task_inventory_attachment(task_no: str):
|
||||||
|
"""
|
||||||
|
从任务库存快照幂等重建正式附件(不重新消费 RPA callback)。
|
||||||
|
核心逻辑:供晋升失败或 marker 异常后的人工/后台补偿。
|
||||||
|
"""
|
||||||
|
payload = _payload()
|
||||||
|
payload.setdefault("task_no", task_no)
|
||||||
|
payload.setdefault("task_id", task_no)
|
||||||
|
return jsonify(shipping_tools.repair_task_inventory_attachment(payload))
|
||||||
|
|
||||||
|
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
|
||||||
|
def rpa_upload_complete():
|
||||||
|
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
|
||||||
|
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:
|
||||||
|
raise NotFoundError(err_msg)
|
||||||
|
resolved = resolve_task_export_download(task)
|
||||||
|
assert resolved is not None
|
||||||
|
path, download_name = resolved
|
||||||
|
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""
|
||||||
|
Speech transcription API — forwards audio to SiliconFlow ASR.
|
||||||
|
"""
|
||||||
|
from flask import Blueprint, jsonify, request
|
||||||
|
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import UnauthorizedError, ValidationError, ServiceUnavailableError
|
||||||
|
from app.services.speech_asr import SpeechAsrService
|
||||||
|
|
||||||
|
speech_bp = Blueprint('speech', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@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,11 @@
|
|||||||
|
"""
|
||||||
|
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
|
||||||
|
from app.api.tools.maintenance import maintenance_tool_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,9 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/tools/maintenance.py
|
||||||
|
|
||||||
|
用途:设备维保 Tool API Blueprint re-export。
|
||||||
|
依赖:app.api.maintenance_tools。
|
||||||
|
逻辑:保持 api.tools 分包统一入口,register_blueprints 只从 app.api.tools 导入各 Tool Blueprint。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from app.api.maintenance_tools import maintenance_tool_bp # noqa: F401
|
||||||
@@ -0,0 +1,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']
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/training.py
|
||||||
|
|
||||||
|
用途:提供新人培训用户侧进度接口与管理端统计导出接口。
|
||||||
|
依赖:JWT 当前用户解析、training_service、Flask Blueprint/send_file。
|
||||||
|
逻辑:员工端负责读写个人培训进度;管理端负责真实记录查询、统计与 Excel 导出。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from flask import Blueprint, jsonify, request, send_file
|
||||||
|
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import ForbiddenError, UnauthorizedError
|
||||||
|
from app.services.training_service import (
|
||||||
|
export_training_records_excel,
|
||||||
|
get_user_training_record,
|
||||||
|
list_training_records,
|
||||||
|
serialize_training_record,
|
||||||
|
summarize_training_records,
|
||||||
|
upsert_user_training_record,
|
||||||
|
)
|
||||||
|
|
||||||
|
training_user_bp = Blueprint("training_user", __name__)
|
||||||
|
training_admin_bp = Blueprint("training_admin", __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_user():
|
||||||
|
"""确保当前请求存在登录用户。"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _require_training_admin():
|
||||||
|
"""
|
||||||
|
确保当前用户具备培训管理权限。
|
||||||
|
|
||||||
|
用途:统一拦截 HR 管理面板的数据查询、统计与导出接口。
|
||||||
|
核心逻辑:优先复用 User.can_manage_training(),把“角色默认权限 + 前端可配置功能权限”收敛到同一个判断入口。
|
||||||
|
"""
|
||||||
|
user = _require_user()
|
||||||
|
if not user.can_manage_training():
|
||||||
|
raise ForbiddenError("Training admin privilege required")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@training_user_bp.route("/training-record", methods=["GET"])
|
||||||
|
def get_my_training_record():
|
||||||
|
"""读取当前用户的培训进度;未创建时返回 null data。"""
|
||||||
|
user = _require_user()
|
||||||
|
record = get_user_training_record(user.id)
|
||||||
|
return jsonify(serialize_training_record(record) if record else None)
|
||||||
|
|
||||||
|
|
||||||
|
@training_user_bp.route("/training-record/progress", methods=["PUT"])
|
||||||
|
def save_my_training_record():
|
||||||
|
"""保存当前用户培训进度,用于视频完成、答题推进与结算归档。"""
|
||||||
|
user = _require_user()
|
||||||
|
payload = request.get_json() or {}
|
||||||
|
record = upsert_user_training_record(user, payload)
|
||||||
|
return jsonify(serialize_training_record(record))
|
||||||
|
|
||||||
|
|
||||||
|
@training_admin_bp.route("/training-records", methods=["GET"])
|
||||||
|
def list_admin_training_records():
|
||||||
|
"""列出培训记录,支持关键字、部门、状态筛选。"""
|
||||||
|
_require_training_admin()
|
||||||
|
keyword = request.args.get("keyword")
|
||||||
|
department = request.args.get("department")
|
||||||
|
status = request.args.get("status")
|
||||||
|
|
||||||
|
result = list_training_records(keyword=keyword, department=department, status=status)
|
||||||
|
all_records = list_training_records()
|
||||||
|
department_options = sorted({str(item.department or "").strip() for item in all_records.records if str(item.department or "").strip()})
|
||||||
|
|
||||||
|
page = max(1, request.args.get("page", type=int) or 1)
|
||||||
|
page_size = max(1, min(200, request.args.get("page_size", type=int) or max(result.total, 1)))
|
||||||
|
start = (page - 1) * page_size
|
||||||
|
end = start + page_size
|
||||||
|
items = result.records[start:end]
|
||||||
|
pages = max(1, (result.total + page_size - 1) // page_size) if result.total else 1
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"items": [serialize_training_record(item) for item in items],
|
||||||
|
"total": result.total,
|
||||||
|
"page": page,
|
||||||
|
"page_size": page_size,
|
||||||
|
"pages": pages,
|
||||||
|
"department_options": department_options,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@training_admin_bp.route("/training-records/stats", methods=["GET"])
|
||||||
|
def get_admin_training_stats():
|
||||||
|
"""返回培训记录聚合统计,供 HR 面板展示。"""
|
||||||
|
_require_training_admin()
|
||||||
|
result = list_training_records(
|
||||||
|
keyword=request.args.get("keyword"),
|
||||||
|
department=request.args.get("department"),
|
||||||
|
status=request.args.get("status"),
|
||||||
|
)
|
||||||
|
return jsonify(summarize_training_records(result.records))
|
||||||
|
|
||||||
|
|
||||||
|
@training_admin_bp.route("/training-records/export", methods=["GET"])
|
||||||
|
def export_admin_training_records():
|
||||||
|
"""导出培训记录为 Excel。"""
|
||||||
|
_require_training_admin()
|
||||||
|
result = list_training_records(
|
||||||
|
keyword=request.args.get("keyword"),
|
||||||
|
department=request.args.get("department"),
|
||||||
|
status=request.args.get("status"),
|
||||||
|
)
|
||||||
|
file_data, file_name = export_training_records_excel(result.records)
|
||||||
|
return send_file(
|
||||||
|
BytesIO(file_data),
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=file_name,
|
||||||
|
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
)
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,18 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/workspace/__init__.py
|
||||||
|
|
||||||
|
用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。
|
||||||
|
依赖:workspace 各子模块 blueprint。
|
||||||
|
逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。
|
||||||
|
"""
|
||||||
|
from app.api.workspace.announcements import workspace_announcements_bp
|
||||||
|
from app.api.workspace.file_check import workspace_file_check_bp
|
||||||
|
from app.api.workspace.schedule import workspace_schedule_bp
|
||||||
|
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
'workspace_announcements_bp',
|
||||||
|
'workspace_file_check_bp',
|
||||||
|
'workspace_schedule_bp',
|
||||||
|
'workspace_shipping_notice_bp',
|
||||||
|
]
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/workspace/announcements.py
|
||||||
|
|
||||||
|
用途:工作台/登录页只读公告列表 API。
|
||||||
|
依赖:services/admin/announcement_service(读活跃公告)。
|
||||||
|
逻辑:GET /announcements 无需登录;管理 CRUD 见 api/admin/announcements.py。
|
||||||
|
"""
|
||||||
|
from flask import Blueprint, jsonify
|
||||||
|
|
||||||
|
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||||
|
|
||||||
|
from app.core.errors import ServiceUnavailableError
|
||||||
|
from app.services.admin import announcement_service
|
||||||
|
|
||||||
|
workspace_announcements_bp = Blueprint('workspace_announcements', __name__)
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_announcements_bp.route('/announcements', methods=['GET'])
|
||||||
|
def list_active_announcements():
|
||||||
|
"""返回已发布的公司公告(公开,供登录页与工作台展示)。"""
|
||||||
|
try:
|
||||||
|
return jsonify(announcement_service.list_active_announcements())
|
||||||
|
except (OperationalError, DatabaseError) as exc:
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
|
current_app.logger.warning('workspace.announcements query failed: %s', exc)
|
||||||
|
raise ServiceUnavailableError('Database connection failed')
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/workspace/file_check.py
|
||||||
|
|
||||||
|
用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。
|
||||||
|
依赖:app.core.auth.jwt、app.core.errors、file_check_tools、schedule.query_service。
|
||||||
|
逻辑:鉴权后查询 ScheduleRun 进度;register_blueprints 经 workspace 包注册。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
from flask import Blueprint, jsonify, request, send_file
|
||||||
|
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import NotFoundError, UnauthorizedError, ValidationError
|
||||||
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
|
from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log_with_source
|
||||||
|
from app.services.schedule.query_service import get_run, serialize_run
|
||||||
|
|
||||||
|
workspace_file_check_bp = Blueprint("workspace_file_check", __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_user():
|
||||||
|
"""
|
||||||
|
校验当前登录用户。
|
||||||
|
Raises:
|
||||||
|
UnauthorizedError: 未认证。
|
||||||
|
"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError()
|
||||||
|
return user
|
||||||
|
|
||||||
|
def serialize_file_judgement(payload: dict) -> dict:
|
||||||
|
"""序列化检核判定统计(读取 response_summary_json.file_judgement)。"""
|
||||||
|
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||||
|
judgement = response_summary.get('file_judgement')
|
||||||
|
if not isinstance(judgement, dict):
|
||||||
|
judgement = {}
|
||||||
|
return {
|
||||||
|
'qualified_count': int(judgement.get('qualified_count') or 0),
|
||||||
|
'unqualified_count': int(judgement.get('unqualified_count') or 0),
|
||||||
|
'manual_count': int(judgement.get('manual_count') or 0),
|
||||||
|
'dify_error_count': int(judgement.get('dify_error_count') or 0),
|
||||||
|
'invalid_result_count': int(judgement.get('invalid_result_count') or 0),
|
||||||
|
'business_manual_count': int(judgement.get('business_manual_count') or 0),
|
||||||
|
'system_error_count': int(judgement.get('system_error_count') or 0),
|
||||||
|
'dify_timeout_count': int(judgement.get('dify_timeout_count') or 0),
|
||||||
|
'invalid_output_count': int(judgement.get('invalid_output_count') or 0),
|
||||||
|
'attachment_error_count': int(judgement.get('attachment_error_count') or 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
def serialize_current_step(payload: dict) -> dict | None:
|
||||||
|
response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {}
|
||||||
|
current_step = response_summary.get('current_step') if isinstance(response_summary.get('current_step'), dict) else None
|
||||||
|
if not current_step:
|
||||||
|
return None
|
||||||
|
return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)}
|
||||||
|
|
||||||
|
def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||||
|
payload = serialize_run(run)
|
||||||
|
total = int(payload.get('total_count') or 0)
|
||||||
|
success = int(payload.get('success_count') or 0)
|
||||||
|
failed = int(payload.get('failed_count') or 0)
|
||||||
|
skipped = int(payload.get('skipped_count') or 0)
|
||||||
|
processed = success + failed + skipped
|
||||||
|
percent = int(round(processed / total * 100)) if total > 0 else 0
|
||||||
|
percent = max(0, min(percent, 100))
|
||||||
|
return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}}
|
||||||
|
|
||||||
|
@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET'])
|
||||||
|
def workspace_file_check_run_for_log():
|
||||||
|
"""按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。"""
|
||||||
|
_require_user()
|
||||||
|
task_id = request.args.get('task_id', type=int)
|
||||||
|
chat_log_id = request.args.get('chat_log_id', type=int)
|
||||||
|
if not task_id or task_id <= 0:
|
||||||
|
raise ValidationError("task_id_required")
|
||||||
|
if not chat_log_id or chat_log_id <= 0:
|
||||||
|
raise ValidationError("chat_log_id_required")
|
||||||
|
match = find_run_for_chat_log_with_source(task_id=task_id, chat_log_id=chat_log_id)
|
||||||
|
return jsonify({
|
||||||
|
'ok': True,
|
||||||
|
'run': _serialize_progress_run(match.run) if match.run else None,
|
||||||
|
'match_source': match.match_source,
|
||||||
|
})
|
||||||
|
|
||||||
|
@workspace_file_check_bp.route('/file-check/runs/for-session', methods=['GET'])
|
||||||
|
def workspace_file_check_run_for_session():
|
||||||
|
"""已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。"""
|
||||||
|
_require_user()
|
||||||
|
return jsonify({'ok': True, 'run': None, 'match_source': None, 'session_updated_at': None})
|
||||||
|
|
||||||
|
@workspace_file_check_bp.route('/file-check/runs/active', methods=['GET'])
|
||||||
|
def workspace_file_check_active_run():
|
||||||
|
"""查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。"""
|
||||||
|
_require_user()
|
||||||
|
task_id = request.args.get('task_id', type=int)
|
||||||
|
conversation_id = str(request.args.get('conversation_id') or '').strip()
|
||||||
|
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id).filter(ScheduleRun.status == 'running')
|
||||||
|
if task_id is not None:
|
||||||
|
query = query.filter(ScheduleRun.schedule_task_id == task_id)
|
||||||
|
rows = query.order_by(ScheduleRun.id.desc()).all()
|
||||||
|
if task_id is not None:
|
||||||
|
run = rows[0] if rows else None
|
||||||
|
else:
|
||||||
|
run = next((row for row in rows if not conversation_id or str((row.api_request_json or {}).get('conversation_id') or '').strip() == conversation_id), None)
|
||||||
|
return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None})
|
||||||
|
|
||||||
|
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>', methods=['GET'])
|
||||||
|
def workspace_file_check_run_detail(run_id: int):
|
||||||
|
_require_user()
|
||||||
|
run = get_run(run_id)
|
||||||
|
if not run:
|
||||||
|
raise NotFoundError('run_not_found')
|
||||||
|
return jsonify({'ok': True, 'run': _serialize_progress_run(run)})
|
||||||
|
|
||||||
|
@workspace_file_check_bp.route('/file-check/runs/<int:run_id>/excel', methods=['GET'])
|
||||||
|
def workspace_file_check_run_excel(run_id: int):
|
||||||
|
_require_user()
|
||||||
|
run = get_run(run_id)
|
||||||
|
if not run:
|
||||||
|
raise NotFoundError('run_not_found')
|
||||||
|
if not run.excel_file_data:
|
||||||
|
raise NotFoundError('excel_not_found')
|
||||||
|
return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/workspace/schedule.py
|
||||||
|
|
||||||
|
用途:工作台排程运行记录查询 API。
|
||||||
|
依赖:app.core.auth.jwt、app.core.errors、schedule.query_service。
|
||||||
|
逻辑:鉴权后只读查询 ScheduleRun;register_blueprints 经 workspace 包注册。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from flask import Blueprint, jsonify, request, send_file
|
||||||
|
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||||
|
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
||||||
|
|
||||||
|
workspace_schedule_bp = Blueprint("workspace_schedule", __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_user():
|
||||||
|
"""校验当前用户;未登录时抛出 UnauthorizedError。"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_schedule_bp.route("/schedule-runs", methods=["GET"])
|
||||||
|
def workspace_schedule_runs():
|
||||||
|
user = _require_user()
|
||||||
|
status = str(request.args.get("status") or "").strip() or None
|
||||||
|
schedule_name = str(request.args.get("schedule_name") or "").strip() or None
|
||||||
|
started_after_str = request.args.get("started_after")
|
||||||
|
started_before_str = request.args.get("started_before")
|
||||||
|
started_after = datetime.fromisoformat(started_after_str.replace("Z", "+00:00")) if started_after_str else None
|
||||||
|
started_before = datetime.fromisoformat(started_before_str.replace("Z", "+00:00")) if started_before_str else None
|
||||||
|
limit = int(request.args.get("limit") or 100)
|
||||||
|
return jsonify(
|
||||||
|
list_runs(
|
||||||
|
notify_user_id=user.id,
|
||||||
|
schedule_name=schedule_name,
|
||||||
|
status=status,
|
||||||
|
started_after=started_after,
|
||||||
|
started_before=started_before,
|
||||||
|
limit=limit,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>", methods=["GET"])
|
||||||
|
def workspace_schedule_run_detail(run_id: int):
|
||||||
|
user = _require_user()
|
||||||
|
run = get_run(run_id)
|
||||||
|
if not run:
|
||||||
|
raise NotFoundError("Not found")
|
||||||
|
if not can_view_run(run, user.id):
|
||||||
|
raise ForbiddenError("Forbidden")
|
||||||
|
return jsonify(serialize_run(run))
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_schedule_bp.route("/schedule-runs/<int:run_id>/excel", methods=["GET"])
|
||||||
|
def workspace_schedule_run_excel(run_id: int):
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
user = _require_user()
|
||||||
|
run = get_run(run_id)
|
||||||
|
if not run:
|
||||||
|
raise NotFoundError("Not found")
|
||||||
|
if not can_view_run(run, user.id):
|
||||||
|
raise ForbiddenError("Forbidden")
|
||||||
|
if not run.excel_file_data:
|
||||||
|
raise NotFoundError("Excel not found")
|
||||||
|
buf = BytesIO(run.excel_file_data)
|
||||||
|
return send_file(
|
||||||
|
buf,
|
||||||
|
as_attachment=True,
|
||||||
|
download_name=run.excel_file_name or "result.xlsx",
|
||||||
|
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
|
)
|
||||||
@@ -0,0 +1,741 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/workspace/shipping_notice.py
|
||||||
|
|
||||||
|
用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。
|
||||||
|
依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload / ui_state。
|
||||||
|
逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from flask import Blueprint, g, jsonify, request, send_file
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.auth.jwt import get_current_user
|
||||||
|
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||||
|
from app.core.response import ok
|
||||||
|
from app.models import ShippingBatch, ShippingTask
|
||||||
|
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||||
|
from app.services.shipping_notice.constants import (
|
||||||
|
AUTO_CHAIN_FALLBACK,
|
||||||
|
CP_EXPORT_GENERATED,
|
||||||
|
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||||
|
MAP_JSON,
|
||||||
|
)
|
||||||
|
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||||
|
from app.services.shipping_notice.query_service import (
|
||||||
|
EXPORT_MIME_TYPE,
|
||||||
|
get_batch_for_user,
|
||||||
|
get_conversation_batch_workspace,
|
||||||
|
get_focus_task_for_batch,
|
||||||
|
get_task_for_user,
|
||||||
|
list_batches_for_user,
|
||||||
|
list_tasks_for_batch,
|
||||||
|
list_tasks_for_user,
|
||||||
|
resolve_task_export_download,
|
||||||
|
serialize_batch_summary,
|
||||||
|
serialize_task_detail,
|
||||||
|
serialize_task_summary,
|
||||||
|
task_export_error_message,
|
||||||
|
)
|
||||||
|
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||||
|
|
||||||
|
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||||
|
|
||||||
|
|
||||||
|
def _require_user():
|
||||||
|
"""
|
||||||
|
校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。
|
||||||
|
Returns:
|
||||||
|
User 模型实例。
|
||||||
|
Raises:
|
||||||
|
UnauthorizedError: 无有效 JWT 或 legacy header。
|
||||||
|
"""
|
||||||
|
user = get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _ok(payload: dict):
|
||||||
|
"""返回带 request_id 的成功 envelope,供工作台读接口复用。"""
|
||||||
|
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||||
|
def workspace_shipping_tasks():
|
||||||
|
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||||
|
user = _require_user()
|
||||||
|
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||||
|
process_status = str(request.args.get('process_status') or '').strip() or None
|
||||||
|
limit = int(request.args.get('limit') or 100)
|
||||||
|
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
|
||||||
|
def workspace_shipping_batches():
|
||||||
|
"""列出当前用户的发货批次摘要。"""
|
||||||
|
user = _require_user()
|
||||||
|
limit = int(request.args.get('limit') or 100)
|
||||||
|
return jsonify(list_batches_for_user(user.id, limit=limit))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||||
|
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||||
|
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||||
|
user = _require_user()
|
||||||
|
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||||
|
def workspace_create_shipping_batch_from_notices():
|
||||||
|
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
|
||||||
|
user = _require_user()
|
||||||
|
uploads = request.files.getlist('files')
|
||||||
|
if not uploads:
|
||||||
|
single = request.files.get('file')
|
||||||
|
if single:
|
||||||
|
uploads = [single]
|
||||||
|
if not uploads:
|
||||||
|
raise ValidationError('files is required')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
from app.services.shipping_notice.batch_from_notices import (
|
||||||
|
create_shipping_batch_from_notice_items,
|
||||||
|
intake_notice_uploads_for_batch,
|
||||||
|
)
|
||||||
|
from app.services.shipping_notice.batch_create_idempotency import (
|
||||||
|
normalize_create_idempotency_key,
|
||||||
|
warn_missing_create_idempotency_key,
|
||||||
|
)
|
||||||
|
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||||
|
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||||
|
idempotency_key = normalize_create_idempotency_key(
|
||||||
|
request.headers.get('Idempotency-Key') or request.form.get('idempotency_key')
|
||||||
|
)
|
||||||
|
if not idempotency_key:
|
||||||
|
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_notices')
|
||||||
|
temp_request_id = str(getattr(g, 'request_id', None) or uuid.uuid4().hex)
|
||||||
|
try:
|
||||||
|
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||||
|
finally:
|
||||||
|
cleanup_temp_notice_uploads(temp_request_id)
|
||||||
|
|
||||||
|
created = create_shipping_batch_from_notice_items(
|
||||||
|
user_id=user.id,
|
||||||
|
conversation_id=conversation_id or None,
|
||||||
|
notice_items=notice_items,
|
||||||
|
file_summary=file_summary,
|
||||||
|
create_idempotency_key=idempotency_key,
|
||||||
|
)
|
||||||
|
return _ok(created)
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
|
||||||
|
def workspace_shipping_batch_detail(batch_no: str):
|
||||||
|
"""
|
||||||
|
返回批次详情与聚合 UI State。
|
||||||
|
|
||||||
|
核心逻辑:工作台详情页与独立 `/ui-state` 端点共享同一份批次状态构建结果,
|
||||||
|
避免批次摘要、焦点任务和任务卡片在不同接口里各自推导造成漂移。
|
||||||
|
"""
|
||||||
|
user = _require_user()
|
||||||
|
batch = get_batch_for_user(batch_no, user.id)
|
||||||
|
if not batch:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
return _ok(build_batch_ui_state(batch))
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
|
||||||
|
def workspace_shipping_batch_ui_state(batch_no: str):
|
||||||
|
"""
|
||||||
|
返回批次级 UI State。
|
||||||
|
|
||||||
|
核心逻辑:供右侧工作台、步骤条与批次任务卡统一读取同源状态,
|
||||||
|
保持与批次详情接口返回的 `focus_task_ui_state/tasks[].ui_state` 完全一致。
|
||||||
|
"""
|
||||||
|
user = _require_user()
|
||||||
|
batch = get_batch_for_user(batch_no, user.id)
|
||||||
|
if not batch:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
return _ok(build_batch_ui_state(batch))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
|
||||||
|
def workspace_shipping_batch_tasks(batch_no: str):
|
||||||
|
"""返回指定批次下的任务列表。"""
|
||||||
|
user = _require_user()
|
||||||
|
batch = get_batch_for_user(batch_no, user.id)
|
||||||
|
if not batch:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
return jsonify(list_tasks_for_batch(batch_no, user.id))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||||
|
def workspace_shipping_batch_focus_task(batch_no: str):
|
||||||
|
"""返回指定批次当前焦点任务的摘要。"""
|
||||||
|
user = _require_user()
|
||||||
|
batch = get_batch_for_user(batch_no, user.id)
|
||||||
|
if not batch:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
focus_task = get_focus_task_for_batch(batch_no, user.id)
|
||||||
|
if not focus_task:
|
||||||
|
raise NotFoundError('Focus task not found')
|
||||||
|
return jsonify(serialize_task_summary(focus_task))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
|
||||||
|
def workspace_switch_shipping_batch_focus_task(batch_no: str):
|
||||||
|
"""切换批次当前焦点任务,供工作台在同批次任务间跳转。"""
|
||||||
|
user = _require_user()
|
||||||
|
batch = get_batch_for_user(batch_no, user.id)
|
||||||
|
if not batch:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip()
|
||||||
|
comment = str(data.get('comment') or '').strip()
|
||||||
|
if not task_no:
|
||||||
|
raise ValidationError('task_no is required')
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task or task.batch_id != batch.id:
|
||||||
|
raise NotFoundError('Task not found in batch')
|
||||||
|
switch_batch_focus(
|
||||||
|
batch,
|
||||||
|
task,
|
||||||
|
source='workspace_api',
|
||||||
|
comment=comment or None,
|
||||||
|
extra={'actor_user_id': user.id},
|
||||||
|
)
|
||||||
|
db.session.commit()
|
||||||
|
return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)})
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST'])
|
||||||
|
def workspace_create_shipping_task():
|
||||||
|
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
|
||||||
|
user = _require_user()
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
payload = {'user_id': user.id}
|
||||||
|
source_type = str(data.get('source_type') or '').strip()
|
||||||
|
if source_type:
|
||||||
|
payload['source_type'] = source_type
|
||||||
|
conversation_id = str(data.get('conversation_id') or '').strip()
|
||||||
|
if conversation_id:
|
||||||
|
payload['conversation_id'] = conversation_id
|
||||||
|
raw_content = str(data.get('raw_content') or '').strip()
|
||||||
|
if raw_content:
|
||||||
|
payload['raw_content'] = raw_content
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
return jsonify(shipping_tools.create_task(payload))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||||
|
def workspace_create_shipping_task_from_notice():
|
||||||
|
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||||
|
user = _require_user()
|
||||||
|
upload = request.files.get('file')
|
||||||
|
if not upload:
|
||||||
|
raise ValidationError('file is required')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
from app.services.shipping_notice.notice_upload import guess_source_type, intake_notice_attachment, notice_source_file_type
|
||||||
|
filename = upload.filename or 'notice'
|
||||||
|
raw = upload.read() or b''
|
||||||
|
source_file_type = notice_source_file_type(upload)
|
||||||
|
source_type = guess_source_type(filename)
|
||||||
|
conversation_id = str(request.form.get('conversation_id') or '').strip()
|
||||||
|
payload = {'user_id': user.id, 'source_type': source_type}
|
||||||
|
if conversation_id:
|
||||||
|
payload['conversation_id'] = conversation_id
|
||||||
|
created = shipping_tools.create_task(payload)
|
||||||
|
task_id = str(created.get('task_id') or '').strip()
|
||||||
|
if not task_id:
|
||||||
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500)
|
||||||
|
intake = intake_notice_attachment(
|
||||||
|
filename=filename,
|
||||||
|
raw=raw,
|
||||||
|
source_file_type=source_file_type,
|
||||||
|
storage='task',
|
||||||
|
task_no=task_id,
|
||||||
|
)
|
||||||
|
if not intake.accepted:
|
||||||
|
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
|
||||||
|
return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)})
|
||||||
|
task = ShippingTask.query.filter_by(task_no=task_id).first()
|
||||||
|
if task:
|
||||||
|
task.raw_content = intake.text
|
||||||
|
task.source_file_name = intake.filename or task.source_file_name
|
||||||
|
task.source_file_type = intake.source_file_type or task.source_file_type
|
||||||
|
db.session.commit()
|
||||||
|
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
|
||||||
|
orchestrator_started = start_task_orchestrator(task_id)
|
||||||
|
return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
|
||||||
|
def workspace_replace_shipping_task_notice(task_no: str):
|
||||||
|
"""重新上传发货通知并覆盖当前任务,不新建批次/任务。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
upload = request.files.get('file')
|
||||||
|
if not upload:
|
||||||
|
raise ValidationError('file is required')
|
||||||
|
from app.services.shipping_notice import task_workflow
|
||||||
|
from app.services.shipping_notice.notice_upload import intake_notice_attachment, notice_source_file_type
|
||||||
|
intake = intake_notice_attachment(
|
||||||
|
filename=upload.filename or 'notice',
|
||||||
|
raw=upload.read() or b'',
|
||||||
|
source_file_type=notice_source_file_type(upload),
|
||||||
|
storage='task',
|
||||||
|
task_no=task.task_no,
|
||||||
|
)
|
||||||
|
task.source_type = intake.source_type or task.source_type
|
||||||
|
result = task_workflow.replace_task_notice(
|
||||||
|
task,
|
||||||
|
raw_text=intake.text,
|
||||||
|
source_file_name=intake.filename,
|
||||||
|
source_file_type=intake.source_file_type,
|
||||||
|
warnings=list(intake.warnings),
|
||||||
|
)
|
||||||
|
data = result.setdefault('data', {})
|
||||||
|
if isinstance(data, dict):
|
||||||
|
data['notice_upload'] = intake.to_notice_upload_meta()
|
||||||
|
return _ok(result)
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>', methods=['GET'])
|
||||||
|
def workspace_shipping_task_detail(task_no: str):
|
||||||
|
"""
|
||||||
|
返回指定任务的详情快照与内嵌 UI State。
|
||||||
|
|
||||||
|
核心逻辑:详情接口直接内嵌 `ui_state`,让页面首屏读取任务详情时即可拿到
|
||||||
|
checkpoint / action_buttons / steps,减少前端二次推导与竞态刷新。
|
||||||
|
"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
return _ok({
|
||||||
|
**serialize_task_detail(task),
|
||||||
|
'ui_state': build_task_ui_state(task),
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
|
||||||
|
def workspace_shipping_task_ui_state(task_no: str):
|
||||||
|
"""
|
||||||
|
返回单票任务 UI State。
|
||||||
|
|
||||||
|
核心逻辑:Chat 顶部步骤条、动作按钮和工作台详情统一复用这里的状态机投影,
|
||||||
|
避免不同前端入口重复拼装按钮集合。
|
||||||
|
"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
return _ok(build_task_ui_state(task))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
|
||||||
|
def workspace_shipping_task_chat_actions(task_no: str):
|
||||||
|
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
return jsonify(build_chat_actions_payload(task))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
|
||||||
|
def workspace_retry_shipping_task(task_no: str):
|
||||||
|
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
payload = {'task_id': task.task_no}
|
||||||
|
comment = str(data.get('comment') or '').strip()
|
||||||
|
if comment:
|
||||||
|
payload['comment'] = comment
|
||||||
|
return jsonify(shipping_tools.retry_task(payload))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
|
||||||
|
def workspace_upload_shipping_inventory(task_no: str):
|
||||||
|
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
upload = request.files.get('file')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||||
|
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||||
|
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
source_code = str(data.get('source_code') or '').strip()
|
||||||
|
if not source_code:
|
||||||
|
raise ValidationError('source_code is required')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
return jsonify(shipping_tools.confirm_inventory_source({
|
||||||
|
'task_id': task.task_no,
|
||||||
|
'source_code': source_code,
|
||||||
|
'_trusted_user_id': user.id,
|
||||||
|
}))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
|
||||||
|
def workspace_apply_inventory_mapping(task_no: str):
|
||||||
|
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
map_json = data.get(MAP_JSON)
|
||||||
|
if not isinstance(map_json, dict) or not map_json:
|
||||||
|
raise ValidationError(f'{MAP_JSON} is required')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||||
|
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
|
||||||
|
def workspace_submit_shipping_decision(task_no: str):
|
||||||
|
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
decision = str(data.get('decision') or '').strip()
|
||||||
|
if not decision:
|
||||||
|
raise ValidationError('decision is required')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True, 'event_source': 'workspace_api'}
|
||||||
|
comment = str(data.get('comment') or '').strip()
|
||||||
|
if comment:
|
||||||
|
payload['comment'] = comment
|
||||||
|
return jsonify(shipping_tools.submit_decision(payload))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
|
||||||
|
def workspace_update_shipping_notice_fields(task_no: str):
|
||||||
|
"""更新发货通知单头字段。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
fields = data.get('fields')
|
||||||
|
if not isinstance(fields, dict) or not fields:
|
||||||
|
raise ValidationError('fields is required')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
payload = {'task_id': task.task_no, 'fields': fields}
|
||||||
|
comment = str(data.get('comment') or '').strip()
|
||||||
|
if comment:
|
||||||
|
payload['comment'] = comment
|
||||||
|
return jsonify(shipping_tools.update_notice_fields(payload))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
|
||||||
|
def workspace_update_shipping_notice_line(task_no: str):
|
||||||
|
"""更新发货通知中的指定订单行。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
try:
|
||||||
|
line_index = int(data.get('line_index'))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValidationError('line_index is required')
|
||||||
|
patch = data.get('patch')
|
||||||
|
if not isinstance(patch, dict) or not patch:
|
||||||
|
raise ValidationError('patch is required')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch}
|
||||||
|
comment = str(data.get('comment') or '').strip()
|
||||||
|
if comment:
|
||||||
|
payload['comment'] = comment
|
||||||
|
return jsonify(shipping_tools.update_notice_line(payload))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/add-notice-line', methods=['POST'])
|
||||||
|
def workspace_add_shipping_notice_line(task_no: str):
|
||||||
|
"""为发货通知新增订单行。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
line = data.get('line')
|
||||||
|
if not isinstance(line, dict) or not line:
|
||||||
|
raise ValidationError('line is required')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
payload = {'task_id': task.task_no, 'line': line}
|
||||||
|
comment = str(data.get('comment') or '').strip()
|
||||||
|
if comment:
|
||||||
|
payload['comment'] = comment
|
||||||
|
return jsonify(shipping_tools.add_notice_line(payload))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/remove-notice-line', methods=['POST'])
|
||||||
|
def workspace_remove_shipping_notice_line(task_no: str):
|
||||||
|
"""删除发货通知中的指定订单行。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
try:
|
||||||
|
line_index = int(data.get('line_index'))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise ValidationError('line_index is required')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
payload = {'task_id': task.task_no, 'line_index': line_index}
|
||||||
|
comment = str(data.get('comment') or '').strip()
|
||||||
|
if comment:
|
||||||
|
payload['comment'] = comment
|
||||||
|
return jsonify(shipping_tools.remove_notice_line(payload))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/auto-progress', methods=['POST'])
|
||||||
|
def workspace_auto_progress_shipping_task(task_no: str):
|
||||||
|
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
payload: dict = {'task_id': task.task_no}
|
||||||
|
for key in ('lang', 'locale', 'language'):
|
||||||
|
if data.get(key):
|
||||||
|
payload[key] = data[key]
|
||||||
|
break
|
||||||
|
result = shipping_tools.auto_progress(payload)
|
||||||
|
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||||
|
gen_data = result.get('data')
|
||||||
|
if isinstance(gen_data, dict) and gen_data.get('export_file_path'):
|
||||||
|
gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}
|
||||||
|
result = {**result, 'data': gen_data}
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/match-inventory', methods=['POST'])
|
||||||
|
def workspace_match_shipping_inventory(task_no: str):
|
||||||
|
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint
|
||||||
|
matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True})
|
||||||
|
if not isinstance(matched, dict):
|
||||||
|
return jsonify(matched)
|
||||||
|
data = matched.get('data')
|
||||||
|
if isinstance(data, dict) and data.get('export_file_path'):
|
||||||
|
matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}}
|
||||||
|
checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED
|
||||||
|
if matched.get('status') == 'ok' and data and data.get('export_file_path'):
|
||||||
|
matched['checkpoint'] = checkpoint
|
||||||
|
if 'human_options' not in matched:
|
||||||
|
options = human_options_for_checkpoint(checkpoint)
|
||||||
|
if options is not None:
|
||||||
|
matched['human_options'] = options
|
||||||
|
if 'action_buttons' not in matched:
|
||||||
|
buttons = action_buttons_for_checkpoint(checkpoint)
|
||||||
|
if buttons:
|
||||||
|
matched['action_buttons'] = buttons
|
||||||
|
return jsonify(matched)
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||||
|
def workspace_mark_manual_uploaded(task_no: str):
|
||||||
|
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'}))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry-upload', methods=['POST'])
|
||||||
|
def workspace_retry_shipping_upload(task_no: str):
|
||||||
|
"""用户态重试上传货代系统,直接触发既有 RPA 上传链路。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'}))
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/generate-excel', methods=['POST'])
|
||||||
|
def workspace_generate_shipping_excel(task_no: str):
|
||||||
|
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
if not task:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.shipping_notice import tools as shipping_tools
|
||||||
|
result = shipping_tools.generate_excel({'task_id': task.task_no})
|
||||||
|
if isinstance(result, dict) and result.get('status') == 'ok':
|
||||||
|
data = result.get('data')
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
data = {}
|
||||||
|
result['data'] = data
|
||||||
|
data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export'
|
||||||
|
return jsonify(result)
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||||
|
def workspace_shipping_task_export(task_no: str):
|
||||||
|
"""下载当前用户可访问任务的出货 Excel。"""
|
||||||
|
user = _require_user()
|
||||||
|
task = get_task_for_user(task_no, user.id)
|
||||||
|
err_msg = task_export_error_message(task)
|
||||||
|
if err_msg:
|
||||||
|
raise NotFoundError(err_msg)
|
||||||
|
resolved = resolve_task_export_download(task)
|
||||||
|
assert resolved is not None
|
||||||
|
path, download_name = resolved
|
||||||
|
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['GET'])
|
||||||
|
def workspace_list_shipping_notice_intakes():
|
||||||
|
"""列出当前会话下未消费的活跃接入记录。"""
|
||||||
|
user = _require_user()
|
||||||
|
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||||
|
status = str(request.args.get('status') or '').strip().lower()
|
||||||
|
from app.services.shipping_notice.intake_service import list_active_intakes_for_conversation
|
||||||
|
|
||||||
|
if status and status != 'active':
|
||||||
|
return _ok({'items': []})
|
||||||
|
items = list_active_intakes_for_conversation(user_id=user.id, conversation_id=conversation_id)
|
||||||
|
return _ok({'items': items})
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||||
|
def workspace_create_shipping_notice_intake():
|
||||||
|
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
|
||||||
|
user = _require_user()
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
asset_no = str(body.get('asset_no') or '').strip()
|
||||||
|
if not asset_no:
|
||||||
|
raise ValidationError('asset_no is required')
|
||||||
|
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||||
|
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||||
|
|
||||||
|
data = create_shipping_notice_intake(
|
||||||
|
user_id=user.id,
|
||||||
|
asset_no=asset_no,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
)
|
||||||
|
return ok(data, request_id=getattr(g, 'request_id', None), status=202)
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['GET'])
|
||||||
|
def workspace_get_shipping_notice_intake(intake_no: str):
|
||||||
|
"""查询单个接入记录。"""
|
||||||
|
user = _require_user()
|
||||||
|
from app.services.shipping_notice.intake_service import get_intake_detail
|
||||||
|
|
||||||
|
return _ok(get_intake_detail(user_id=user.id, intake_no=intake_no))
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/status', methods=['POST'])
|
||||||
|
def workspace_shipping_notice_intake_statuses():
|
||||||
|
"""批量查询接入状态。"""
|
||||||
|
user = _require_user()
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
intake_nos = body.get('intake_nos')
|
||||||
|
if not isinstance(intake_nos, list):
|
||||||
|
raise ValidationError('intake_nos is required')
|
||||||
|
from app.services.shipping_notice.intake_service import get_intake_statuses
|
||||||
|
|
||||||
|
return _ok({'items': get_intake_statuses(user_id=user.id, intake_nos=intake_nos)})
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>/retry', methods=['POST'])
|
||||||
|
def workspace_retry_shipping_notice_intake(intake_no: str):
|
||||||
|
"""重试失败的预解析。"""
|
||||||
|
user = _require_user()
|
||||||
|
from app.services.shipping_notice.intake_service import retry_intake_parse
|
||||||
|
|
||||||
|
return _ok(retry_intake_parse(user_id=user.id, intake_no=intake_no))
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-notice/intakes/<intake_no>', methods=['DELETE'])
|
||||||
|
def workspace_cancel_shipping_notice_intake(intake_no: str):
|
||||||
|
"""取消未消费接入记录。"""
|
||||||
|
user = _require_user()
|
||||||
|
from app.services.shipping_notice.intake_service import cancel_intake
|
||||||
|
|
||||||
|
cancel_intake(user_id=user.id, intake_no=intake_no)
|
||||||
|
return _ok({'cancelled': True})
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route(
|
||||||
|
'/shipping-notice/intakes/<intake_no>/duplicate-resolution',
|
||||||
|
methods=['POST'],
|
||||||
|
)
|
||||||
|
def workspace_resolve_shipping_notice_duplicate(intake_no: str):
|
||||||
|
"""保存发货通知重复检测决策。"""
|
||||||
|
user = _require_user()
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
action = str(body.get('action') or '').strip()
|
||||||
|
target_task_no = str(body.get('target_task_no') or '').strip() or None
|
||||||
|
reason = str(body.get('reason') or '').strip() or None
|
||||||
|
from app.services.shipping_notice.intake_service import resolve_intake_duplicate
|
||||||
|
|
||||||
|
return _ok(
|
||||||
|
resolve_intake_duplicate(
|
||||||
|
user_id=user.id,
|
||||||
|
intake_no=intake_no,
|
||||||
|
action=action,
|
||||||
|
target_task_no=target_task_no,
|
||||||
|
reason=reason,
|
||||||
|
actor=user,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route(
|
||||||
|
'/shipping-notice/intakes/<intake_no>/duplicate-refresh',
|
||||||
|
methods=['POST'],
|
||||||
|
)
|
||||||
|
def workspace_refresh_shipping_notice_duplicate(intake_no: str):
|
||||||
|
"""重新执行重复检测。"""
|
||||||
|
user = _require_user()
|
||||||
|
from app.services.shipping_notice.intake_service import refresh_intake_duplicate_detection
|
||||||
|
|
||||||
|
return _ok(refresh_intake_duplicate_detection(user_id=user.id, intake_no=intake_no))
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
|
||||||
|
def workspace_create_shipping_batch_from_intakes():
|
||||||
|
"""从已解析接入记录确认建批。"""
|
||||||
|
user = _require_user()
|
||||||
|
body = request.get_json(silent=True) or {}
|
||||||
|
intake_nos = body.get('intake_nos')
|
||||||
|
if not isinstance(intake_nos, list) or not intake_nos:
|
||||||
|
raise ValidationError('intake_nos is required')
|
||||||
|
conversation_id = str(body.get('conversation_id') or '').strip() or None
|
||||||
|
from app.services.shipping_notice.batch_create_idempotency import (
|
||||||
|
normalize_create_idempotency_key,
|
||||||
|
warn_missing_create_idempotency_key,
|
||||||
|
)
|
||||||
|
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||||
|
|
||||||
|
idempotency_key = normalize_create_idempotency_key(
|
||||||
|
request.headers.get('Idempotency-Key') or body.get('idempotency_key')
|
||||||
|
)
|
||||||
|
if not idempotency_key:
|
||||||
|
warn_missing_create_idempotency_key(source='workspace_create_shipping_batch_from_intakes')
|
||||||
|
result = create_shipping_batch_from_intakes(
|
||||||
|
user_id=user.id,
|
||||||
|
conversation_id=conversation_id,
|
||||||
|
intake_nos=[str(item) for item in intake_nos],
|
||||||
|
create_idempotency_key=idempotency_key,
|
||||||
|
)
|
||||||
|
return _ok(result)
|
||||||
|
|
||||||
|
|
||||||
|
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
|
||||||
|
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||||
|
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
|
||||||
|
user = _require_user()
|
||||||
|
batch = get_batch_for_user(batch_no, user.id)
|
||||||
|
if not batch:
|
||||||
|
raise NotFoundError('Not found')
|
||||||
|
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
|
||||||
|
return jsonify(retry_batch_pending_tasks(batch.batch_no))
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/workspace_file_check.py
|
||||||
|
|
||||||
|
用途:工作台文件检核 API 兼容 shim(Wave 1 迁包)。
|
||||||
|
依赖:app.api.workspace.file_check。
|
||||||
|
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||||
|
"""
|
||||||
|
from app.api.workspace.file_check import (
|
||||||
|
serialize_current_step,
|
||||||
|
serialize_file_judgement,
|
||||||
|
workspace_file_check_bp,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
'serialize_current_step',
|
||||||
|
'serialize_file_judgement',
|
||||||
|
'workspace_file_check_bp',
|
||||||
|
]
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/workspace_schedule.py
|
||||||
|
|
||||||
|
用途:工作台排程 API 兼容 shim(Wave 1 迁包)。
|
||||||
|
依赖:app.api.workspace.schedule。
|
||||||
|
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
|
||||||
|
"""
|
||||||
|
from app.api.workspace.schedule import workspace_schedule_bp
|
||||||
|
|
||||||
|
__all__ = ['workspace_schedule_bp']
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
backend/app/api/workspace_shipping_notice.py
|
||||||
|
|
||||||
|
用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。
|
||||||
|
依赖:app.api.workspace.shipping_notice。
|
||||||
|
逻辑:旧 import 路径继续 re-export `workspace_shipping_notice_bp`;真实实现统一维护在 workspace 子包中,避免双份路由漂移。
|
||||||
|
"""
|
||||||
|
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
|
||||||
|
|
||||||
|
__all__ = ['workspace_shipping_notice_bp']
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
"""
|
||||||
|
backend/app/core/__init__.py
|
||||||
|
|
||||||
|
用途:横切能力包入口(errors、response、auth、config、decorators)。
|
||||||
|
逻辑:业务代码 from app.core.errors / app.core.auth.jwt 等子模块 import。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from app.core.errors import AppError # noqa: F401
|
||||||
|
|
||||||
|
__all__ = ['AppError']
|
||||||
@@ -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,314 @@
|
|||||||
|
"""
|
||||||
|
backend/app/core/auth/jwt.py
|
||||||
|
|
||||||
|
用途:Casdoor JWT 校验、legacy header 回退与当前用户解析。
|
||||||
|
依赖:app.extensions.db、app.models.User、PyJWT、requests。
|
||||||
|
逻辑:api 层与 decorators 调用 get_current_user()。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
import jwt
|
||||||
|
import requests
|
||||||
|
from flask import current_app, g, request
|
||||||
|
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||||
|
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models import User
|
||||||
|
|
||||||
|
_JWKS_CACHE: dict[str, Any] = {
|
||||||
|
'url': None,
|
||||||
|
'keys': None,
|
||||||
|
'expires_at': 0.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _token_brief(token: Optional[str]) -> str:
|
||||||
|
if not token:
|
||||||
|
return 'empty'
|
||||||
|
text = str(token)
|
||||||
|
if len(text) <= 16:
|
||||||
|
return f'len={len(text)}:{text}'
|
||||||
|
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_bearer_token() -> Optional[str]:
|
||||||
|
auth = request.headers.get('Authorization', '')
|
||||||
|
if not auth:
|
||||||
|
return None
|
||||||
|
parts = auth.split(' ', 1)
|
||||||
|
if len(parts) != 2 or parts[0].lower() != 'bearer':
|
||||||
|
return None
|
||||||
|
token = parts[1].strip()
|
||||||
|
return token or None
|
||||||
|
|
||||||
|
|
||||||
|
def _get_jwks_keys(jwks_url: str) -> dict:
|
||||||
|
now = time.time()
|
||||||
|
if (
|
||||||
|
_JWKS_CACHE.get('url') == jwks_url
|
||||||
|
and isinstance(_JWKS_CACHE.get('keys'), dict)
|
||||||
|
and now < float(_JWKS_CACHE.get('expires_at') or 0.0)
|
||||||
|
):
|
||||||
|
return _JWKS_CACHE['keys']
|
||||||
|
|
||||||
|
resp = requests.get(jwks_url, timeout=5)
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json() or {}
|
||||||
|
keys = {}
|
||||||
|
for item in data.get('keys', []):
|
||||||
|
kid = item.get('kid')
|
||||||
|
if kid:
|
||||||
|
keys[kid] = item
|
||||||
|
if not keys:
|
||||||
|
raise ValueError('No JWKS keys found')
|
||||||
|
|
||||||
|
_JWKS_CACHE['url'] = jwks_url
|
||||||
|
_JWKS_CACHE['keys'] = keys
|
||||||
|
_JWKS_CACHE['expires_at'] = now + 300
|
||||||
|
return keys
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_jwt(token: str) -> dict:
|
||||||
|
issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||||
|
audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||||
|
jwks_url = (current_app.config.get('AUTH_JWT_JWKS_URL') or '').strip()
|
||||||
|
if not issuer or not audience or not jwks_url:
|
||||||
|
raise ValueError('JWT auth is not fully configured')
|
||||||
|
|
||||||
|
header = jwt.get_unverified_header(token)
|
||||||
|
kid = header.get('kid')
|
||||||
|
if not kid:
|
||||||
|
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
|
||||||
|
raise ValueError('JWT header missing kid')
|
||||||
|
secret = current_app.config.get('SECRET_KEY')
|
||||||
|
if not secret:
|
||||||
|
raise ValueError('Local JWT secret is missing')
|
||||||
|
local_issuer = (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend').strip()
|
||||||
|
local_audience = (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend').strip()
|
||||||
|
return jwt.decode(
|
||||||
|
token,
|
||||||
|
key=secret,
|
||||||
|
algorithms=['HS256'],
|
||||||
|
audience=local_audience,
|
||||||
|
issuer=local_issuer,
|
||||||
|
options={'require': ['exp', 'iat']},
|
||||||
|
)
|
||||||
|
|
||||||
|
keys = _get_jwks_keys(jwks_url)
|
||||||
|
jwk = keys.get(kid)
|
||||||
|
if not jwk:
|
||||||
|
_JWKS_CACHE['expires_at'] = 0.0
|
||||||
|
keys = _get_jwks_keys(jwks_url)
|
||||||
|
jwk = keys.get(kid)
|
||||||
|
if not jwk:
|
||||||
|
raise ValueError('No matching JWKS key for token')
|
||||||
|
|
||||||
|
public_key = None
|
||||||
|
pyjwk = getattr(jwt, 'PyJWK', None)
|
||||||
|
if pyjwk and hasattr(pyjwk, 'from_dict'):
|
||||||
|
public_key = pyjwk.from_dict(jwk).key
|
||||||
|
if public_key is None:
|
||||||
|
rsa_alg = getattr(getattr(jwt, 'algorithms', None), 'RSAAlgorithm', None)
|
||||||
|
if rsa_alg and hasattr(rsa_alg, 'from_jwk'):
|
||||||
|
public_key = rsa_alg.from_jwk(json.dumps(jwk))
|
||||||
|
if public_key is None:
|
||||||
|
get_algs = getattr(getattr(jwt, 'algorithms', None), 'get_default_algorithms', None)
|
||||||
|
if callable(get_algs):
|
||||||
|
rs256 = (get_algs() or {}).get('RS256')
|
||||||
|
if rs256 and hasattr(rs256, 'from_jwk'):
|
||||||
|
public_key = rs256.from_jwk(json.dumps(jwk))
|
||||||
|
if public_key is None:
|
||||||
|
raise ValueError('Cannot build RSA public key from JWK; check installed jwt package')
|
||||||
|
|
||||||
|
return jwt.decode(
|
||||||
|
token,
|
||||||
|
key=public_key,
|
||||||
|
algorithms=['RS256', 'RS384', 'RS512'],
|
||||||
|
audience=audience,
|
||||||
|
issuer=issuer,
|
||||||
|
options={'require': ['exp', 'iat']},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_unverified_claims(token: str) -> dict:
|
||||||
|
try:
|
||||||
|
return jwt.decode(
|
||||||
|
token,
|
||||||
|
options={
|
||||||
|
'verify_signature': False,
|
||||||
|
'verify_exp': False,
|
||||||
|
'verify_iat': False,
|
||||||
|
'verify_nbf': False,
|
||||||
|
'verify_aud': False,
|
||||||
|
'verify_iss': False,
|
||||||
|
},
|
||||||
|
) or {}
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||||
|
def _lookup() -> Optional[User]:
|
||||||
|
user_id = claims.get('user_id') or claims.get('id')
|
||||||
|
if user_id is not None:
|
||||||
|
try:
|
||||||
|
user = db.session.get(User, int(user_id))
|
||||||
|
if user:
|
||||||
|
return user
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||||
|
if username:
|
||||||
|
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||||
|
if user:
|
||||||
|
return user
|
||||||
|
|
||||||
|
email = claims.get('email')
|
||||||
|
if email:
|
||||||
|
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||||
|
if user:
|
||||||
|
return user
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
return _lookup()
|
||||||
|
except (OperationalError, DatabaseError) as exc:
|
||||||
|
current_app.logger.warning(
|
||||||
|
'[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s',
|
||||||
|
request.path,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
db.session.rollback()
|
||||||
|
db.session.remove()
|
||||||
|
try:
|
||||||
|
db.engine.dispose()
|
||||||
|
except Exception:
|
||||||
|
current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True)
|
||||||
|
return _lookup()
|
||||||
|
|
||||||
|
|
||||||
|
def _legacy_header_user() -> Optional[User]:
|
||||||
|
def _lookup() -> Optional[User]:
|
||||||
|
user_id = request.headers.get('X-User-Id')
|
||||||
|
if user_id:
|
||||||
|
try:
|
||||||
|
user = db.session.get(User, int(user_id))
|
||||||
|
if user:
|
||||||
|
return user
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
username = request.headers.get('X-Username')
|
||||||
|
if username:
|
||||||
|
return db.session.query(User).filter_by(username=username).first()
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
return _lookup()
|
||||||
|
except (OperationalError, DatabaseError) as exc:
|
||||||
|
current_app.logger.warning(
|
||||||
|
'[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s',
|
||||||
|
request.path,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
db.session.rollback()
|
||||||
|
db.session.remove()
|
||||||
|
try:
|
||||||
|
db.engine.dispose()
|
||||||
|
except Exception:
|
||||||
|
current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True)
|
||||||
|
return _lookup()
|
||||||
|
|
||||||
|
|
||||||
|
def _current_user_cache_key() -> tuple[str, str, str, str]:
|
||||||
|
"""构造当前请求用户缓存键,避免测试或保留上下文场景串用上一条请求的用户缓存。"""
|
||||||
|
return (
|
||||||
|
str(request.headers.get('Authorization') or '').strip(),
|
||||||
|
str(request.headers.get('X-User-Id') or '').strip(),
|
||||||
|
str(request.headers.get('X-Username') or '').strip(),
|
||||||
|
f'{request.method}:{request.path}',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_user() -> Optional[User]:
|
||||||
|
"""
|
||||||
|
解析当前请求用户:优先 JWT Bearer,其次 legacy header(若配置启用)。
|
||||||
|
Returns:
|
||||||
|
User 实例;未认证时返回 None。
|
||||||
|
"""
|
||||||
|
cache_key = _current_user_cache_key()
|
||||||
|
cached = getattr(g, 'current_user', None)
|
||||||
|
cached_key = getattr(g, 'current_user_cache_key', None)
|
||||||
|
if cached is not None and cached_key == cache_key:
|
||||||
|
return cached
|
||||||
|
|
||||||
|
token = _extract_bearer_token()
|
||||||
|
if token:
|
||||||
|
try:
|
||||||
|
claims = _decode_jwt(token)
|
||||||
|
user = _resolve_user_from_claims(claims)
|
||||||
|
except Exception:
|
||||||
|
# Decode metadata is diagnostic-only: do not emit it for successful requests.
|
||||||
|
try:
|
||||||
|
header = jwt.get_unverified_header(token)
|
||||||
|
except Exception:
|
||||||
|
header = {}
|
||||||
|
unverified = _extract_unverified_claims(token)
|
||||||
|
expected_issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
|
||||||
|
expected_audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
|
||||||
|
current_app.logger.error(
|
||||||
|
'[auth_jwt] decode context kid=%s alg=%s token=%s token_iss=%s token_aud=%s '
|
||||||
|
'expected_iss=%s expected_aud=%s path=%s',
|
||||||
|
header.get('kid'),
|
||||||
|
header.get('alg'),
|
||||||
|
_token_brief(token),
|
||||||
|
unverified.get('iss'),
|
||||||
|
unverified.get('aud'),
|
||||||
|
expected_issuer,
|
||||||
|
expected_audience,
|
||||||
|
request.path,
|
||||||
|
)
|
||||||
|
current_app.logger.exception('[auth_jwt] decode failed')
|
||||||
|
user = None
|
||||||
|
claims = None
|
||||||
|
if user:
|
||||||
|
g.jwt_claims = claims
|
||||||
|
g.current_user = user
|
||||||
|
g.current_user_cache_key = cache_key
|
||||||
|
return user
|
||||||
|
|
||||||
|
if bool(current_app.config.get('AUTH_LEGACY_HEADER_ENABLED', True)):
|
||||||
|
user = _legacy_header_user()
|
||||||
|
if user:
|
||||||
|
g.current_user = user
|
||||||
|
g.current_user_cache_key = cache_key
|
||||||
|
return user
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def issue_local_access_token(user: User) -> str:
|
||||||
|
"""签发本地 HS256 JWT(密码登录兼容)。"""
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
exp_hours = int(current_app.config.get('AUTH_LOCAL_JWT_EXPIRES_HOURS') or 12)
|
||||||
|
payload = {
|
||||||
|
'sub': str(user.id),
|
||||||
|
'id': user.id,
|
||||||
|
'user_id': user.id,
|
||||||
|
'username': user.username,
|
||||||
|
'role': user.role,
|
||||||
|
'email': user.email,
|
||||||
|
'iat': int(now.timestamp()),
|
||||||
|
'exp': int((now + timedelta(hours=max(1, exp_hours))).timestamp()),
|
||||||
|
'iss': (current_app.config.get('AUTH_LOCAL_JWT_ISSUER') or 'hxops-backend'),
|
||||||
|
'aud': (current_app.config.get('AUTH_LOCAL_JWT_AUDIENCE') or 'hxops-frontend'),
|
||||||
|
}
|
||||||
|
secret = current_app.config.get('SECRET_KEY')
|
||||||
|
return jwt.encode(payload, secret, algorithm='HS256')
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
"""
|
||||||
|
backend/app/core/config/__init__.py
|
||||||
|
|
||||||
|
用途:配置包入口(settings、env_persistence)。
|
||||||
|
"""
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
"""
|
||||||
|
backend/app/core/config/env_persistence.py
|
||||||
|
|
||||||
|
用途:运行时配置 DB 持久化与 env 镜像(WeCom 等 admin 设置)。
|
||||||
|
依赖:app.extensions.db、app.models.AppSetting。
|
||||||
|
逻辑:before_request 调用 apply_env_settings;persist_env_settings 供 admin 写入。
|
||||||
|
|
||||||
|
Storage strategy:
|
||||||
|
1. Database (app_settings) - canonical
|
||||||
|
2. .env.local (dev only) - secondary mirror
|
||||||
|
3. os.environ - in-process mirror on write
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Iterable
|
||||||
|
|
||||||
|
from dotenv import dotenv_values, set_key
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||||
|
_ROOT_DIR = _BACKEND_DIR.parent
|
||||||
|
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||||
|
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||||
|
# Backward-compatible alias for tests and older callers that still patch/read
|
||||||
|
# the historical backend/.env location directly.
|
||||||
|
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
|
||||||
|
WECOM_BOOL_KEYS = {
|
||||||
|
'WECOM_ENABLED',
|
||||||
|
'WECOM_AUTO_CREATE_USER',
|
||||||
|
'WECOM_MOBILE_NORMALIZE',
|
||||||
|
'WECOM_NOTIFY_ENABLED',
|
||||||
|
'WECOM_FEEDBACK_NOTIFY_ENABLED',
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_env_file_exists() -> bool:
|
||||||
|
try:
|
||||||
|
ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
if not ROOT_ENV_LOCAL_PATH.exists():
|
||||||
|
ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8')
|
||||||
|
return True
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_env_name(raw: str | None) -> str:
|
||||||
|
value = (raw or '').strip().lower()
|
||||||
|
if value in ('dev', 'development', ''):
|
||||||
|
return 'dev'
|
||||||
|
if value in ('test', 'testing'):
|
||||||
|
return 'test'
|
||||||
|
if value in ('prod', 'production'):
|
||||||
|
return 'prod'
|
||||||
|
return 'dev'
|
||||||
|
|
||||||
|
|
||||||
|
def _to_env_string(value: object) -> str:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return 'true' if value else 'false'
|
||||||
|
if value is None:
|
||||||
|
return ''
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_env_value(key: str, value: object) -> object:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
if key in WECOM_BOOL_KEYS:
|
||||||
|
return str(value).strip().lower() == 'true'
|
||||||
|
return str(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _matches_prefixes(key: str, prefixes: Iterable[str]) -> bool:
|
||||||
|
return any(key.startswith(prefix) for prefix in prefixes)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Database read/write (primary store)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _persist_to_db(values: dict[str, str]) -> bool:
|
||||||
|
"""Write key/value pairs into the ``app_settings`` table.
|
||||||
|
|
||||||
|
Returns True if every value was committed, False otherwise. The function
|
||||||
|
is defensive: it must not raise, because settings persistence is also
|
||||||
|
written to ``.env`` and we don't want to fail the API request.
|
||||||
|
"""
|
||||||
|
if not values:
|
||||||
|
return True
|
||||||
|
try:
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models import AppSetting
|
||||||
|
except Exception as exc: # pragma: no cover - import safety net
|
||||||
|
logger.warning('AppSetting model unavailable: %s', exc)
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
for key, value in values.items():
|
||||||
|
existing = db.session.get(AppSetting, key)
|
||||||
|
if existing is None:
|
||||||
|
db.session.add(AppSetting(key=key, value=value))
|
||||||
|
else:
|
||||||
|
existing.value = value
|
||||||
|
db.session.commit()
|
||||||
|
return True
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning('Failed to persist settings to DB: %s', exc)
|
||||||
|
try:
|
||||||
|
db.session.rollback()
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
pass
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||||
|
try:
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models import AppSetting
|
||||||
|
except Exception as exc: # pragma: no cover
|
||||||
|
logger.debug('AppSetting model unavailable for read: %s', exc)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
try:
|
||||||
|
rows = db.session.query(AppSetting).all()
|
||||||
|
except Exception as exc:
|
||||||
|
# Most common case: the migration has not been applied yet on a
|
||||||
|
# freshly-built container. Degrade gracefully to .env-only mode.
|
||||||
|
logger.debug('app_settings table not readable yet: %s', exc)
|
||||||
|
try:
|
||||||
|
db.session.rollback()
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
pass
|
||||||
|
return {}
|
||||||
|
|
||||||
|
result: dict[str, str] = {}
|
||||||
|
for row in rows:
|
||||||
|
if row.key and _matches_prefixes(row.key, prefixes):
|
||||||
|
result[row.key] = row.value if row.value is not None else ''
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# .env read/write (secondary store, best-effort)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||||
|
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||||
|
if env_name != 'dev':
|
||||||
|
return True
|
||||||
|
if not values:
|
||||||
|
return True
|
||||||
|
if not _ensure_env_file_exists():
|
||||||
|
return False
|
||||||
|
ok = True
|
||||||
|
for key, value in values.items():
|
||||||
|
try:
|
||||||
|
set_key(str(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto')
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc)
|
||||||
|
ok = False
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||||
|
merged: dict[str, str] = {}
|
||||||
|
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||||
|
if not env_path.exists():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
loaded = dotenv_values(env_path)
|
||||||
|
except OSError as exc:
|
||||||
|
logger.warning('Cannot read %s: %s', env_path, exc)
|
||||||
|
continue
|
||||||
|
for key, value in loaded.items():
|
||||||
|
if key and _matches_prefixes(key, prefixes):
|
||||||
|
merged[key] = value if value is not None else ''
|
||||||
|
return merged
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Public API
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||||
|
"""Persist settings to the canonical store and mirror to ``os.environ``.
|
||||||
|
|
||||||
|
Order:
|
||||||
|
1. Mirror to ``os.environ`` so the current process picks them up
|
||||||
|
immediately.
|
||||||
|
2. Persist to the database (canonical, survives container rebuilds).
|
||||||
|
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||||
|
without DB access keep working.
|
||||||
|
"""
|
||||||
|
if not values:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
persisted: dict[str, str] = {}
|
||||||
|
for key, value in values.items():
|
||||||
|
env_value = _to_env_string(value)
|
||||||
|
os.environ[key] = env_value
|
||||||
|
persisted[key] = env_value
|
||||||
|
|
||||||
|
db_ok = _persist_to_db(persisted)
|
||||||
|
file_ok = _persist_to_env_file(persisted)
|
||||||
|
|
||||||
|
if not db_ok and not file_ok:
|
||||||
|
logger.error(
|
||||||
|
'Failed to persist settings %s to BOTH database and .env.local mirror. '
|
||||||
|
'Settings will be lost when the process restarts.',
|
||||||
|
list(persisted.keys()),
|
||||||
|
)
|
||||||
|
|
||||||
|
return persisted
|
||||||
|
|
||||||
|
|
||||||
|
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||||
|
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||||
|
|
||||||
|
DB values take priority over env-file values; both are merged so
|
||||||
|
keys that only live in env files (e.g. fresh deploy before any admin
|
||||||
|
edit) are still honored.
|
||||||
|
"""
|
||||||
|
file_values = _load_from_env_file(prefixes)
|
||||||
|
db_values = _load_from_db(prefixes)
|
||||||
|
|
||||||
|
merged: dict[str, str] = {**file_values, **db_values}
|
||||||
|
|
||||||
|
applied: dict[str, object] = {}
|
||||||
|
for key, raw_value in merged.items():
|
||||||
|
parsed = _parse_env_value(key, raw_value)
|
||||||
|
os.environ[key] = _to_env_string(parsed)
|
||||||
|
applied[key] = parsed
|
||||||
|
return applied
|
||||||
@@ -0,0 +1,432 @@
|
|||||||
|
"""
|
||||||
|
backend/app/core/config/settings.py
|
||||||
|
|
||||||
|
用途:Flask Config 类与环境文件加载(dev/test/prod)。
|
||||||
|
依赖:dotenv、app.path_utils。
|
||||||
|
逻辑:create_app 通过 config[config_name] 加载;旧路径 app.config 为兼容 shim。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from dotenv import dotenv_values
|
||||||
|
|
||||||
|
|
||||||
|
_BACKEND_DIR = Path(__file__).resolve().parents[3]
|
||||||
|
_ROOT_DIR = _BACKEND_DIR.parent
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_env_name(raw: str | None) -> str:
|
||||||
|
value = (raw or '').strip().lower()
|
||||||
|
if value in ('dev', 'development', ''):
|
||||||
|
return 'dev'
|
||||||
|
if value in ('test', 'testing'):
|
||||||
|
return 'test'
|
||||||
|
if value in ('prod', 'production'):
|
||||||
|
return 'prod'
|
||||||
|
return 'dev'
|
||||||
|
|
||||||
|
|
||||||
|
def _load_environment_files() -> str:
|
||||||
|
"""Load env files from project root with stable priority.
|
||||||
|
|
||||||
|
Priority (low -> high):
|
||||||
|
1. .env.shared
|
||||||
|
2. .env.<ENV_NAME>
|
||||||
|
3. .env.local (only for dev)
|
||||||
|
4. system environment variables (always highest, never overridden)
|
||||||
|
"""
|
||||||
|
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||||
|
preserved_env = dict(os.environ)
|
||||||
|
merged_values: dict[str, str] = {}
|
||||||
|
|
||||||
|
shared_file = _ROOT_DIR / '.env.shared'
|
||||||
|
if shared_file.exists():
|
||||||
|
merged_values.update({k: v for k, v in dotenv_values(shared_file).items() if v is not None})
|
||||||
|
|
||||||
|
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||||
|
if env_file.exists():
|
||||||
|
merged_values.update({k: v for k, v in dotenv_values(env_file).items() if v is not None})
|
||||||
|
|
||||||
|
if env_name == 'dev':
|
||||||
|
local_file = _ROOT_DIR / '.env.local'
|
||||||
|
if local_file.exists():
|
||||||
|
merged_values.update({k: v for k, v in dotenv_values(local_file).items() if v is not None})
|
||||||
|
|
||||||
|
for key, value in merged_values.items():
|
||||||
|
if key not in preserved_env:
|
||||||
|
os.environ[key] = value
|
||||||
|
return env_name
|
||||||
|
|
||||||
|
|
||||||
|
ACTIVE_ENV_NAME = _load_environment_files()
|
||||||
|
|
||||||
|
|
||||||
|
def _data_path(env_key: str, *parts: str) -> str:
|
||||||
|
from app.path_utils import resolve_backend_relative_path
|
||||||
|
|
||||||
|
default = _BACKEND_DIR.joinpath("data", *parts)
|
||||||
|
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||||
|
|
||||||
|
|
||||||
|
def _backend_path(env_key: str, *parts: str) -> str:
|
||||||
|
from app.path_utils import resolve_backend_relative_path
|
||||||
|
|
||||||
|
default = _BACKEND_DIR.joinpath(*parts)
|
||||||
|
return resolve_backend_relative_path(os.getenv(env_key), default)
|
||||||
|
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||||
|
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||||
|
# 配置最大上传文件大小(200MB)
|
||||||
|
MAX_CONTENT_LENGTH = 200 * 1024 * 1024
|
||||||
|
KB_STORAGE_ROOT = _data_path('KB_STORAGE_ROOT', 'kb')
|
||||||
|
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||||
|
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||||
|
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
|
||||||
|
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
|
||||||
|
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
|
||||||
|
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
|
||||||
|
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
|
||||||
|
# 数据库连接池配置
|
||||||
|
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||||
|
'pool_size': 20,
|
||||||
|
'max_overflow': 10,
|
||||||
|
'pool_recycle': 3600,
|
||||||
|
'pool_pre_ping': True,
|
||||||
|
}
|
||||||
|
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
|
||||||
|
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
|
||||||
|
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
|
||||||
|
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
|
||||||
|
# Dify 网关配置
|
||||||
|
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||||
|
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||||
|
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
|
||||||
|
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
|
||||||
|
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||||
|
REDIS_URL = os.getenv('REDIS_URL')
|
||||||
|
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||||
|
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
|
||||||
|
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
|
||||||
|
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||||
|
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||||
|
'OA_WORKFLOW_WSDL_URL',
|
||||||
|
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||||
|
)
|
||||||
|
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||||
|
|
||||||
|
# External integration API (resolve original source file links by Dify IDs)
|
||||||
|
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||||
|
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||||
|
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||||
|
|
||||||
|
# HXOPS Tool API 对外基地址(文件检核 / 货代等 Dify Chatflow 服务端调用;无尾斜杠,常为内网 IP)
|
||||||
|
HXOPS_TOOLS_API_BASE = os.getenv('HXOPS_TOOLS_API_BASE') or os.getenv('HXOPS_TOOLS_API_BASE')
|
||||||
|
|
||||||
|
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠,应为域名)
|
||||||
|
HXOPS_PUBLIC_BASE_URL = os.getenv('HXOPS_PUBLIC_BASE_URL')
|
||||||
|
|
||||||
|
# 货代发货通知 Agent Tool API
|
||||||
|
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
|
||||||
|
|
||||||
|
# 文件检核 Chatflow Tool API
|
||||||
|
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
|
||||||
|
|
||||||
|
# 设备维保助手 Chatflow Tool API
|
||||||
|
MAINTENANCE_TOOL_API_KEY = os.getenv('MAINTENANCE_TOOL_API_KEY')
|
||||||
|
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
|
||||||
|
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
|
||||||
|
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
|
||||||
|
)
|
||||||
|
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
|
||||||
|
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
|
||||||
|
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||||
|
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||||
|
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||||
|
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
|
||||||
|
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
|
||||||
|
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
|
||||||
|
in {'1', 'true', 'yes', 'on'}
|
||||||
|
if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
|
||||||
|
else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip()
|
||||||
|
SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
|
||||||
|
or '.hxops_rpa_shared_mount'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'true').lower() == 'true'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv(
|
||||||
|
'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', ''
|
||||||
|
).strip()
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
|
||||||
|
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
|
||||||
|
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
|
||||||
|
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
|
||||||
|
'shipment_{task_no}_{ts}.xlsx',
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
|
||||||
|
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
|
||||||
|
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
|
||||||
|
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
|
||||||
|
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path(
|
||||||
|
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.yaml'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
|
||||||
|
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
|
||||||
|
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||||
|
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||||
|
FREIGHT_INVENTORY_DROP_DIR = _data_path(
|
||||||
|
"FREIGHT_INVENTORY_DROP_DIR", "shipping_notice", "freight_rpa", "inventory_drop"
|
||||||
|
)
|
||||||
|
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||||
|
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "shipping_notice", "freight_rpa", "inventory_triggers"
|
||||||
|
)
|
||||||
|
FREIGHT_UPLOAD_QUEUE_DIR = _data_path(
|
||||||
|
"FREIGHT_UPLOAD_QUEUE_DIR", "shipping_notice", "freight_rpa", "upload_queue"
|
||||||
|
)
|
||||||
|
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
|
||||||
|
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers"
|
||||||
|
)
|
||||||
|
FREIGHT_RPA_BROWSER_PROFILE_DIR = _data_path(
|
||||||
|
"FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile"
|
||||||
|
)
|
||||||
|
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _data_path(
|
||||||
|
"FREIGHT_RPA_INVENTORY_ARCHIVE_DIR", "shipping_notice", "freight_rpa", "inventory_archives"
|
||||||
|
)
|
||||||
|
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||||
|
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||||
|
)
|
||||||
|
|
||||||
|
# WeCom (企业微信) 登录配置
|
||||||
|
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||||
|
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||||
|
WECOM_AGENT_ID = os.getenv('WECOM_AGENT_ID')
|
||||||
|
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||||
|
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||||
|
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||||
|
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES')
|
||||||
|
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR').upper()
|
||||||
|
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE')
|
||||||
|
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS')
|
||||||
|
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE')
|
||||||
|
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||||
|
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN')
|
||||||
|
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY')
|
||||||
|
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL')
|
||||||
|
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL')
|
||||||
|
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN')
|
||||||
|
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||||
|
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||||
|
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||||
|
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||||
|
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset')
|
||||||
|
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||||
|
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||||
|
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||||
|
|
||||||
|
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||||
|
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||||
|
AUTH_JWT_REQUIRED = os.getenv('AUTH_JWT_REQUIRED', 'true').lower() == 'true'
|
||||||
|
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN = os.getenv('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', 'true').lower() == 'true'
|
||||||
|
# Login mode switch: "casdoor" (default) or "password".
|
||||||
|
# casdoor: login form credentials are sent to Casdoor token endpoint (no redirect page for users).
|
||||||
|
# password: keep legacy local username/password login.
|
||||||
|
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').strip().lower()
|
||||||
|
AUTH_ALLOW_LOCAL_JWT = os.getenv('AUTH_ALLOW_LOCAL_JWT', 'true').lower() == 'true'
|
||||||
|
# JWT 的签发者(iss)校验值,后端用它确认“这个 token 是谁发的”
|
||||||
|
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
|
||||||
|
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||||
|
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE')
|
||||||
|
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||||
|
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL')
|
||||||
|
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
|
||||||
|
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
|
||||||
|
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
|
||||||
|
# Fallback when authorize-url request omits redirect_uri; OAuth flow sends browser origin + /casdoor-callback.
|
||||||
|
# Casdoor Application must whitelist every origin users hit, e.g. IP and domain on port 8881.
|
||||||
|
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||||
|
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||||
|
# Casdoor organization (userOwner) for set-password and other management APIs.
|
||||||
|
CASDOOR_ORGANIZATION = (os.getenv('CASDOOR_ORGANIZATION') or 'organization_HX').strip()
|
||||||
|
# WeCom as Casdoor IdP: provider Name from Casdoor Providers page (used with default_provider=wecom on authorize-url).
|
||||||
|
CASDOOR_WECOM_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||||
|
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||||
|
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER')
|
||||||
|
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE')
|
||||||
|
AUTH_LOCAL_JWT_EXPIRES_HOURS = int(os.getenv('AUTH_LOCAL_JWT_EXPIRES_HOURS', '12'))
|
||||||
|
SCHEDULE_WORKER_ENABLED = os.getenv('SCHEDULE_WORKER_ENABLED', 'true').lower() == 'true'
|
||||||
|
# Cron 表达式按此时区解读(如 0 12 * * * 表示该时区 12:00);入库 next_run_at 仍为 UTC。
|
||||||
|
SCHEDULE_TIMEZONE = (os.getenv('SCHEDULE_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||||
|
SRM_SQLSERVER_HOST = os.getenv('SRM_SQLSERVER_HOST', '')
|
||||||
|
SRM_SQLSERVER_PORT = os.getenv('SRM_SQLSERVER_PORT', '1433')
|
||||||
|
SRM_SQLSERVER_DATABASE = os.getenv('SRM_SQLSERVER_DATABASE', '')
|
||||||
|
SRM_SQLSERVER_USERNAME = os.getenv('SRM_SQLSERVER_USERNAME', '')
|
||||||
|
SRM_SQLSERVER_PASSWORD = os.getenv('SRM_SQLSERVER_PASSWORD', '')
|
||||||
|
SRM_SQLSERVER_DRIVER = os.getenv('SRM_SQLSERVER_DRIVER', 'SQL Server')
|
||||||
|
SRM_SQLSERVER_ENCRYPT = os.getenv('SRM_SQLSERVER_ENCRYPT', 'no')
|
||||||
|
SRM_SQLSERVER_TRUST_CERT = os.getenv('SRM_SQLSERVER_TRUST_CERT', 'yes')
|
||||||
|
SRM_SQLSERVER_TIMEOUT = int(os.getenv('SRM_SQLSERVER_TIMEOUT', '15'))
|
||||||
|
SMTP_HOST = os.getenv('SMTP_HOST', '')
|
||||||
|
SMTP_PORT = int(os.getenv('SMTP_PORT', '25'))
|
||||||
|
SMTP_USER = os.getenv('SMTP_USER', '')
|
||||||
|
SMTP_PASSWORD = os.getenv('SMTP_PASSWORD', '')
|
||||||
|
SMTP_FROM = os.getenv('SMTP_FROM', '')
|
||||||
|
SMTP_USE_TLS = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
|
||||||
|
INTERNAL_API_BASE_URL = os.getenv('INTERNAL_API_BASE_URL', 'http://127.0.0.1:5052')
|
||||||
|
FIXED_ASSETS_SYNC_ENABLED = os.getenv('FIXED_ASSETS_SYNC_ENABLED', 'true').lower() == 'true'
|
||||||
|
FIXED_ASSETS_SYNC_TIMEZONE = (os.getenv('FIXED_ASSETS_SYNC_TIMEZONE') or 'Asia/Shanghai').strip()
|
||||||
|
FIXED_ASSETS_SYNC_HOUR = int(os.getenv('FIXED_ASSETS_SYNC_HOUR', '3') or '3')
|
||||||
|
FIXED_ASSETS_SYNC_MINUTE = int(os.getenv('FIXED_ASSETS_SYNC_MINUTE', '0') or '0')
|
||||||
|
FIXED_ASSETS_SYNC_TIMEOUT_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_TIMEOUT_SECONDS', '600') or '600')
|
||||||
|
FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES = int(
|
||||||
|
os.getenv('FIXED_ASSETS_SYNC_RETRY_INTERVAL_MINUTES', '30') or '30'
|
||||||
|
)
|
||||||
|
FIXED_ASSETS_SYNC_MAX_ATTEMPTS = int(os.getenv('FIXED_ASSETS_SYNC_MAX_ATTEMPTS', '4') or '4')
|
||||||
|
FIXED_ASSETS_SYNC_POLL_SECONDS = int(os.getenv('FIXED_ASSETS_SYNC_POLL_SECONDS', '60') or '60')
|
||||||
|
FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING = (
|
||||||
|
os.getenv('FIXED_ASSETS_SYNC_ON_BOOT_IF_MISSING', 'true').lower() == 'true'
|
||||||
|
)
|
||||||
|
FIXED_ASSETS_HISTORY_KEEP_COUNT = int(os.getenv('FIXED_ASSETS_HISTORY_KEEP_COUNT', '3') or '3')
|
||||||
|
FIXED_ASSETS_STORAGE_ROOT = _data_path('FIXED_ASSETS_STORAGE_ROOT', 'fixed_assets')
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_ROOT = os.getenv('FIXED_ASSET_HISTORY_SHARE_ROOT', '').strip()
|
||||||
|
FIXED_ASSET_HISTORY_LOCAL_ROOT = os.getenv('FIXED_ASSET_HISTORY_LOCAL_ROOT', '').strip()
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_USERNAME = os.getenv('FIXED_ASSET_HISTORY_SHARE_USERNAME', '').strip()
|
||||||
|
FIXED_ASSET_HISTORY_SHARE_PASSWORD = os.getenv('FIXED_ASSET_HISTORY_SHARE_PASSWORD', '')
|
||||||
|
FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS = int(os.getenv('FIXED_ASSET_HISTORY_SEARCH_MAX_RESULTS', '20') or '20')
|
||||||
|
FIXED_ASSET_IMAGE_BASE_URL = os.getenv('FIXED_ASSET_IMAGE_BASE_URL', '').strip()
|
||||||
|
FIXED_ASSET_IMAGE_USERNAME = os.getenv('FIXED_ASSET_IMAGE_USERNAME', '').strip()
|
||||||
|
FIXED_ASSET_IMAGE_PASSWORD = os.getenv('FIXED_ASSET_IMAGE_PASSWORD', '')
|
||||||
|
FIXED_ASSET_IMAGE_LIBRARY_ID = os.getenv('FIXED_ASSET_IMAGE_LIBRARY_ID', '').strip()
|
||||||
|
FIXED_ASSET_IMAGE_FOLDER_ID = os.getenv('FIXED_ASSET_IMAGE_FOLDER_ID', '').strip()
|
||||||
|
FIXED_ASSETS_DOCS_EXPORT_ROOT = os.getenv(
|
||||||
|
'FIXED_ASSETS_DOCS_EXPORT_ROOT',
|
||||||
|
str(_ROOT_DIR / 'docs'),
|
||||||
|
)
|
||||||
|
FIXED_ASSETS_EXPORT_TO_DOCS = os.getenv('FIXED_ASSETS_EXPORT_TO_DOCS', 'true').lower() == 'true'
|
||||||
|
FIXED_ASSETS_ERP_USERNAME = os.getenv('FIXED_ASSETS_ERP_USERNAME', 'EXT_VIEW_USER')
|
||||||
|
FIXED_ASSETS_ERP_PASSWORD = os.getenv('FIXED_ASSETS_ERP_PASSWORD', 'extviewuser')
|
||||||
|
FIXED_ASSETS_ERP_DSN = os.getenv('FIXED_ASSETS_ERP_DSN') or os.getenv('ERP_DB_DSN', '192.168.8.24:1521/topprod')
|
||||||
|
|
||||||
|
# MinIO 配置
|
||||||
|
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
|
||||||
|
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
|
||||||
|
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
|
||||||
|
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
|
||||||
|
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
|
||||||
|
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
|
||||||
|
MINIO_FILE_ASSETS_BUCKET = os.getenv('MINIO_FILE_ASSETS_BUCKET', 'hxops-file-assets')
|
||||||
|
FILE_ASSET_MAX_SIZE_MB = int(os.getenv('FILE_ASSET_MAX_SIZE_MB', '30'))
|
||||||
|
FILE_ASSET_TEMP_TTL_HOURS = int(os.getenv('FILE_ASSET_TEMP_TTL_HOURS', '72'))
|
||||||
|
FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS = int(os.getenv('FILE_ASSET_DOWNLOAD_URL_TTL_SECONDS', '300'))
|
||||||
|
SHIPPING_NOTICE_INTAKE_TTL_HOURS = int(os.getenv('SHIPPING_NOTICE_INTAKE_TTL_HOURS', '72'))
|
||||||
|
SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_PARSE_MAX_ATTEMPTS', '3'))
|
||||||
|
SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', '300')
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_PARSER_VERSION = os.getenv('SHIPPING_NOTICE_PARSER_VERSION', 'v6')
|
||||||
|
# EML 附件提取安全上限(阶段一对齐:只抽取文本,不执行宏/脚本)
|
||||||
|
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
|
||||||
|
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
|
||||||
|
SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20'))
|
||||||
|
SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024))
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES', str(50 * 1024 * 1024))
|
||||||
|
)
|
||||||
|
SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH = int(os.getenv('SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH', '3'))
|
||||||
|
# EML 全部附件 extracted_text 写入 structured_result_json 的合计字符上限
|
||||||
|
SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS = int(
|
||||||
|
os.getenv('SHIPPING_NOTICE_EML_MAX_STORED_ATTACHMENT_CHARS', str(500_000))
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class DevelopmentConfig(Config):
|
||||||
|
DEBUG = True
|
||||||
|
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||||
|
|
||||||
|
|
||||||
|
class ProductionConfig(Config):
|
||||||
|
DEBUG = False
|
||||||
|
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||||
|
|
||||||
|
|
||||||
|
class TestingConfig(Config):
|
||||||
|
TESTING = True
|
||||||
|
SQLALCHEMY_DATABASE_URI = 'sqlite:///:memory:'
|
||||||
|
WTF_CSRF_ENABLED = False
|
||||||
|
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||||
|
SCHEDULE_WORKER_ENABLED = False
|
||||||
|
FIXED_ASSETS_SYNC_ENABLED = False
|
||||||
|
FIXED_ASSETS_EXPORT_TO_DOCS = False
|
||||||
|
ENV_NAME = 'dev'
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
|
||||||
|
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
|
||||||
|
|
||||||
|
|
||||||
|
config = {
|
||||||
|
'dev': DevelopmentConfig,
|
||||||
|
'development': DevelopmentConfig,
|
||||||
|
'test': TestingConfig,
|
||||||
|
'testing': TestingConfig, # alias for create_app('testing') in pytest
|
||||||
|
'prod': ProductionConfig,
|
||||||
|
'production': ProductionConfig,
|
||||||
|
'default': DevelopmentConfig,
|
||||||
|
}
|
||||||
|
|
||||||
@@ -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,95 @@
|
|||||||
|
"""
|
||||||
|
backend/app/core/decorators.py
|
||||||
|
|
||||||
|
用途:API 路由权限装饰器(admin、agent 权限)。
|
||||||
|
依赖:app.core.auth.jwt、app.core.errors、app.models。
|
||||||
|
逻辑:api 路由使用 @require_admin、@require_agent_permission。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
from flask import current_app, g, request
|
||||||
|
|
||||||
|
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||||
|
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||||
|
from app.models import Agent, User
|
||||||
|
|
||||||
|
|
||||||
|
def _get_current_user() -> User:
|
||||||
|
"""通过 JWT / legacy header 解析当前用户并写入 g.current_user。"""
|
||||||
|
user = _auth_current_user()
|
||||||
|
if user:
|
||||||
|
g.current_user = user
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_request_agent_id() -> str | None:
|
||||||
|
"""
|
||||||
|
从 JSON body、query 或 multipart form 解析 agent_id。
|
||||||
|
|
||||||
|
核心逻辑:Chat Turn 附件上传走 multipart/form-data,agent_id 在 form 字段而非 JSON body。
|
||||||
|
"""
|
||||||
|
data = request.get_json(silent=True) or {}
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
data = {}
|
||||||
|
return (
|
||||||
|
data.get("agent_id")
|
||||||
|
or data.get("agentId")
|
||||||
|
or request.args.get("agent_id")
|
||||||
|
or request.args.get("agentId")
|
||||||
|
or request.form.get("agent_id")
|
||||||
|
or request.form.get("agentId")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def require_agent_permission(f):
|
||||||
|
"""
|
||||||
|
装饰器:校验当前用户是否拥有指定 Agent 访问权限。
|
||||||
|
核心逻辑:从 body/query/form 读 agent_id → 获取用户 → admin 放行或检查 user.agents。
|
||||||
|
Args:
|
||||||
|
f: 被装饰的视图函数。
|
||||||
|
Returns:
|
||||||
|
包装后的视图函数。
|
||||||
|
"""
|
||||||
|
|
||||||
|
@wraps(f)
|
||||||
|
def decorated_function(*args, **kwargs):
|
||||||
|
agent_id = _resolve_request_agent_id()
|
||||||
|
if not agent_id:
|
||||||
|
raise ValidationError('agent_id is required')
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError('Unauthorized')
|
||||||
|
agent = Agent.query.get(agent_id)
|
||||||
|
if not agent:
|
||||||
|
raise NotFoundError('Agent not found')
|
||||||
|
g.current_agent = agent
|
||||||
|
if user.role == 'admin':
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
if agent not in user.agents:
|
||||||
|
raise ForbiddenError('Permission denied for this agent')
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
|
return decorated_function
|
||||||
|
|
||||||
|
|
||||||
|
def require_admin(f):
|
||||||
|
"""
|
||||||
|
装饰器:限制仅 admin 角色可访问。
|
||||||
|
核心逻辑:解析用户 → 校验 role == admin;JWT 必填时检查 Authorization 头。
|
||||||
|
"""
|
||||||
|
|
||||||
|
@wraps(f)
|
||||||
|
def decorated_function(*args, **kwargs):
|
||||||
|
user = _get_current_user()
|
||||||
|
if not user:
|
||||||
|
raise UnauthorizedError('Unauthorized')
|
||||||
|
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||||
|
raise UnauthorizedError('JWT token is required')
|
||||||
|
if user.role != 'admin':
|
||||||
|
raise ForbiddenError('Admin privilege required')
|
||||||
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
|
return decorated_function
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
"""
|
||||||
|
backend/app/core/errors.py
|
||||||
|
|
||||||
|
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||||
|
依赖:无 Flask 依赖。
|
||||||
|
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AppError(Exception):
|
||||||
|
code: str
|
||||||
|
message: str
|
||||||
|
http_status: int = 400
|
||||||
|
details: dict[str, Any] = field(default_factory=dict)
|
||||||
|
retryable: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class ValidationError(AppError):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = "Invalid request parameters",
|
||||||
|
*,
|
||||||
|
code: str = "VALIDATION.INVALID_PARAM",
|
||||||
|
details: dict[str, Any] | None = None,
|
||||||
|
):
|
||||||
|
super().__init__(
|
||||||
|
code=code,
|
||||||
|
message=message,
|
||||||
|
http_status=400,
|
||||||
|
details=details or {},
|
||||||
|
retryable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class UnauthorizedError(AppError):
|
||||||
|
def __init__(self, message: str = "Unauthorized"):
|
||||||
|
super().__init__(code="AUTH.UNAUTHORIZED", message=message, http_status=401, retryable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class ForbiddenError(AppError):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = "Forbidden",
|
||||||
|
*,
|
||||||
|
code: str = "AUTH.FORBIDDEN",
|
||||||
|
):
|
||||||
|
super().__init__(code=code, message=message, http_status=403, retryable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class NotFoundError(AppError):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = "Resource not found",
|
||||||
|
*,
|
||||||
|
code: str = "RESOURCE.NOT_FOUND",
|
||||||
|
):
|
||||||
|
super().__init__(code=code, message=message, http_status=404, retryable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class ConflictError(AppError):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = "Resource conflict",
|
||||||
|
*,
|
||||||
|
code: str = "RESOURCE.CONFLICT",
|
||||||
|
details: dict[str, Any] | None = None,
|
||||||
|
):
|
||||||
|
super().__init__(
|
||||||
|
code=code,
|
||||||
|
message=message,
|
||||||
|
http_status=409,
|
||||||
|
details=details or {},
|
||||||
|
retryable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceUnavailableError(AppError):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = "Service unavailable",
|
||||||
|
*,
|
||||||
|
code: str = "SYSTEM.SERVICE_UNAVAILABLE",
|
||||||
|
details: dict[str, Any] | None = None,
|
||||||
|
):
|
||||||
|
super().__init__(code=code, message=message, http_status=503, details=details or {}, retryable=True)
|
||||||
|
|
||||||
|
|
||||||
|
class AgentHandlerNotConfiguredError(AppError):
|
||||||
|
"""Catalog 声明 runtime_handler 但 HANDLER_REGISTRY 未注册实现。"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = "Agent handler is not configured",
|
||||||
|
*,
|
||||||
|
agent_code: str | None = None,
|
||||||
|
handler_key: str | None = None,
|
||||||
|
runtime_provider: str | None = None,
|
||||||
|
details: dict[str, Any] | None = None,
|
||||||
|
):
|
||||||
|
merged_details = dict(details or {})
|
||||||
|
if agent_code:
|
||||||
|
merged_details.setdefault('agent_code', agent_code)
|
||||||
|
if handler_key:
|
||||||
|
merged_details.setdefault('handler_key', handler_key)
|
||||||
|
if runtime_provider:
|
||||||
|
merged_details.setdefault('runtime_provider', runtime_provider)
|
||||||
|
super().__init__(
|
||||||
|
code='AGENT.HANDLER_NOT_CONFIGURED',
|
||||||
|
message=message,
|
||||||
|
http_status=501,
|
||||||
|
details=merged_details,
|
||||||
|
retryable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def raise_for_status(message: str, status: int, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
|
||||||
|
"""
|
||||||
|
按 HTTP 状态码映射并抛出对应 AppError 子类。
|
||||||
|
Args:
|
||||||
|
message: 错误文案。
|
||||||
|
status: HTTP 状态码。
|
||||||
|
code: 可选业务错误码。
|
||||||
|
details: 可选详情 dict。
|
||||||
|
Raises:
|
||||||
|
AppError 或其子类。
|
||||||
|
"""
|
||||||
|
if status == 401:
|
||||||
|
raise UnauthorizedError(message)
|
||||||
|
if status == 403:
|
||||||
|
raise ForbiddenError(message)
|
||||||
|
if status == 404:
|
||||||
|
raise NotFoundError(message)
|
||||||
|
if status == 409:
|
||||||
|
raise ConflictError(message, code=code or "RESOURCE.CONFLICT", details=details)
|
||||||
|
if status == 503:
|
||||||
|
raise ServiceUnavailableError(message, code=code or "SYSTEM.SERVICE_UNAVAILABLE")
|
||||||
|
if status >= 500:
|
||||||
|
raise AppError(
|
||||||
|
code=code or "SYSTEM.INTERNAL_ERROR",
|
||||||
|
message=message,
|
||||||
|
http_status=status,
|
||||||
|
details=details or {},
|
||||||
|
)
|
||||||
|
raise AppError(
|
||||||
|
code=code or "VALIDATION.INVALID_PARAM",
|
||||||
|
message=message,
|
||||||
|
http_status=status,
|
||||||
|
details=details or {},
|
||||||
|
)
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
"""
|
||||||
|
backend/app/core/response.py
|
||||||
|
|
||||||
|
用途:统一 API 响应结构工具(成功 envelope 与错误 payload)。
|
||||||
|
依赖:flask.jsonify(仅 ok() 使用)。
|
||||||
|
逻辑:create_app 异常 handler 使用 error_payload;可选 ENABLE_API_ENVELOPE 包装成功响应。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from flask import jsonify
|
||||||
|
|
||||||
|
|
||||||
|
def utc_iso_now() -> str:
|
||||||
|
"""返回当前 UTC 时间的 ISO8601 字符串(Z 后缀)。"""
|
||||||
|
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
def utc_iso(dt: datetime | None) -> str | None:
|
||||||
|
"""
|
||||||
|
将 naive UTC datetime 序列化为带 Z 后缀的 ISO 字符串。
|
||||||
|
Args:
|
||||||
|
dt: datetime 或 None。
|
||||||
|
Returns:
|
||||||
|
ISO 字符串或 None。
|
||||||
|
"""
|
||||||
|
if dt is None:
|
||||||
|
return None
|
||||||
|
if dt.tzinfo is not None:
|
||||||
|
return dt.astimezone(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
|
||||||
|
return dt.isoformat() + "Z"
|
||||||
|
|
||||||
|
|
||||||
|
def ok(data: Any, *, request_id: str | None = None, status: int = 200):
|
||||||
|
"""
|
||||||
|
构造 success=true 的标准 JSON 响应。
|
||||||
|
Args:
|
||||||
|
data: 业务数据。
|
||||||
|
request_id: 可选请求追踪 id。
|
||||||
|
status: HTTP 状态码。
|
||||||
|
Returns:
|
||||||
|
(jsonify Response, status) 元组。
|
||||||
|
"""
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"success": True,
|
||||||
|
"data": data,
|
||||||
|
"timestamp": utc_iso_now(),
|
||||||
|
}
|
||||||
|
if request_id:
|
||||||
|
payload["request_id"] = request_id
|
||||||
|
return jsonify(payload), status
|
||||||
|
|
||||||
|
|
||||||
|
def error_payload(
|
||||||
|
*,
|
||||||
|
code: str,
|
||||||
|
message: str,
|
||||||
|
request_id: str | None = None,
|
||||||
|
details: dict[str, Any] | None = None,
|
||||||
|
retryable: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
构造 success=false 的错误响应体 dict(供 jsonify 使用)。
|
||||||
|
Args:
|
||||||
|
code: 业务错误码。
|
||||||
|
message: 用户可见文案。
|
||||||
|
request_id: 可选请求 id。
|
||||||
|
details: 可选详情。
|
||||||
|
retryable: 是否可重试。
|
||||||
|
Returns:
|
||||||
|
可 jsonify 的 dict。
|
||||||
|
"""
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"success": False,
|
||||||
|
"error": {
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
"details": details or {},
|
||||||
|
"retryable": retryable,
|
||||||
|
},
|
||||||
|
"timestamp": utc_iso_now(),
|
||||||
|
}
|
||||||
|
if request_id:
|
||||||
|
payload["request_id"] = request_id
|
||||||
|
return payload
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"""
|
||||||
|
backend/app/extensions.py
|
||||||
|
|
||||||
|
用途:Flask 扩展单例(SQLAlchemy db、Flask-Migrate migrate)的唯一定义处。
|
||||||
|
依赖:flask_sqlalchemy、flask_migrate。
|
||||||
|
逻辑:create_app 调用 db.init_app / migrate.init_app;models 与 services 通过 from app import db 或
|
||||||
|
from app.extensions import db 引用同一实例,避免在 app/__init__.py 与应用工厂混杂定义。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
from flask_migrate import Migrate
|
||||||
|
|
||||||
|
db = SQLAlchemy()
|
||||||
|
migrate = Migrate()
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""
|
||||||
|
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, enqueue_clean_job, enqueue_kb_job
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
'JobType',
|
||||||
|
'JobStatus',
|
||||||
|
'enqueue',
|
||||||
|
'enqueue_kb_job',
|
||||||
|
'enqueue_clean_job',
|
||||||
|
]
|
||||||
@@ -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_parse, shipping_notice_run, wecom_directory_sync # noqa: F401
|
||||||
Loaded 100 of 1313 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user