Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
537e3e18f0 | ||
|
|
2e8405e2f0 | ||
|
|
b2fe9b78e2 | ||
|
|
8336ab6349 | ||
|
|
d64a49548f | ||
|
|
81eeef944f | ||
|
|
60a8b20bf9 | ||
|
|
638a46ad0d | ||
|
|
1b3b63df24 | ||
|
|
eb468d3c78 | ||
|
|
8e73031e42 | ||
|
|
4105fd92f2 | ||
|
|
dd3a671a3d | ||
|
|
ee2b7cdb7e | ||
|
|
26f25d88c0 | ||
|
|
90166068ee | ||
|
|
bf44a5a70e | ||
|
|
be49b44004 | ||
|
|
8c3df85b2e | ||
|
|
97c46625e4 | ||
|
|
d4c30b5825 | ||
|
|
836ddea84d | ||
|
|
c99513092a | ||
|
|
34ad40778b | ||
|
|
859f20eb00 | ||
|
|
d5f988a16c | ||
|
|
e8ad4cc743 | ||
|
|
37b743d5d3 | ||
|
|
ade440d004 | ||
|
|
3f025fbb9b | ||
|
|
ed18907e95 | ||
|
|
a91f26f753 | ||
|
|
b64ed9b792 | ||
|
|
6eb4c76beb | ||
|
|
29315cab20 | ||
|
|
b31e887b2a | ||
|
|
d094d8eb83 | ||
|
|
9dd7184aa7 | ||
|
|
ec47e012a7 | ||
|
|
63a86f8944 | ||
|
|
0c27b81654 | ||
|
|
ace836c1af | ||
|
|
2cee02bec1 | ||
|
|
194a51bc2d | ||
|
|
e421d2607d | ||
|
|
396f17a15a | ||
|
|
f7361905b7 | ||
|
|
48fe19ed71 |
No files matched your search
@@ -101,6 +101,10 @@ backend/data/freight_rpa/
|
|||||||
backend/data/shipping_notice/
|
backend/data/shipping_notice/
|
||||||
backend/data/logs/
|
backend/data/logs/
|
||||||
backend/data/logs/*.log
|
backend/data/logs/*.log
|
||||||
|
backend/data/logs/*.log
|
||||||
|
# ERP HRAO 部门导入的本地数据(CSV 导出与真实公司映射不入库,模板 *.example.json 保留)
|
||||||
|
backend/scripts/data/*.csv
|
||||||
|
backend/scripts/data/hrao_company_map.json
|
||||||
|
|
||||||
# Engramory live memory store (plain text, machine-local)
|
# Engramory live memory store (plain text, machine-local)
|
||||||
/.engramory-memory/
|
/.engramory-memory/
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.2 MiB |
@@ -1,90 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"file": ".taste-skill/prototype/assets/gold-belt-mount-with-rivet.jpg",
|
|
||||||
"media": "image",
|
|
||||||
"ref": "met:464103",
|
|
||||||
"title": "Gold Belt Mount with Rivet",
|
|
||||||
"creator": "Avar maker",
|
|
||||||
"creatorUrl": null,
|
|
||||||
"date": "700s",
|
|
||||||
"license": "public domain (CC0)",
|
|
||||||
"licenseCode": "cc0",
|
|
||||||
"licenseUrl": "https://creativecommons.org/publicdomain/zero/1.0/",
|
|
||||||
"creditRequired": false,
|
|
||||||
"page": "https://www.metmuseum.org/art/collection/search/464103",
|
|
||||||
"via": "The Metropolitan Museum of Art",
|
|
||||||
"image": "https://images.metmuseum.org/CRDImages/md/original/17_190_1694ab_MED_s02.jpg",
|
|
||||||
"width": 3140,
|
|
||||||
"height": 4000,
|
|
||||||
"bytes": 1937315,
|
|
||||||
"credit": "\"Gold Belt Mount with Rivet\" by Avar maker, 700s, public domain (CC0), via The Metropolitan Museum of Art",
|
|
||||||
"notes": [],
|
|
||||||
"saved": "2026-10-27T02:25:25.754Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"file": ".taste-skill/prototype/assets/hammer.jpg",
|
|
||||||
"media": "image",
|
|
||||||
"ref": "met:204741",
|
|
||||||
"title": "Hammer",
|
|
||||||
"creator": null,
|
|
||||||
"creatorUrl": null,
|
|
||||||
"date": "probably 18th century",
|
|
||||||
"license": "public domain (CC0)",
|
|
||||||
"licenseCode": "cc0",
|
|
||||||
"licenseUrl": "https://creativecommons.org/publicdomain/zero/1.0/",
|
|
||||||
"creditRequired": false,
|
|
||||||
"page": "https://www.metmuseum.org/art/collection/search/204741",
|
|
||||||
"via": "The Metropolitan Museum of Art",
|
|
||||||
"image": "https://images.metmuseum.org/CRDImages/es/original/187608.jpg",
|
|
||||||
"width": 1984,
|
|
||||||
"height": 860,
|
|
||||||
"bytes": 281382,
|
|
||||||
"credit": "\"Hammer\", probably 18th century, public domain (CC0), via The Metropolitan Museum of Art",
|
|
||||||
"notes": [],
|
|
||||||
"saved": "2026-10-27T02:25:30.738Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"file": ".taste-skill/prototype/assets/armorer-s-anvil.jpg",
|
|
||||||
"media": "image",
|
|
||||||
"ref": "met:471599",
|
|
||||||
"title": "Armorer's Anvil",
|
|
||||||
"creator": "European maker",
|
|
||||||
"creatorUrl": null,
|
|
||||||
"date": "16th century",
|
|
||||||
"license": "public domain (CC0)",
|
|
||||||
"licenseCode": "cc0",
|
|
||||||
"licenseUrl": "https://creativecommons.org/publicdomain/zero/1.0/",
|
|
||||||
"creditRequired": false,
|
|
||||||
"page": "https://www.metmuseum.org/art/collection/search/471599",
|
|
||||||
"via": "The Metropolitan Museum of Art",
|
|
||||||
"image": "https://images.metmuseum.org/CRDImages/cl/original/cdi55-61-26.jpg",
|
|
||||||
"width": 2100,
|
|
||||||
"height": 1918,
|
|
||||||
"bytes": 1210493,
|
|
||||||
"credit": "\"Armorer's Anvil\" by European maker, 16th century, public domain (CC0), via The Metropolitan Museum of Art",
|
|
||||||
"notes": [],
|
|
||||||
"saved": "2026-10-27T02:25:45.912Z"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"file": ".taste-skill/prototype/assets/armor.jpg",
|
|
||||||
"media": "image",
|
|
||||||
"ref": "met:35937",
|
|
||||||
"title": "Armor",
|
|
||||||
"creator": "German, possibly Lower Saxony maker",
|
|
||||||
"creatorUrl": null,
|
|
||||||
"date": "ca. 1540–50 and later",
|
|
||||||
"license": "public domain (CC0)",
|
|
||||||
"licenseCode": "cc0",
|
|
||||||
"licenseUrl": "https://creativecommons.org/publicdomain/zero/1.0/",
|
|
||||||
"creditRequired": false,
|
|
||||||
"page": "https://www.metmuseum.org/art/collection/search/35937",
|
|
||||||
"via": "The Metropolitan Museum of Art",
|
|
||||||
"image": "https://images.metmuseum.org/CRDImages/aa/original/DP-36206-003.jpg",
|
|
||||||
"width": 3001,
|
|
||||||
"height": 4000,
|
|
||||||
"bytes": 1373710,
|
|
||||||
"credit": "\"Armor\" by German, possibly Lower Saxony maker, ca. 1540–50 and later, public domain (CC0), via The Metropolitan Museum of Art",
|
|
||||||
"notes": [],
|
|
||||||
"saved": "2026-10-27T02:26:00.813Z"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.8 MiB |
Binary file not shown.
|
Before Width: | Height: | Size: 275 KiB |
@@ -1,533 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="zh-CN">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
||||||
<title>尚未计时 · 托威斯拉钉机验收单</title>
|
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500&family=Stack+Sans+Headline:wght@300&family=Stack+Sans+Text:wght@400;500&display=swap" rel="stylesheet">
|
|
||||||
<script>document.documentElement.classList.add('js')</script>
|
|
||||||
<style>
|
|
||||||
:root {
|
|
||||||
--bg: #133621;
|
|
||||||
--surface: #1a4429;
|
|
||||||
--ink: #f4d96c;
|
|
||||||
--muted: #d4c27a;
|
|
||||||
--accent: #f4d96c;
|
|
||||||
--accent-ink: #133621;
|
|
||||||
--fold-1: #07160e;
|
|
||||||
--fold-2: #0c2418;
|
|
||||||
--fold-3: #12301f;
|
|
||||||
--fold-4: #184028;
|
|
||||||
--font-display: "Stack Sans Headline", "Noto Sans SC", sans-serif;
|
|
||||||
--font-text: "Stack Sans Text", "Noto Sans SC", sans-serif;
|
|
||||||
--step-small: clamp(0.8125rem, 0.79rem + 0.1vw, 0.875rem);
|
|
||||||
--step-body: clamp(1.0625rem, 1rem + 0.25vw, 1.1875rem);
|
|
||||||
--step-lead: clamp(1.25rem, 1.1rem + 0.7vw, 1.625rem);
|
|
||||||
--step-head: clamp(2rem, 1.3rem + 3.2vw, 4rem);
|
|
||||||
--step-display: clamp(4.25rem, 8vw, 9rem);
|
|
||||||
--margin: clamp(1rem, 2.2vw, 2rem);
|
|
||||||
--gutter: clamp(1rem, 2vw, 2rem);
|
|
||||||
--section: clamp(7.5rem, 12vw, 13.75rem);
|
|
||||||
--radius: 999px;
|
|
||||||
--ease-out: cubic-bezier(0.22, 1, 0.36, 1);
|
|
||||||
--t-press: 140ms;
|
|
||||||
--t-hover: 180ms;
|
|
||||||
--t-ui: 240ms;
|
|
||||||
--t-reveal: 800ms;
|
|
||||||
}
|
|
||||||
*, *::before, *::after { box-sizing: border-box; }
|
|
||||||
html { text-size-adjust: 100%; }
|
|
||||||
body {
|
|
||||||
margin: 0;
|
|
||||||
background: var(--bg);
|
|
||||||
color: var(--ink);
|
|
||||||
font-family: var(--font-text);
|
|
||||||
font-size: var(--step-body);
|
|
||||||
font-weight: 400;
|
|
||||||
line-height: 1.5;
|
|
||||||
-webkit-font-smoothing: antialiased;
|
|
||||||
}
|
|
||||||
h1, h2, p, figure { margin: 0; }
|
|
||||||
img { display: block; max-width: 100%; }
|
|
||||||
button, input { font: inherit; color: inherit; }
|
|
||||||
button { background: none; border: 0; padding: 0; cursor: pointer; }
|
|
||||||
a { color: inherit; }
|
|
||||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
|
|
||||||
::selection { background: var(--accent); color: var(--accent-ink); }
|
|
||||||
.nums { font-variant-numeric: tabular-nums; }
|
|
||||||
|
|
||||||
.rivet {
|
|
||||||
display: inline-grid;
|
|
||||||
place-items: center;
|
|
||||||
width: 1.15em;
|
|
||||||
height: 1.15em;
|
|
||||||
border-radius: 50%;
|
|
||||||
background: var(--accent);
|
|
||||||
flex: none;
|
|
||||||
}
|
|
||||||
.rivet i {
|
|
||||||
width: 34%;
|
|
||||||
height: 34%;
|
|
||||||
border-radius: 50%;
|
|
||||||
background: var(--hole, var(--bg));
|
|
||||||
}
|
|
||||||
|
|
||||||
.top {
|
|
||||||
position: absolute;
|
|
||||||
z-index: 2;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
right: 0;
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: 1fr auto 1fr;
|
|
||||||
align-items: center;
|
|
||||||
min-height: 4.5rem;
|
|
||||||
padding-inline: var(--margin);
|
|
||||||
}
|
|
||||||
.top .brand { grid-column: 2; font-family: var(--font-display); font-weight: 300; font-size: var(--step-body); text-decoration: none; }
|
|
||||||
.top .back { grid-column: 3; justify-self: end; font-size: var(--step-body); text-underline-offset: 0.2em; }
|
|
||||||
|
|
||||||
.hero { position: relative; overflow-x: clip; padding: 6.5rem var(--margin) 0; }
|
|
||||||
.hero h1 {
|
|
||||||
position: relative;
|
|
||||||
z-index: 1;
|
|
||||||
font-family: var(--font-display);
|
|
||||||
font-weight: 300;
|
|
||||||
font-size: var(--step-display);
|
|
||||||
line-height: 1.05;
|
|
||||||
letter-spacing: -0.03em;
|
|
||||||
text-wrap: balance;
|
|
||||||
}
|
|
||||||
.support {
|
|
||||||
position: relative;
|
|
||||||
z-index: 1;
|
|
||||||
max-width: 18em;
|
|
||||||
margin-top: 1.25rem;
|
|
||||||
font-size: var(--step-body);
|
|
||||||
line-height: 1.5;
|
|
||||||
}
|
|
||||||
.giant {
|
|
||||||
position: absolute;
|
|
||||||
z-index: 0;
|
|
||||||
top: 4.5rem;
|
|
||||||
right: -26vh;
|
|
||||||
width: 108vh;
|
|
||||||
height: 108vh;
|
|
||||||
border-radius: 50%;
|
|
||||||
overflow: hidden;
|
|
||||||
background: var(--accent);
|
|
||||||
}
|
|
||||||
.giant img { width: 100%; height: 100%; object-fit: cover; object-position: center 62%; }
|
|
||||||
|
|
||||||
.stack { position: relative; z-index: 1; width: min(86%, 1120px); margin: 7vh auto 0; padding-top: 16rem; }
|
|
||||||
.leaf {
|
|
||||||
position: absolute;
|
|
||||||
left: 0;
|
|
||||||
right: 0;
|
|
||||||
height: 4rem;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.75rem;
|
|
||||||
padding-inline: 1.25rem;
|
|
||||||
color: var(--ink);
|
|
||||||
text-decoration: none;
|
|
||||||
font-size: var(--step-body);
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
.leaf:nth-of-type(1) { top: 0; background: var(--fold-1); }
|
|
||||||
.leaf:nth-of-type(2) { top: 4rem; background: var(--fold-2); }
|
|
||||||
.leaf:nth-of-type(3) { top: 8rem; background: var(--fold-3); }
|
|
||||||
.leaf:nth-of-type(4) { top: 12rem; background: var(--fold-4); }
|
|
||||||
.leaf .rivet { --hole: var(--leaf, var(--bg)); width: 2.4rem; height: 2.4rem; }
|
|
||||||
.front {
|
|
||||||
position: relative;
|
|
||||||
min-height: 46vh;
|
|
||||||
padding: 2rem;
|
|
||||||
background: var(--surface);
|
|
||||||
}
|
|
||||||
.front .tabline { display: flex; align-items: center; gap: 0.75rem; font-weight: 500; margin-bottom: 1.5rem; }
|
|
||||||
.front .rivet { --hole: var(--surface); width: 2.4rem; height: 2.4rem; }
|
|
||||||
.button {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
min-height: 3.25rem;
|
|
||||||
padding: 0 1.5rem;
|
|
||||||
background: var(--accent);
|
|
||||||
color: var(--accent-ink);
|
|
||||||
border-radius: var(--radius);
|
|
||||||
text-decoration: none;
|
|
||||||
font-weight: 500;
|
|
||||||
}
|
|
||||||
.button:active { transform: scale(0.97); }
|
|
||||||
.front p { max-width: 36ch; margin-top: 1.5rem; }
|
|
||||||
|
|
||||||
.band { padding: var(--section) var(--margin); }
|
|
||||||
.ladder { background: var(--fold-1); }
|
|
||||||
.ladder h2, .facts h2 {
|
|
||||||
font-family: var(--font-display);
|
|
||||||
font-weight: 300;
|
|
||||||
font-size: var(--step-head);
|
|
||||||
line-height: 1.05;
|
|
||||||
letter-spacing: -0.02em;
|
|
||||||
max-width: 8em;
|
|
||||||
text-wrap: balance;
|
|
||||||
}
|
|
||||||
.ladder h2 { margin-bottom: 4rem; }
|
|
||||||
.stages { display: flex; align-items: stretch; gap: 6px; }
|
|
||||||
.stage { display: flex; flex-direction: column; gap: 0.9rem; min-width: 0; }
|
|
||||||
.seg {
|
|
||||||
display: flex;
|
|
||||||
align-items: flex-start;
|
|
||||||
min-height: 22vh;
|
|
||||||
padding: 1.25rem;
|
|
||||||
background: var(--seg, var(--surface));
|
|
||||||
color: var(--seg-ink, var(--ink));
|
|
||||||
font-family: var(--font-display);
|
|
||||||
font-weight: 300;
|
|
||||||
font-size: var(--step-lead);
|
|
||||||
line-height: 1.1;
|
|
||||||
}
|
|
||||||
.stage p { font-size: var(--step-body); }
|
|
||||||
.s1 { flex: 30 1 12%; --seg: #0c2418; }
|
|
||||||
.s2 { flex: 7 1 12%; --seg: #184028; }
|
|
||||||
.s3 { flex: 7 1 12%; --seg: #1f5536; }
|
|
||||||
.s4 { flex: 7 1 12%; --seg: var(--accent); --seg-ink: var(--accent-ink); }
|
|
||||||
.meter { position: relative; margin-top: 3rem; max-width: 72ch; }
|
|
||||||
.meter label { display: block; margin-bottom: 0.75rem; }
|
|
||||||
.meter input[type="range"] { width: 100%; height: 3rem; accent-color: #f4d96c; }
|
|
||||||
.meter .reading { margin-top: 0.75rem; max-width: 42ch; }
|
|
||||||
.track {
|
|
||||||
position: relative;
|
|
||||||
height: 2.75rem;
|
|
||||||
margin-bottom: 0.5rem;
|
|
||||||
}
|
|
||||||
.track .bar {
|
|
||||||
position: absolute;
|
|
||||||
left: 0;
|
|
||||||
right: 0;
|
|
||||||
top: 50%;
|
|
||||||
height: 0.55rem;
|
|
||||||
margin-top: -0.275rem;
|
|
||||||
background: #245c38;
|
|
||||||
}
|
|
||||||
.pin {
|
|
||||||
position: absolute;
|
|
||||||
top: 50%;
|
|
||||||
left: 0;
|
|
||||||
width: 1.75rem;
|
|
||||||
height: 1.75rem;
|
|
||||||
margin: -0.875rem 0 0 -0.875rem;
|
|
||||||
display: grid;
|
|
||||||
place-items: center;
|
|
||||||
border-radius: 50%;
|
|
||||||
background: var(--accent);
|
|
||||||
}
|
|
||||||
.pin i { width: 0.55rem; height: 0.55rem; border-radius: 50%; background: var(--fold-1); }
|
|
||||||
|
|
||||||
.facts { background: var(--fold-3); }
|
|
||||||
.split { display: grid; grid-template-columns: 5fr 7fr; column-gap: var(--gutter); align-items: start; }
|
|
||||||
.split h2 { grid-column: 2; grid-row: 1; margin-bottom: 2rem; }
|
|
||||||
.frame { position: sticky; top: 12vh; grid-column: 1; grid-row: 1 / span 2; width: min(34vw, 460px); }
|
|
||||||
.index { grid-column: 2; grid-row: 2; }
|
|
||||||
.shot {
|
|
||||||
position: relative;
|
|
||||||
width: 100%;
|
|
||||||
aspect-ratio: 1;
|
|
||||||
border-radius: 50%;
|
|
||||||
overflow: hidden;
|
|
||||||
background: var(--surface);
|
|
||||||
}
|
|
||||||
.shot img {
|
|
||||||
position: absolute;
|
|
||||||
inset: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
object-fit: cover;
|
|
||||||
opacity: 0;
|
|
||||||
}
|
|
||||||
.shot img.is-on { opacity: 1; }
|
|
||||||
.cap { max-width: 28ch; margin-top: 1rem; color: var(--muted); font-size: var(--step-small); }
|
|
||||||
.index h2 { margin-bottom: 0; }
|
|
||||||
.row {
|
|
||||||
display: block;
|
|
||||||
width: 100%;
|
|
||||||
text-align: left;
|
|
||||||
color: var(--muted);
|
|
||||||
border-radius: 0;
|
|
||||||
}
|
|
||||||
.row.is-on { color: var(--ink); }
|
|
||||||
.line { display: flex; justify-content: space-between; align-items: center; gap: 1rem; min-height: 3.6rem; }
|
|
||||||
.name { display: inline-flex; align-items: center; gap: 0.7rem; font-size: var(--step-lead); font-weight: 500; }
|
|
||||||
.row .rivet { --hole: var(--fold-3); }
|
|
||||||
.row.is-on .rivet { --hole: var(--fold-3); }
|
|
||||||
.val { font-size: var(--step-body); font-weight: 500; }
|
|
||||||
.desc { display: grid; grid-template-rows: 0fr; transition: grid-template-rows 320ms var(--ease-out); }
|
|
||||||
.desc span { overflow: hidden; }
|
|
||||||
.desc p { max-width: 36ch; padding-bottom: 0.8rem; font-size: var(--step-body); font-weight: 400; }
|
|
||||||
.row.is-on .desc { grid-template-rows: 1fr; }
|
|
||||||
.inline { display: none; }
|
|
||||||
|
|
||||||
.close { background: #07160e; padding-bottom: 3rem; }
|
|
||||||
.mark {
|
|
||||||
display: flex;
|
|
||||||
align-items: flex-end;
|
|
||||||
gap: 4px;
|
|
||||||
max-width: 100%;
|
|
||||||
overflow: visible;
|
|
||||||
}
|
|
||||||
.blob {
|
|
||||||
display: grid;
|
|
||||||
place-items: center;
|
|
||||||
flex: var(--g) 1 0;
|
|
||||||
min-width: 0;
|
|
||||||
aspect-ratio: 1;
|
|
||||||
border-radius: 50%;
|
|
||||||
background: var(--accent);
|
|
||||||
}
|
|
||||||
.blob i { width: 32%; height: 32%; border-radius: 50%; background: #07160e; }
|
|
||||||
.close-grid {
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: repeat(12, minmax(0, 1fr));
|
|
||||||
column-gap: var(--gutter);
|
|
||||||
margin-top: 3.5rem;
|
|
||||||
}
|
|
||||||
.links { grid-column: 1 / 9; display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 0.8rem 1rem; }
|
|
||||||
.links a { font-size: var(--step-body); text-decoration: none; }
|
|
||||||
.where { grid-column: 9 / 13; font-size: var(--step-body); }
|
|
||||||
.legal {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
gap: 1rem;
|
|
||||||
margin-top: 3rem;
|
|
||||||
}
|
|
||||||
.legal p, .credits { max-width: 78ch; color: var(--muted); font-size: var(--step-small); }
|
|
||||||
.credits { margin-top: 1.5rem; }
|
|
||||||
.credits a { color: inherit; }
|
|
||||||
|
|
||||||
@media (hover: hover) and (pointer: fine) {
|
|
||||||
.button:hover { background: #ffe58a; }
|
|
||||||
.leaf:hover .name, .links a:hover { text-decoration: underline; text-underline-offset: 0.18em; }
|
|
||||||
}
|
|
||||||
@media (max-width: 800px) {
|
|
||||||
.hero { padding-top: 48svh; }
|
|
||||||
.hero h1, .support {
|
|
||||||
position: absolute;
|
|
||||||
left: var(--margin);
|
|
||||||
right: var(--margin);
|
|
||||||
max-width: none;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
.hero h1 { top: 5.5rem; font-size: 17vw; }
|
|
||||||
.support { top: calc(5.5rem + 17vw + 0.8rem); font-size: 1rem; }
|
|
||||||
.giant { width: 62vw; height: 62vw; right: -14vw; top: calc(8.5rem + 17vw); bottom: auto; }
|
|
||||||
.stack { width: 100%; margin-top: 0; padding-top: 13rem; }
|
|
||||||
.leaf { height: 3.25rem; }
|
|
||||||
.leaf:nth-of-type(2) { top: 3.25rem; }
|
|
||||||
.leaf:nth-of-type(3) { top: 6.5rem; }
|
|
||||||
.leaf:nth-of-type(4) { top: 9.75rem; }
|
|
||||||
.front .button { width: 100%; }
|
|
||||||
.stages { flex-direction: column; }
|
|
||||||
.stage { flex: none; }
|
|
||||||
.seg { min-height: 5.5rem; }
|
|
||||||
.split { grid-template-columns: 1fr; }
|
|
||||||
.split h2, .frame, .index { grid-column: 1; width: auto; }
|
|
||||||
.split h2 { grid-row: 1; }
|
|
||||||
.frame { position: static; grid-row: 2; width: min(72vw, 360px); }
|
|
||||||
.index { grid-row: 3; }
|
|
||||||
.shot { width: min(70vw, 320px); margin-inline: auto; }
|
|
||||||
.close-grid { grid-template-columns: 1fr; }
|
|
||||||
.links, .where { grid-column: auto; }
|
|
||||||
.links { grid-template-columns: 1fr 1fr; }
|
|
||||||
.legal { flex-direction: column; align-items: flex-start; }
|
|
||||||
.mark { max-width: 100%; }
|
|
||||||
}
|
|
||||||
@media (prefers-reduced-motion: no-preference) {
|
|
||||||
.js [data-rise] { opacity: 0; transform: translateY(22px); animation: rise var(--t-reveal) var(--ease-out) forwards; animation-delay: calc(var(--i, 0) * 80ms + 80ms); }
|
|
||||||
.js [data-reveal] { opacity: 0; transform: translateY(22px); transition: opacity 700ms var(--ease-out), transform 800ms var(--ease-out); }
|
|
||||||
.js [data-reveal].is-in { opacity: 1; transform: none; }
|
|
||||||
.js .shot img { transition: opacity var(--t-ui) linear; }
|
|
||||||
.js .shot img.is-on { animation: drift 16s ease-in-out infinite alternate; }
|
|
||||||
.button, .leaf, .row, .links a { transition: background-color var(--t-hover) ease, color var(--t-hover) ease, transform var(--t-press) var(--ease-out); }
|
|
||||||
}
|
|
||||||
@keyframes rise { to { opacity: 1; transform: none; } }
|
|
||||||
@keyframes drift { to { transform: scale(1.06); } }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<header class="hero" id="top">
|
|
||||||
<div class="top">
|
|
||||||
<a class="brand" href="#top">设备验收预警</a>
|
|
||||||
<a class="back" href="#close">返回停留情况</a>
|
|
||||||
</div>
|
|
||||||
<div class="giant" data-rise style="--i:2">
|
|
||||||
<img src="assets/gold-belt-mount-with-rivet.jpg" width="3140" height="4000" alt="八世纪金带扣,面上有一颗铆钉和一个孔。这不是托威斯拉钉机。">
|
|
||||||
</div>
|
|
||||||
<h1 data-rise style="--i:0">尚未计时</h1>
|
|
||||||
<p class="support" data-rise style="--i:1">托威斯这台拉钉机还停在品质担当,<br>签核天数是零。</p>
|
|
||||||
<div class="stack">
|
|
||||||
<a class="leaf" href="#ladder" data-rise style="--i:3; --leaf:#07160e"><span class="rivet" aria-hidden="true"><i></i></span>四档</a>
|
|
||||||
<a class="leaf" href="#facts" data-rise style="--i:4; --leaf:#0c2418"><span class="rivet" aria-hidden="true"><i></i></span>单据</a>
|
|
||||||
<a class="leaf" href="#handler" data-rise style="--i:5; --leaf:#12301f"><span class="rivet" aria-hidden="true"><i></i></span>经手</a>
|
|
||||||
<a class="leaf" href="#close" data-rise style="--i:6; --leaf:#184028"><span class="rivet" aria-hidden="true"><i></i></span>落款</a>
|
|
||||||
<div class="front" data-rise style="--i:7">
|
|
||||||
<div class="tabline"><span class="rivet" aria-hidden="true"><i></i></span>这张单</div>
|
|
||||||
<a class="button" href="#facts">看单据上的字</a>
|
|
||||||
<p>验收单 20260718000003,流程 20260718-1520。温德佳经手。审批还没结束,这张单可以验收,也没有退回。</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<section class="band ladder" id="ladder">
|
|
||||||
<h2 data-reveal>三十天才第一封</h2>
|
|
||||||
<div class="stages" data-ui>
|
|
||||||
<article class="stage s1" data-reveal style="--i:1">
|
|
||||||
<div class="seg">三十天</div>
|
|
||||||
<p>使用部门担当收到,并抄送主管。</p>
|
|
||||||
</article>
|
|
||||||
<article class="stage s2" data-reveal style="--i:2">
|
|
||||||
<div class="seg">七天</div>
|
|
||||||
<p>经副理收到,抄送 COO。</p>
|
|
||||||
</article>
|
|
||||||
<article class="stage s3" data-reveal style="--i:3">
|
|
||||||
<div class="seg">七天</div>
|
|
||||||
<p>COO 收到,抄送采购经副理。</p>
|
|
||||||
</article>
|
|
||||||
<article class="stage s4" data-reveal style="--i:4">
|
|
||||||
<div class="seg">七天</div>
|
|
||||||
<p>总经理默认不发。</p>
|
|
||||||
</article>
|
|
||||||
</div>
|
|
||||||
<div class="meter" data-reveal style="--i:5">
|
|
||||||
<div class="track" aria-hidden="true">
|
|
||||||
<div class="bar"></div>
|
|
||||||
<span class="pin" id="pin"><i></i></span>
|
|
||||||
</div>
|
|
||||||
<label for="dwell">假设已经签核 <output class="nums" id="days">0</output> 天</label>
|
|
||||||
<input id="dwell" type="range" min="0" max="60" value="0" step="1">
|
|
||||||
<p class="reading" id="reading">还在起点。进入使用部门担当之后,才从到达那天算。</p>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="band facts" id="facts">
|
|
||||||
<div class="split">
|
|
||||||
<h2 data-reveal>单据上的字</h2>
|
|
||||||
<figure class="frame">
|
|
||||||
<div class="shot">
|
|
||||||
<img class="is-on" data-shot="0" src="assets/gold-belt-mount-with-rivet.jpg" width="3140" height="4000" alt="金带扣上的铆钉,阿瓦尔人,八世纪">
|
|
||||||
<img data-shot="1" src="assets/hammer.jpg" width="1984" height="860" alt="一把十八世纪的小锤" loading="lazy">
|
|
||||||
<img data-shot="2" src="assets/armorer-s-anvil.jpg" width="2100" height="1918" alt="十六世纪盔甲匠用的铁砧" loading="lazy">
|
|
||||||
<img data-shot="3" src="assets/armor.jpg" width="3001" height="4000" alt="十六世纪板甲,甲片用铆钉固定" loading="lazy">
|
|
||||||
</div>
|
|
||||||
<figcaption class="cap" id="cap">金带扣上的铆钉。阿瓦尔人,八世纪。大都会艺术博物馆藏,不是这台机器。</figcaption>
|
|
||||||
</figure>
|
|
||||||
<div class="index">
|
|
||||||
<button class="row is-on" type="button" data-shot="0" data-cap="金带扣上的铆钉。阿瓦尔人,八世纪。大都会艺术博物馆藏,不是这台机器。">
|
|
||||||
<span class="line"><span class="name"><span class="rivet" aria-hidden="true"><i></i></span>验收单</span><span class="val nums">20260718000003</span></span>
|
|
||||||
<span class="desc"><span><p>流程编号 20260718-1520。标题是托威斯平台式自动拉钉机,一套,提交 OA。创建于 2026-07-18 16:51:47。</p></span></span>
|
|
||||||
</button>
|
|
||||||
<button class="row" type="button" data-shot="1" data-cap="小锤。大概十八世纪。大都会艺术博物馆藏,不是采购单上的设备。">
|
|
||||||
<span class="line"><span class="name"><span class="rivet" aria-hidden="true"><i></i></span>采购单</span><span class="val nums">5202-2606030008</span></span>
|
|
||||||
<span class="desc"><span><p>申请人柴晓红。这张快照里没有合同号,采购单号就这一条。</p></span></span>
|
|
||||||
</button>
|
|
||||||
<button class="row" id="handler" type="button" data-shot="2" data-cap="盔甲匠的铁砧。十六世纪。人还没到计时的那一站,就像工件还搁在砧上。">
|
|
||||||
<span class="line"><span class="name"><span class="rivet" aria-hidden="true"><i></i></span>当前处理人</span><span class="val">温德佳</span></span>
|
|
||||||
<span class="desc"><span><p>节点是品质担当。计时要等使用部门担当,所以起点和天数都还是空的。工号这页没写。</p></span></span>
|
|
||||||
</button>
|
|
||||||
<button class="row" type="button" data-shot="3" data-cap="板甲。十六世纪,下萨克森一带。甲片靠铆钉固定,不是验收结论的照片。">
|
|
||||||
<span class="line"><span class="name"><span class="rivet" aria-hidden="true"><i></i></span>验收结论</span><span class="val">可以验收</span></span>
|
|
||||||
<span class="desc"><span><p>没有无法验收说明,也没有退回。流程仍是审批中,结束时间还没有。</p></span></span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<footer class="band close" id="close">
|
|
||||||
<div class="mark" aria-hidden="true">
|
|
||||||
<span class="blob" data-reveal style="--g:0.62"><i></i></span>
|
|
||||||
<span class="blob" data-reveal style="--g:0.84; --i:1"><i></i></span>
|
|
||||||
<span class="blob" data-reveal style="--g:1; --i:2"><i></i></span>
|
|
||||||
<span class="blob" data-reveal style="--g:0.7; --i:3"><i></i></span>
|
|
||||||
<span class="blob" data-reveal style="--g:0.92; --i:4"><i></i></span>
|
|
||||||
<span class="blob" data-reveal style="--g:0.58; --i:5"><i></i></span>
|
|
||||||
<span class="blob" data-reveal style="--g:1; --i:6"><i></i></span>
|
|
||||||
</div>
|
|
||||||
<div class="close-grid">
|
|
||||||
<nav class="links" aria-label="页面">
|
|
||||||
<a href="#top">停留情况</a>
|
|
||||||
<a href="#ladder">四档天数</a>
|
|
||||||
<a href="#facts">这张单据</a>
|
|
||||||
<a href="#handler">当前处理人</a>
|
|
||||||
</nav>
|
|
||||||
<p class="where">验收单 20260718000003<br>流程 20260718-1520</p>
|
|
||||||
</div>
|
|
||||||
<div class="legal">
|
|
||||||
<p>正式页面里,返回会回到停留列表。这里只停在这一张单上。</p>
|
|
||||||
<a class="button" href="#top">返回停留情况</a>
|
|
||||||
</div>
|
|
||||||
<p class="credits">器物照片都来自大都会艺术博物馆,公有领域,不是托威斯的设备,也不是温德佳或柴晓红。<a href="https://www.metmuseum.org/art/collection/search/464103">金带扣与铆钉</a>,阿瓦尔人,八世纪。<a href="https://www.metmuseum.org/art/collection/search/204741">小锤</a>,约十八世纪。<a href="https://www.metmuseum.org/art/collection/search/471599">盔甲匠铁砧</a>,十六世纪。<a href="https://www.metmuseum.org/art/collection/search/35937">板甲</a>,约 1540–1550 年,可能来自下萨克森。</p>
|
|
||||||
</footer>
|
|
||||||
<script>
|
|
||||||
const rows = [...document.querySelectorAll('.row')];
|
|
||||||
const shots = [...document.querySelectorAll('.shot img')];
|
|
||||||
const cap = document.getElementById('cap');
|
|
||||||
function show(row) {
|
|
||||||
rows.forEach((item) => item.classList.toggle('is-on', item === row));
|
|
||||||
shots.forEach((img) => img.classList.toggle('is-on', img.dataset.shot === row.dataset.shot));
|
|
||||||
cap.textContent = row.dataset.cap;
|
|
||||||
}
|
|
||||||
rows.forEach((row) => {
|
|
||||||
row.addEventListener('mouseenter', () => show(row));
|
|
||||||
row.addEventListener('focus', () => show(row));
|
|
||||||
row.addEventListener('click', () => show(row));
|
|
||||||
});
|
|
||||||
|
|
||||||
const dwell = document.getElementById('dwell');
|
|
||||||
const days = document.getElementById('days');
|
|
||||||
const reading = document.getElementById('reading');
|
|
||||||
const pin = document.getElementById('pin');
|
|
||||||
const narrow = window.matchMedia('(max-width: 800px)');
|
|
||||||
function sentence(n) {
|
|
||||||
if (n <= 0) return '还在起点。进入使用部门担当之后,才从到达那天算。';
|
|
||||||
if (n < 30) return '已过 ' + n + ' 天,还没到三十天,一封都不发。';
|
|
||||||
if (n < 37) return '已过三十天。通知使用部门担当,抄送直接主管和采购担当。';
|
|
||||||
if (n < 44) return '已过三十七天。通知经副理,抄送 COO 和采购经副理。';
|
|
||||||
if (n < 51) return '已过四十四天。通知 COO,抄送采购经副理。';
|
|
||||||
return '已过五十一天。总经理这一档默认关着,打开后才发。';
|
|
||||||
}
|
|
||||||
function paint() {
|
|
||||||
const n = Number(dwell.value);
|
|
||||||
const pct = Math.min(100, (n / 51) * 100);
|
|
||||||
days.textContent = String(n);
|
|
||||||
reading.textContent = sentence(n);
|
|
||||||
if (narrow.matches) {
|
|
||||||
pin.style.top = '50%';
|
|
||||||
pin.style.left = pct + '%';
|
|
||||||
} else {
|
|
||||||
pin.style.top = '50%';
|
|
||||||
pin.style.left = pct + '%';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
dwell.addEventListener('input', paint);
|
|
||||||
narrow.addEventListener('change', paint);
|
|
||||||
paint();
|
|
||||||
|
|
||||||
const targets = document.querySelectorAll('[data-reveal]');
|
|
||||||
if ('IntersectionObserver' in window) {
|
|
||||||
const io = new IntersectionObserver((entries) => {
|
|
||||||
entries.forEach((entry) => {
|
|
||||||
if (!entry.isIntersecting) return;
|
|
||||||
entry.target.classList.add('is-in');
|
|
||||||
io.unobserve(entry.target);
|
|
||||||
});
|
|
||||||
}, { rootMargin: '0px 0px -8% 0px', threshold: 0.12 });
|
|
||||||
targets.forEach((el) => io.observe(el));
|
|
||||||
} else {
|
|
||||||
targets.forEach((el) => el.classList.add('is-in'));
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,9 +1,9 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/api/admin/departments.py
|
backend/app/api/admin/departments.py
|
||||||
|
|
||||||
用途:管理后台部门 CRUD API(薄路由层)。
|
用途:管理后台部门 CRUD API(薄路由层,树形结构)。
|
||||||
依赖:admin.blueprint、services/admin/department_service。
|
依赖:admin.blueprint、services/admin/department_service。
|
||||||
逻辑:/departments* 路由。
|
逻辑:/departments 平铺列表(兼容旧消费方)、/departments/tree 树、成员名单(支持含下级)。
|
||||||
"""
|
"""
|
||||||
from flask import jsonify, request
|
from flask import jsonify, request
|
||||||
|
|
||||||
@@ -15,10 +15,17 @@ from app.services.admin import department_service
|
|||||||
@admin_bp.route('/departments', methods=['GET'])
|
@admin_bp.route('/departments', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def list_departments():
|
def list_departments():
|
||||||
"""返回全部部门列表。"""
|
"""返回全部部门平铺列表(旧消费方兼容:部门下拉等)。"""
|
||||||
return jsonify(department_service.list_departments())
|
return jsonify(department_service.list_departments())
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/departments/tree', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def department_tree():
|
||||||
|
"""返回完整部门树(children 嵌套,成员数含下级递归汇总)。"""
|
||||||
|
return jsonify(department_service.list_department_tree())
|
||||||
|
|
||||||
|
|
||||||
@admin_bp.route('/departments', methods=['POST'])
|
@admin_bp.route('/departments', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def create_department():
|
def create_department():
|
||||||
@@ -31,8 +38,15 @@ def create_department():
|
|||||||
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
@admin_bp.route('/departments/<int:id>/members', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def list_department_members(id: int):
|
def list_department_members(id: int):
|
||||||
"""返回部门员工数量与名单。"""
|
"""部门员工分页名单(OA 组织面板口径):include_descendants=1 含下级,keyword 搜姓名/工号/邮箱/手机。"""
|
||||||
return jsonify(department_service.list_department_members(id))
|
include_descendants = request.args.get('include_descendants', '') in ('1', 'true')
|
||||||
|
return jsonify(department_service.list_department_members(
|
||||||
|
id,
|
||||||
|
include_descendants,
|
||||||
|
keyword=request.args.get('keyword', ''),
|
||||||
|
page=request.args.get('page', 1, type=int),
|
||||||
|
page_size=request.args.get('page_size', 20, type=int),
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
@admin_bp.route('/departments/<int:id>', methods=['PUT'])
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ backend/app/api/admin/reports.py
|
|||||||
依赖:admin.blueprint、services/admin/report_service。
|
依赖:admin.blueprint、services/admin/report_service。
|
||||||
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
逻辑:/reports/usage、/reports/applications、feedback 与 general-feedbacks 路由。
|
||||||
"""
|
"""
|
||||||
from flask import jsonify, request
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
from flask import Response, jsonify, request
|
||||||
|
|
||||||
from app.api.admin.blueprint import admin_bp
|
from app.api.admin.blueprint import admin_bp
|
||||||
from app.core.decorators import require_admin
|
from app.core.decorators import require_admin
|
||||||
@@ -134,3 +136,15 @@ def issue_analysis():
|
|||||||
def close_general_feedback(feedback_id: int):
|
def close_general_feedback(feedback_id: int):
|
||||||
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
"""将一条意见反馈标记为已关闭(status='closed')。"""
|
||||||
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
return jsonify(report_service.mark_general_feedback_closed(feedback_id))
|
||||||
|
|
||||||
|
|
||||||
|
@admin_bp.route('/reports/general-feedbacks/<int:feedback_id>/images/<int:image_id>/raw', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def general_feedback_image_raw(feedback_id: int, image_id: int):
|
||||||
|
"""代理输出意见反馈截图字节流(inline 展示用)。"""
|
||||||
|
payload = report_service.get_general_feedback_image_payload(feedback_id, image_id)
|
||||||
|
resp = Response(payload['data'], mimetype=payload['mime_type'])
|
||||||
|
# [SECURITY] Content-Type 已按扩展名白名单收敛,仍禁浏览器嗅探,双保险防内联渲染为 HTML
|
||||||
|
resp.headers['X-Content-Type-Options'] = 'nosniff'
|
||||||
|
resp.headers['Content-Disposition'] = f"inline; filename*=UTF-8''{quote(payload['filename'])}"
|
||||||
|
return resp
|
||||||
@@ -12,7 +12,7 @@ from flask import Blueprint
|
|||||||
chat_bp = Blueprint('chat', __name__)
|
chat_bp = Blueprint('chat', __name__)
|
||||||
|
|
||||||
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
||||||
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
from . import assets, capability_list, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
||||||
from .shared import ( # noqa: E402, F401
|
from .shared import ( # noqa: E402, F401
|
||||||
CHAT_USER_ATTACHMENT_LIMIT,
|
CHAT_USER_ATTACHMENT_LIMIT,
|
||||||
CHAT_USER_ATTACHMENT_MAX_SIZE,
|
CHAT_USER_ATTACHMENT_MAX_SIZE,
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"""
|
||||||
|
api/chat/capability_list.py
|
||||||
|
|
||||||
|
用途:聊天端「知识库内容清单」查询接口,作为知识库未命中兜底回复按钮的数据源。
|
||||||
|
依赖:chat.shared(公共上下文与异常)、chat_bp、services.chat.capability_list。
|
||||||
|
逻辑:GET /api/chat/capability-list?agent_id=...,经 require_agent_permission 鉴权后
|
||||||
|
返回常用问题中该应用「能力清单条目」的标准答案;未配置时抛 404 业务错误。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .shared import * # noqa: F403
|
||||||
|
from . import chat_bp
|
||||||
|
from app.services.chat.capability_list import get_agent_capability_list
|
||||||
|
|
||||||
|
|
||||||
|
@chat_bp.route('/capability-list', methods=['GET'])
|
||||||
|
@require_agent_permission
|
||||||
|
def get_capability_list():
|
||||||
|
"""
|
||||||
|
获取当前应用的知识库内容清单。
|
||||||
|
用途:AI 回复命中知识库未命中兜底语句时,前端【知识库内容清单】按钮点击后调用。
|
||||||
|
核心逻辑:
|
||||||
|
1. require_agent_permission 从 query 读取 agent_id 并校验用户对该应用的访问权限;
|
||||||
|
2. 委托 services.chat.capability_list 返回「能力清单条目」标准答案;
|
||||||
|
3. 未配置时抛 code=CHAT.CAPABILITY_LIST_NOT_FOUND(404),前端按错误码本地化提示。
|
||||||
|
参数约束:agent_id 必须来自当前会话路由(当前聊天应用),禁止跨应用探测他人条目。
|
||||||
|
"""
|
||||||
|
agent = getattr(g, 'current_agent', None)
|
||||||
|
if agent is None:
|
||||||
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing agent context', http_status=500)
|
||||||
|
return jsonify(get_agent_capability_list(agent))
|
||||||
@@ -2,8 +2,9 @@
|
|||||||
backend/app/api/equipment_acceptance/__init__.py
|
backend/app/api/equipment_acceptance/__init__.py
|
||||||
|
|
||||||
用途:设备验收预警的 Chat 作业面接口。
|
用途:设备验收预警的 Chat 作业面接口。
|
||||||
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
|
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应、jobs.queue。
|
||||||
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
|
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;
|
||||||
|
同步、扫描、发送和保存配置仅平台管理员。扫描与发送改为入队,由 schedule worker 执行,避免 HTTP 504。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -12,15 +13,17 @@ from io import BytesIO
|
|||||||
|
|
||||||
from flask import Blueprint, g, request, send_file
|
from flask import Blueprint, g, request, send_file
|
||||||
|
|
||||||
|
from app import db
|
||||||
from app.core.auth.jwt import get_current_user
|
from app.core.auth.jwt import get_current_user
|
||||||
from app.core.errors import ForbiddenError, UnauthorizedError
|
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||||
from app.core.response import ok
|
from app.core.response import ok
|
||||||
from app.models import Agent
|
from app.jobs.queue import enqueue
|
||||||
|
from app.jobs.types import JobType
|
||||||
|
from app.models import Agent, Job
|
||||||
from app.services.equipment_acceptance.config_service import (
|
from app.services.equipment_acceptance.config_service import (
|
||||||
get_acceptance_config,
|
get_acceptance_config,
|
||||||
save_acceptance_config,
|
save_acceptance_config,
|
||||||
)
|
)
|
||||||
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
|
|
||||||
from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records
|
from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records
|
||||||
from app.services.equipment_acceptance.sync_service import (
|
from app.services.equipment_acceptance.sync_service import (
|
||||||
get_acceptance_order,
|
get_acceptance_order,
|
||||||
@@ -28,6 +31,11 @@ from app.services.equipment_acceptance.sync_service import (
|
|||||||
sync_acceptance_snapshots,
|
sync_acceptance_snapshots,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
_EQUIPMENT_ACCEPTANCE_JOB_TYPES = {
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN.value,
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY.value,
|
||||||
|
}
|
||||||
|
|
||||||
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
|
equipment_acceptance_bp = Blueprint("equipment_acceptance", __name__)
|
||||||
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
|
EQUIPMENT_ACCEPTANCE_AGENT_CODE = "equipment_acceptance"
|
||||||
|
|
||||||
@@ -149,16 +157,79 @@ def save_equipment_acceptance_config():
|
|||||||
|
|
||||||
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
|
@equipment_acceptance_bp.route("/alerts/scan", methods=["POST"])
|
||||||
def scan_equipment_acceptance_alerts():
|
def scan_equipment_acceptance_alerts():
|
||||||
"""管理员立即同步 E10 并生成待发送记录。不发企业微信。"""
|
"""
|
||||||
_require_equipment_acceptance_admin()
|
将设备验收扫描任务入队。
|
||||||
return ok(generate_alerts(), request_id=getattr(g, "request_id", None))
|
|
||||||
|
核心逻辑:仅平台管理员。Worker 同步后生成待发送,不发企业微信。
|
||||||
|
同业务键已有 queued/running 时复用,避免连点重复扫。
|
||||||
|
Returns:
|
||||||
|
HTTP 202 与 job_id。
|
||||||
|
"""
|
||||||
|
user = _require_equipment_acceptance_admin()
|
||||||
|
job_id = enqueue(
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN,
|
||||||
|
{},
|
||||||
|
domain="equipment_acceptance",
|
||||||
|
business_ref="daily-alert",
|
||||||
|
created_by_id=user.id,
|
||||||
|
message="等待扫描设备验收预警",
|
||||||
|
)
|
||||||
|
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||||
|
|
||||||
|
|
||||||
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
|
@equipment_acceptance_bp.route("/alerts/send", methods=["POST"])
|
||||||
def send_equipment_acceptance_alerts():
|
def send_equipment_acceptance_alerts():
|
||||||
"""管理员立即把待发送记录按收件人发到企业微信。"""
|
"""
|
||||||
_require_equipment_acceptance_admin()
|
将设备验收发送任务入队。
|
||||||
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
|
|
||||||
|
核心逻辑:仅平台管理员。Worker 按收件人发企微后改发送记录状态。
|
||||||
|
同业务键已有 queued/running 时复用,避免连点重复发。
|
||||||
|
Returns:
|
||||||
|
HTTP 202 与 job_id。
|
||||||
|
"""
|
||||||
|
user = _require_equipment_acceptance_admin()
|
||||||
|
job_id = enqueue(
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY,
|
||||||
|
{},
|
||||||
|
domain="equipment_acceptance",
|
||||||
|
business_ref="weekly-alert",
|
||||||
|
created_by_id=user.id,
|
||||||
|
message="等待发送设备验收预警",
|
||||||
|
)
|
||||||
|
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||||
|
|
||||||
|
|
||||||
|
@equipment_acceptance_bp.route("/jobs/<int:job_id>", methods=["GET"])
|
||||||
|
def get_equipment_acceptance_job(job_id: int):
|
||||||
|
"""
|
||||||
|
查询当前管理员提交的设备验收后台任务是否跑完。
|
||||||
|
|
||||||
|
核心逻辑:只返回本人创建的设备验收 Job。发送任务的 result 含 sent/failed。
|
||||||
|
Args:
|
||||||
|
job_id: jobs 表主键。
|
||||||
|
Returns:
|
||||||
|
status、message、result。
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 任务不存在或不属于当前管理员。
|
||||||
|
"""
|
||||||
|
user = _require_equipment_acceptance_admin()
|
||||||
|
row = db.session.get(Job, job_id)
|
||||||
|
if (
|
||||||
|
row is None
|
||||||
|
or row.domain != "equipment_acceptance"
|
||||||
|
or row.job_type not in _EQUIPMENT_ACCEPTANCE_JOB_TYPES
|
||||||
|
or row.created_by_id != user.id
|
||||||
|
):
|
||||||
|
raise NotFoundError("任务不存在")
|
||||||
|
return ok(
|
||||||
|
{
|
||||||
|
"id": row.id,
|
||||||
|
"status": row.status,
|
||||||
|
"message": row.message,
|
||||||
|
"result": row.result_json or {},
|
||||||
|
},
|
||||||
|
request_id=getattr(g, "request_id", None),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
|
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
|
||||||
|
|||||||
@@ -7,9 +7,10 @@ backend/app/api/user/handlers.py
|
|||||||
"""
|
"""
|
||||||
from flask import Blueprint, request, jsonify, current_app
|
from flask import Blueprint, request, jsonify, current_app
|
||||||
from sqlalchemy import and_, or_
|
from sqlalchemy import and_, or_
|
||||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, ChatLog
|
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, GeneralFeedbackImage, ChatLog
|
||||||
|
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
|
||||||
from app.services.feedback_notify import send_feedback_group_notification
|
from app.services.feedback_notify import send_feedback_group_notification
|
||||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||||
@@ -32,6 +33,11 @@ from .auth import (
|
|||||||
)
|
)
|
||||||
user_bp = Blueprint('user', __name__)
|
user_bp = Blueprint('user', __name__)
|
||||||
|
|
||||||
|
# [CONST] 反馈附件图片上限与允许的图片扩展名(POST /feedback 的 image_asset_nos 校验用)
|
||||||
|
_FEEDBACK_MAX_IMAGES = 5
|
||||||
|
_FEEDBACK_IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}
|
||||||
|
|
||||||
|
|
||||||
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
||||||
def mark_wecom_deeplink_opened():
|
def mark_wecom_deeplink_opened():
|
||||||
user = _get_current_user()
|
user = _get_current_user()
|
||||||
@@ -161,9 +167,46 @@ def submit_general_feedback():
|
|||||||
raise ValidationError('chat_log_id not found')
|
raise ValidationError('chat_log_id not found')
|
||||||
if chat_log.user_id != user.id:
|
if chat_log.user_id != user.id:
|
||||||
raise ForbiddenError('chat_log_id is not owned by current user')
|
raise ForbiddenError('chat_log_id is not owned by current user')
|
||||||
|
# [STEP 1] 解析并规整 image_asset_nos(可选参数):非 list 直接拒绝;元素转 str 去空白、保序去重;超上限整单拒绝
|
||||||
|
raw_asset_nos = data.get('image_asset_nos')
|
||||||
|
normalized_asset_nos: list[str] = []
|
||||||
|
if raw_asset_nos is not None:
|
||||||
|
if not isinstance(raw_asset_nos, list):
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='image_asset_nos must be a list')
|
||||||
|
seen_asset_nos: set[str] = set()
|
||||||
|
for item in raw_asset_nos:
|
||||||
|
asset_no = str(item or '').strip()
|
||||||
|
if not asset_no or asset_no in seen_asset_nos:
|
||||||
|
continue
|
||||||
|
seen_asset_nos.add(asset_no)
|
||||||
|
normalized_asset_nos.append(asset_no)
|
||||||
|
if len(normalized_asset_nos) > _FEEDBACK_MAX_IMAGES:
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_TOO_MANY', message='最多附加 5 张图片')
|
||||||
|
# [STEP 2] 逐个校验资产归属与图片语义(任一失败整单拒绝,反馈与图片关联都不落库)
|
||||||
|
feedback_assets = []
|
||||||
|
for asset_no in normalized_asset_nos:
|
||||||
|
asset = get_asset_for_user(asset_no, user.id)
|
||||||
|
if asset.extension not in _FEEDBACK_IMAGE_EXTENSIONS:
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='仅支持 png/jpg/jpeg/webp 图片')
|
||||||
|
if asset.upload_status != 'ready':
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='图片尚未上传完成')
|
||||||
|
if asset.reference_count != 0 or asset.lifecycle_status != 'temporary':
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='该文件已被使用')
|
||||||
|
feedback_assets.append(asset)
|
||||||
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
|
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
|
||||||
|
# [STEP 3] 落库:flush 拿反馈 id → 按枚举序写图片关联(sort_order=下标)→ 逐个标记资产被引用 → commit;
|
||||||
|
# IntegrityError 兜底并发双挂(asset_id 唯一约束),回滚整单并转业务错误
|
||||||
db.session.add(row)
|
db.session.add(row)
|
||||||
db.session.commit()
|
db.session.flush()
|
||||||
|
for idx, asset in enumerate(feedback_assets):
|
||||||
|
db.session.add(GeneralFeedbackImage(feedback_id=row.id, asset_id=asset.id, sort_order=idx))
|
||||||
|
mark_asset_referenced(asset)
|
||||||
|
try:
|
||||||
|
db.session.commit()
|
||||||
|
except IntegrityError:
|
||||||
|
db.session.rollback()
|
||||||
|
raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='图片已被使用,请重新添加')
|
||||||
|
# [STEP 4] 通知与返回不变:提交成功后推送企微群通知(失败不影响提交结果),返回旧契约 JSON
|
||||||
notify_result = send_feedback_group_notification(row, user)
|
notify_result = send_feedback_group_notification(row, user)
|
||||||
if notify_result.get('ok'):
|
if notify_result.get('ok'):
|
||||||
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ backend/app/jobs/handlers/__init__.py
|
|||||||
|
|
||||||
from app.jobs.handlers import ( # noqa: F401
|
from app.jobs.handlers import ( # noqa: F401
|
||||||
contract_payment,
|
contract_payment,
|
||||||
|
equipment_acceptance,
|
||||||
file_check_run,
|
file_check_run,
|
||||||
in_transit_transfer_item,
|
in_transit_transfer_item,
|
||||||
in_transit_transfer_match,
|
in_transit_transfer_match,
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""
|
||||||
|
backend/app/jobs/handlers/equipment_acceptance.py
|
||||||
|
|
||||||
|
用途:执行设备验收预警域后台任务(手动扫描、手动发送)。
|
||||||
|
依赖:jobs.registry、equipment_acceptance.alert_service、jobs.queue.finish_job。
|
||||||
|
逻辑:与周五排程共用 generate_alerts / send_pending_alerts。成功须显式 finish_job,
|
||||||
|
否则 Job 停在 running,超时回收后会重复发送。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from app.jobs.context import JobContext
|
||||||
|
from app.jobs.queue import finish_job
|
||||||
|
from app.jobs.registry import register_handler
|
||||||
|
from app.jobs.types import JobType
|
||||||
|
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
|
||||||
|
|
||||||
|
|
||||||
|
@register_handler(JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN)
|
||||||
|
def run_equipment_acceptance_alert_scan(ctx: JobContext, payload: dict) -> None:
|
||||||
|
"""
|
||||||
|
执行一次设备验收同步并生成待发送记录。
|
||||||
|
|
||||||
|
核心逻辑:不发企业微信。供管理员「扫描预警」入队后由 Worker 执行。
|
||||||
|
Args:
|
||||||
|
ctx: 后台任务上下文。
|
||||||
|
payload: 含通用队列注入的 job_id。
|
||||||
|
Returns:
|
||||||
|
None;结果写入 Job.result_json。
|
||||||
|
"""
|
||||||
|
job_id = int(payload.get("job_id") or 0)
|
||||||
|
result = generate_alerts()
|
||||||
|
ctx.logger.info("equipment acceptance alert scan result=%s", result)
|
||||||
|
if job_id:
|
||||||
|
finish_job(job_id, result=result, message="设备验收预警扫描完成")
|
||||||
|
|
||||||
|
|
||||||
|
@register_handler(JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY)
|
||||||
|
def run_equipment_acceptance_alert_weekly(ctx: JobContext, payload: dict) -> None:
|
||||||
|
"""
|
||||||
|
执行一次设备验收待发送记录的企业微信汇总发送。
|
||||||
|
|
||||||
|
核心逻辑:按收件人发卡片和 Excel,发完后才改发送记录状态。
|
||||||
|
供管理员「发送预警」入队;与周五排程共用同一发送函数。
|
||||||
|
Args:
|
||||||
|
ctx: 后台任务上下文。
|
||||||
|
payload: 含通用队列注入的 job_id。
|
||||||
|
Returns:
|
||||||
|
None;sent/failed 写入 Job.result_json,页面轮询后展示。
|
||||||
|
"""
|
||||||
|
job_id = int(payload.get("job_id") or 0)
|
||||||
|
result = send_pending_alerts()
|
||||||
|
ctx.logger.info("equipment acceptance weekly alert result=%s", result)
|
||||||
|
if job_id:
|
||||||
|
finish_job(job_id, result=result, message="设备验收预警发送完成")
|
||||||
@@ -109,6 +109,23 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
|||||||
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
|
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
|
||||||
job_type=job_type,
|
job_type=job_type,
|
||||||
)
|
)
|
||||||
|
equipment_acceptance_types = (
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN,
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY,
|
||||||
|
)
|
||||||
|
if {item.value for item in equipment_acceptance_types} & allowed_types:
|
||||||
|
from app.jobs.queue import recover_stale_jobs
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
|
# 设备验收发送可能要给很多收件人发企微,超时与合同付款周汇总同级。
|
||||||
|
for job_type in equipment_acceptance_types:
|
||||||
|
if job_type.value not in allowed_types:
|
||||||
|
continue
|
||||||
|
recover_stale_jobs(
|
||||||
|
domain="equipment_acceptance",
|
||||||
|
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
|
||||||
|
job_type=job_type,
|
||||||
|
)
|
||||||
|
|
||||||
# [STEP 2] 按队列优先级 claim
|
# [STEP 2] 按队列优先级 claim
|
||||||
for name in queue_names:
|
for name in queue_names:
|
||||||
@@ -149,13 +166,22 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
|||||||
)
|
)
|
||||||
if job:
|
if job:
|
||||||
return _normalize_generic_job(job)
|
return _normalize_generic_job(job)
|
||||||
# file-check / 企微通讯录同步与排程共用 schedule worker,但 domain 不同
|
# file-check / 企微通讯录同步 / 设备验收手动扫描发送与排程共用 schedule worker
|
||||||
job = claim_next_job(
|
job = claim_next_job(
|
||||||
domain=None,
|
domain=None,
|
||||||
job_types=[JobType.FILE_CHECK_RUN, JobType.WECOM_DIRECTORY_SYNC],
|
job_types=[JobType.FILE_CHECK_RUN, JobType.WECOM_DIRECTORY_SYNC],
|
||||||
)
|
)
|
||||||
if job:
|
if job:
|
||||||
return _normalize_generic_job(job)
|
return _normalize_generic_job(job)
|
||||||
|
job = claim_next_job(
|
||||||
|
domain="equipment_acceptance",
|
||||||
|
job_types=[
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_SCAN,
|
||||||
|
JobType.EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
if job:
|
||||||
|
return _normalize_generic_job(job)
|
||||||
elif name == 'transfer':
|
elif name == 'transfer':
|
||||||
# 在途调拨域:预检/票级执行/行级任务共用 domain="in_transit_transfer"
|
# 在途调拨域:预检/票级执行/行级任务共用 domain="in_transit_transfer"
|
||||||
# (与 execution_service 入队口径一致);缺此分支时 transfer worker
|
# (与 execution_service 入队口径一致);缺此分支时 transfer worker
|
||||||
|
|||||||
@@ -42,6 +42,9 @@ class JobType(StrEnum):
|
|||||||
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
|
CONTRACT_PAYMENT_SYNC = 'contract_payment_sync'
|
||||||
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
|
CONTRACT_PAYMENT_ALERT = 'contract_payment_alert'
|
||||||
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
|
CONTRACT_PAYMENT_ALERT_WEEKLY = 'contract_payment_alert_weekly'
|
||||||
|
# 设备验收预警:管理员手动扫描 / 发送入队,由 schedule worker 执行,避免 HTTP 504。
|
||||||
|
EQUIPMENT_ACCEPTANCE_ALERT_SCAN = 'equipment_acceptance_alert_scan'
|
||||||
|
EQUIPMENT_ACCEPTANCE_ALERT_WEEKLY = 'equipment_acceptance_alert_weekly'
|
||||||
# 在途仓自动调拨:文件准备 + 只读匹配(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
# 在途仓自动调拨:文件准备 + 只读匹配(Phase 1);执行 Run/Item 在 Phase 2 注册。
|
||||||
TRANSFER_MATCH = 'in_transit_transfer_match'
|
TRANSFER_MATCH = 'in_transit_transfer_match'
|
||||||
TRANSFER_RUN = 'in_transit_transfer_run'
|
TRANSFER_RUN = 'in_transit_transfer_run'
|
||||||
@@ -84,7 +87,13 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
|||||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||||
}),
|
}),
|
||||||
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
|
||||||
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
|
'schedule': frozenset({
|
||||||
|
'schedule_run',
|
||||||
|
'file_check_run',
|
||||||
|
'wecom_directory_sync',
|
||||||
|
'equipment_acceptance_alert_scan',
|
||||||
|
'equipment_acceptance_alert_weekly',
|
||||||
|
}),
|
||||||
'transfer': frozenset({
|
'transfer': frozenset({
|
||||||
'in_transit_transfer_match', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
'in_transit_transfer_match', 'in_transit_transfer_run', 'in_transit_transfer_item',
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -9,8 +9,15 @@ backend/app/models/__init__.py
|
|||||||
|
|
||||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||||
from app.models.base import Base, user_agent_permissions
|
from app.models.base import Base, user_agent_permissions
|
||||||
from app.models.permission_role import PermissionRole, permission_role_agents
|
from app.models.permission_role import PermissionRole, permission_role_agents, user_permission_roles
|
||||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
from app.models.chat import (
|
||||||
|
ChatLog,
|
||||||
|
ChatSession,
|
||||||
|
ChatToolRun,
|
||||||
|
Feedback,
|
||||||
|
GeneralFeedback,
|
||||||
|
GeneralFeedbackImage,
|
||||||
|
)
|
||||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||||
from app.models.department import Department
|
from app.models.department import Department
|
||||||
from app.models.linked_service import LinkedService
|
from app.models.linked_service import LinkedService
|
||||||
@@ -267,6 +274,7 @@ __all__ = [
|
|||||||
'Base',
|
'Base',
|
||||||
'user_agent_permissions',
|
'user_agent_permissions',
|
||||||
'permission_role_agents',
|
'permission_role_agents',
|
||||||
|
'user_permission_roles',
|
||||||
'PermissionRole',
|
'PermissionRole',
|
||||||
'ZlLanguage',
|
'ZlLanguage',
|
||||||
'Department',
|
'Department',
|
||||||
@@ -280,6 +288,7 @@ __all__ = [
|
|||||||
'ChatToolRun',
|
'ChatToolRun',
|
||||||
'Feedback',
|
'Feedback',
|
||||||
'GeneralFeedback',
|
'GeneralFeedback',
|
||||||
|
'GeneralFeedbackImage',
|
||||||
'PermissionRequest',
|
'PermissionRequest',
|
||||||
'QuickQuestion',
|
'QuickQuestion',
|
||||||
'FaqHotCandidate',
|
'FaqHotCandidate',
|
||||||
|
|||||||
@@ -135,3 +135,22 @@ class GeneralFeedback(Base):
|
|||||||
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
# 关闭时间:记录何时被处理/关闭,用于「本月已关闭」统计
|
||||||
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
# 反馈附件截图列表:按 sort_order 排序;级联删除随反馈一并移除
|
||||||
|
images: Mapped[list['GeneralFeedbackImage']] = relationship(
|
||||||
|
order_by='GeneralFeedbackImage.sort_order', cascade='all, delete-orphan'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class GeneralFeedbackImage(Base):
|
||||||
|
"""
|
||||||
|
通用意见反馈附件表
|
||||||
|
用途:关联 general_feedbacks 与 file_assets,一条反馈可带多张截图;asset_id 唯一,一图只挂一条反馈
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'general_feedback_images'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
feedback_id: Mapped[int] = mapped_column(ForeignKey('general_feedbacks.id'), index=True)
|
||||||
|
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), unique=True)
|
||||||
|
sort_order: Mapped[int] = mapped_column(default=0)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
@@ -1,27 +1,40 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/models/department.py
|
backend/app/models/department.py
|
||||||
|
|
||||||
用途:部门组织模型。
|
用途:部门组织模型(parent_id 邻接表树形结构,对应 OA 组织架构)。
|
||||||
依赖:models.base.Base。
|
依赖:models.base.Base。
|
||||||
|
逻辑:parent_id 自关联构成部门树;sort_order 为同级排序(对应 ERP HRAO hrao09 阶层序号),
|
||||||
|
is_hidden 对应 hrao08「在组织框架图中显示否」。树的组装与校验在 services/admin/department_service。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
||||||
from sqlalchemy import String, Text
|
from sqlalchemy import Boolean, ForeignKey, String, Text
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||||
|
|
||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
|
|
||||||
|
|
||||||
class Department(Base):
|
class Department(Base):
|
||||||
"""部门表:存储公司部门列表。"""
|
"""部门表:存储公司部门树(parent_id 邻接表)。"""
|
||||||
|
|
||||||
__tablename__ = 'departments'
|
__tablename__ = 'departments'
|
||||||
|
|
||||||
id: Mapped[int] = mapped_column(primary_key=True)
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
name: Mapped[str] = mapped_column(String(100), unique=True)
|
# 树形结构下 name 仅要求「同一上级下不重名」(由 department_service 校验),不再全局唯一,
|
||||||
|
# 以支持多公司存在同名部门(如各公司均有「管理部」)。
|
||||||
|
name: Mapped[str] = mapped_column(String(100))
|
||||||
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
code: Mapped[Optional[str]] = mapped_column(String(50), unique=True)
|
||||||
company: Mapped[Optional[str]] = mapped_column(String(100))
|
company: Mapped[Optional[str]] = mapped_column(String(100))
|
||||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||||
|
# 上级部门主键;None 表示顶级部门(树顶公司层由前端按 company 字段虚拟分组,不入库)
|
||||||
|
parent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('departments.id'), nullable=True)
|
||||||
|
# 同级排序号(升序),对应 ERP hrao09 部门阶层序号
|
||||||
|
sort_order: Mapped[int] = mapped_column(default=0, server_default='0', nullable=False)
|
||||||
|
# 是否在组织树中隐藏(对应 ERP hrao08「在组织框架图中显示否」;管理端仍可见并打标)
|
||||||
|
is_hidden: Mapped[bool] = mapped_column(Boolean, default=False, server_default='false', nullable=False)
|
||||||
|
|
||||||
|
# 上级部门;children 由 backref 提供,供 service 组装树
|
||||||
|
parent: Mapped[Optional['Department']] = relationship(remote_side=[id], backref='children')
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
"""
|
"""
|
||||||
models/permission_role.py
|
models/permission_role.py
|
||||||
|
|
||||||
用途:可配置权限组(角色包)及角色与 Agent 的授权关系。
|
用途:可配置权限组(角色包)、角色与 Agent、用户与角色的授权关系。
|
||||||
依赖:models.base.Base、agents / 无直接 User FK(成员仍写在 users.role)。
|
依赖:models.base.Base、agents、users。
|
||||||
逻辑:Admin 角色配置读写本表;运行时按 users.role=code 取包,再同步到 user_agent_permissions。
|
逻辑:Admin 角色配置读写本表;一个用户可挂多个业务角色,经 user_permission_roles 关联。
|
||||||
|
users.role 只保留排序最前的主角色,供旧查询兼容;运行时按全部角色取并集后再同步到 user_agent_permissions。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -24,6 +25,12 @@ permission_role_agents = db.Table(
|
|||||||
db.Column('agent_id', ForeignKey('agents.id', ondelete='CASCADE'), primary_key=True),
|
db.Column('agent_id', ForeignKey('agents.id', ondelete='CASCADE'), primary_key=True),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
user_permission_roles = db.Table(
|
||||||
|
'user_permission_roles',
|
||||||
|
db.Column('user_id', ForeignKey('users.id', ondelete='CASCADE'), primary_key=True),
|
||||||
|
db.Column('role_id', ForeignKey('permission_roles.id', ondelete='CASCADE'), primary_key=True),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class PermissionRole(Base):
|
class PermissionRole(Base):
|
||||||
"""权限组:可用应用入口 + 应用内能力。"""
|
"""权限组:可用应用入口 + 应用内能力。"""
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ backend/app/models/user.py
|
|||||||
|
|
||||||
用途:用户账户、首页偏好、登录审计相关模型。
|
用途:用户账户、首页偏好、登录审计相关模型。
|
||||||
依赖:models.base(Base、user_agent_permissions);功能权限优先读 permission_roles。
|
依赖:models.base(Base、user_agent_permissions);功能权限优先读 permission_roles。
|
||||||
逻辑:User 与 Agent 多对多经 user_agent_permissions;角色包启用后个人 feature_permissions 仅作兼容覆盖。
|
逻辑:User 与 Agent 多对多经 user_agent_permissions;与权限组多对多经 user_permission_roles。
|
||||||
|
users.role 是主角色。已挂多个业务角色时,功能权限与应用入口取并集。
|
||||||
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
|
is_platform_admin() 读权限组标记,未种子时回退 role=admin。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -17,6 +18,7 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship
|
|||||||
from werkzeug.security import check_password_hash, generate_password_hash
|
from werkzeug.security import check_password_hash, generate_password_hash
|
||||||
|
|
||||||
from app.models.base import Base, user_agent_permissions
|
from app.models.base import Base, user_agent_permissions
|
||||||
|
from app.models.permission_role import user_permission_roles
|
||||||
|
|
||||||
|
|
||||||
class UserHomepageConfig(Base):
|
class UserHomepageConfig(Base):
|
||||||
@@ -77,6 +79,10 @@ class User(Base):
|
|||||||
secondary=user_agent_permissions,
|
secondary=user_agent_permissions,
|
||||||
back_populates='users',
|
back_populates='users',
|
||||||
)
|
)
|
||||||
|
permission_roles: Mapped[List['PermissionRole']] = relationship(
|
||||||
|
'PermissionRole',
|
||||||
|
secondary=user_permission_roles,
|
||||||
|
)
|
||||||
|
|
||||||
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
reset_token: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||||
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
reset_token_expiry: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||||
@@ -118,7 +124,7 @@ class User(Base):
|
|||||||
返回当前用户的有效功能权限。
|
返回当前用户的有效功能权限。
|
||||||
|
|
||||||
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
|
||||||
核心逻辑:已配置 permission_roles 时完全由权限组计算;否则先按写死角色生成默认值,再用用户 JSON 覆盖。
|
核心逻辑:已配置 permission_roles 时按该用户全部角色取并集;否则先按写死角色生成默认值,再用用户 JSON 覆盖。
|
||||||
输出约束:仅返回布尔型权限键。
|
输出约束:仅返回布尔型权限键。
|
||||||
"""
|
"""
|
||||||
from app.services.permission_roles.service import effective_feature_permissions
|
from app.services.permission_roles.service import effective_feature_permissions
|
||||||
@@ -164,13 +170,14 @@ class User(Base):
|
|||||||
return self.has_feature_permission('training_hr_manage')
|
return self.has_feature_permission('training_hr_manage')
|
||||||
|
|
||||||
def client_auth_fields(self) -> dict:
|
def client_auth_fields(self) -> dict:
|
||||||
"""登录态/首页共用的角色与功能权限字段。"""
|
"""登录态/首页共用的角色与功能权限字段。多个业务角色的名称用顿号拼接。"""
|
||||||
from app.services.permission_roles.service import list_role_name_map
|
from app.services.permission_roles.service import role_auth_payload
|
||||||
|
|
||||||
names = list_role_name_map()
|
payload = role_auth_payload(self)
|
||||||
return {
|
return {
|
||||||
'is_platform_admin': self.is_platform_admin(),
|
'is_platform_admin': self.is_platform_admin(),
|
||||||
'role_name': names.get(self.role) or self.role,
|
'role_name': payload['role_name'],
|
||||||
|
'role_codes': payload['role_codes'],
|
||||||
'feature_permissions': self.get_feature_permissions(),
|
'feature_permissions': self.get_feature_permissions(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,59 +1,206 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/admin/department_service.py
|
backend/app/services/admin/department_service.py
|
||||||
|
|
||||||
用途:管理端部门 CRUD 业务编排。
|
用途:管理端部门树 CRUD 业务编排(parent_id 邻接表)。
|
||||||
依赖:models.Department、app.core.errors。
|
依赖:models.Department、models.User、app.core.errors。
|
||||||
逻辑:由 api/admin/departments.py 调用。
|
逻辑:api/admin/departments.py 调用;成员归属沿用 users.department 文本按部门名关联;
|
||||||
|
树顶公司层不入库,由前端按 company 字段虚拟分组。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from typing import Any
|
from collections import defaultdict
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import NotFoundError, ValidationError
|
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||||
from app.models import Department, User
|
from app.models import Department, User
|
||||||
|
|
||||||
|
# 业务错误码:与前端 locales/*/errors.json 的 codes 段一一对应
|
||||||
|
ERR_NAME_REQUIRED = 'DEPT.NAME_REQUIRED'
|
||||||
|
ERR_PARENT_INVALID = 'DEPT.PARENT_INVALID'
|
||||||
|
ERR_NAME_EXISTS = 'DEPT.NAME_EXISTS'
|
||||||
|
ERR_CODE_EXISTS = 'DEPT.CODE_EXISTS'
|
||||||
|
ERR_CYCLE_FORBIDDEN = 'DEPT.CYCLE_FORBIDDEN'
|
||||||
|
ERR_HAS_CHILDREN = 'DEPT.HAS_CHILDREN'
|
||||||
|
ERR_HAS_MEMBERS = 'DEPT.HAS_MEMBERS'
|
||||||
|
|
||||||
|
|
||||||
def serialize_department(dept: Department) -> dict:
|
def serialize_department(dept: Department) -> dict:
|
||||||
"""部门 ORM → API dict。"""
|
"""部门 ORM → API dict(平铺行,供部门下拉等旧消费方兼容)。"""
|
||||||
return {
|
return {
|
||||||
'id': dept.id,
|
'id': dept.id,
|
||||||
'name': dept.name,
|
'name': dept.name,
|
||||||
'code': dept.code,
|
'code': dept.code,
|
||||||
'company': dept.company,
|
'company': dept.company,
|
||||||
'description': dept.description,
|
'description': dept.description,
|
||||||
|
'parent_id': dept.parent_id,
|
||||||
|
'sort_order': int(dept.sort_order or 0),
|
||||||
|
'is_hidden': bool(dept.is_hidden),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def list_departments() -> list[dict]:
|
def _member_count_by_name() -> dict[str, int]:
|
||||||
"""返回全部部门(按 name 升序)。"""
|
|
||||||
rows = (
|
|
||||||
db.session.query(Department, func.count(User.id).label('member_count'))
|
|
||||||
.outerjoin(User, User.department == Department.name)
|
|
||||||
.group_by(Department.id)
|
|
||||||
.order_by(Department.name.asc())
|
|
||||||
.all()
|
|
||||||
)
|
|
||||||
return [{**serialize_department(dept), 'member_count': int(member_count or 0)} for dept, member_count in rows]
|
|
||||||
|
|
||||||
|
|
||||||
def list_department_members(dept_id: int) -> dict:
|
|
||||||
"""
|
"""
|
||||||
查询指定部门的员工名单。
|
全员按部门名聚合计数。
|
||||||
|
核心逻辑:users.department 为文本字段,一次 GROUP BY 供整棵树复用,避免逐节点查库。
|
||||||
|
"""
|
||||||
|
rows = db.session.query(User.department, func.count(User.id)).group_by(User.department).all()
|
||||||
|
return {name: int(cnt) for name, cnt in rows if name}
|
||||||
|
|
||||||
[STEP 1] 通过部门主键读取部门名称。
|
|
||||||
[STEP 2] 复用现有 users.department 文本关联查询成员。
|
def _sibling_sort_key(node: dict) -> tuple:
|
||||||
[STEP 3] 返回人数与脱敏后的管理端成员资料。
|
"""同级排序:sort_order 升序 → 编码 → 名称(编码可能为空,排最后)。"""
|
||||||
|
return (node['sort_order'], node['code'] or '', node['name'])
|
||||||
|
|
||||||
|
|
||||||
|
def list_departments() -> list[dict]:
|
||||||
|
"""平铺部门列表(保持旧接口兼容),按公司 → 同级排序号 → 名称排序。"""
|
||||||
|
depts = db.session.query(Department).all()
|
||||||
|
counts = _member_count_by_name()
|
||||||
|
depts.sort(key=lambda d: (d.company or '', d.sort_order or 0, d.code or '', d.name))
|
||||||
|
return [{**serialize_department(d), 'member_count': counts.get(d.name, 0)} for d in depts]
|
||||||
|
|
||||||
|
|
||||||
|
def list_department_tree() -> list[dict]:
|
||||||
|
"""
|
||||||
|
返回完整部门树(children 嵌套,成员数含下级递归汇总)。
|
||||||
|
|
||||||
|
[STEP 1] 一次取全表部门 + 一次按部门名聚合人数。
|
||||||
|
[STEP 2] 按 parent_id 挂 children;父缺失或成环的脏数据按顶级处理(防御)。
|
||||||
|
[STEP 3] 后序遍历汇总 total_member_count(本部门 + 全部下级)。
|
||||||
|
[STEP 4] 同级按 sort_order → 编码 → 名称排序后输出根节点数组。
|
||||||
|
"""
|
||||||
|
depts = db.session.query(Department).all()
|
||||||
|
counts = _member_count_by_name()
|
||||||
|
dept_by_id = {d.id: d for d in depts}
|
||||||
|
nodes = {
|
||||||
|
d.id: {
|
||||||
|
**serialize_department(d),
|
||||||
|
'member_count': counts.get(d.name, 0),
|
||||||
|
'total_member_count': counts.get(d.name, 0),
|
||||||
|
'children': [],
|
||||||
|
}
|
||||||
|
for d in depts
|
||||||
|
}
|
||||||
|
|
||||||
|
def _is_orphan(d: Department) -> bool:
|
||||||
|
"""父链断裂或成环时按顶级处理,避免历史脏数据导致死循环。"""
|
||||||
|
seen: set[int] = set()
|
||||||
|
cur = d
|
||||||
|
while cur.parent_id:
|
||||||
|
if cur.parent_id not in dept_by_id or cur.parent_id in seen:
|
||||||
|
return True
|
||||||
|
seen.add(cur.parent_id)
|
||||||
|
cur = dept_by_id[cur.parent_id]
|
||||||
|
return False
|
||||||
|
|
||||||
|
roots: list[dict] = []
|
||||||
|
for d in depts:
|
||||||
|
node = nodes[d.id]
|
||||||
|
parent_node = nodes.get(d.parent_id) if d.parent_id else None
|
||||||
|
if parent_node is not None and not _is_orphan(d):
|
||||||
|
parent_node['children'].append(node)
|
||||||
|
else:
|
||||||
|
roots.append(node)
|
||||||
|
|
||||||
|
def _summarize(node: dict) -> int:
|
||||||
|
"""后序汇总:total_member_count = 本部门 + 直接成员数之和(树已去环,可安全递归)。"""
|
||||||
|
total = node['member_count']
|
||||||
|
for child in node['children']:
|
||||||
|
total += _summarize(child)
|
||||||
|
node['total_member_count'] = total
|
||||||
|
return total
|
||||||
|
|
||||||
|
def _sort_level(level: list[dict]) -> None:
|
||||||
|
level.sort(key=_sibling_sort_key)
|
||||||
|
for n in level:
|
||||||
|
_sort_level(n['children'])
|
||||||
|
|
||||||
|
_sort_level(roots)
|
||||||
|
for r in roots:
|
||||||
|
_summarize(r)
|
||||||
|
return roots
|
||||||
|
|
||||||
|
|
||||||
|
def _subtree_departments(root: Department) -> list[Department]:
|
||||||
|
"""收集 root 的全部下级部门(不含 root 自身;BFS,脏数据由 parent_id 存在性保证收敛)。"""
|
||||||
|
depts = db.session.query(Department).all()
|
||||||
|
by_parent: dict[Optional[int], list[Department]] = defaultdict(list)
|
||||||
|
for d in depts:
|
||||||
|
by_parent[d.parent_id].append(d)
|
||||||
|
out: list[Department] = []
|
||||||
|
stack = [root.id]
|
||||||
|
while stack:
|
||||||
|
current = stack.pop()
|
||||||
|
for child in by_parent.get(current, []):
|
||||||
|
out.append(child)
|
||||||
|
stack.append(child.id)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def list_department_members(
|
||||||
|
dept_id: int,
|
||||||
|
include_descendants: bool = False,
|
||||||
|
keyword: str = '',
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 20,
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
分页查询部门员工名单(OA 组织结构右侧面板口径)。
|
||||||
|
|
||||||
|
[STEP 1] 读取部门;include_descendants=True 时递归收集子树内全部部门名。
|
||||||
|
[STEP 2] 按 users.department 文本 in 部门名集合过滤,keyword 模糊匹配
|
||||||
|
姓名/用户名/工号/邮箱/手机号。
|
||||||
|
[STEP 3] 返回 total 与当前页成员资料(含成员所属部门名,供含下级视图区分)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
dept_id: 部门主键。
|
||||||
|
include_descendants: 是否包含全部下级部门的成员(默认 False)。
|
||||||
|
keyword: 搜索关键词(姓名/工号/邮箱/手机号/用户名 模糊匹配)。
|
||||||
|
page: 页码,从 1 起;非正数按 1 处理。
|
||||||
|
page_size: 每页条数,钳制在 1..100。
|
||||||
|
Returns:
|
||||||
|
{ department, total, page, page_size, members }。
|
||||||
|
Raises:
|
||||||
|
NotFoundError: 部门不存在。
|
||||||
"""
|
"""
|
||||||
dept = db.session.get(Department, dept_id)
|
dept = db.session.get(Department, dept_id)
|
||||||
if not dept:
|
if not dept:
|
||||||
raise NotFoundError('Not found')
|
raise NotFoundError('Department not found')
|
||||||
users = db.session.query(User).filter(User.department == dept.name).order_by(User.real_name.asc(), User.username.asc()).all()
|
if include_descendants:
|
||||||
|
dept_names = [dept.name] + [d.name for d in _subtree_departments(dept)]
|
||||||
|
else:
|
||||||
|
dept_names = [dept.name]
|
||||||
|
|
||||||
|
query = db.session.query(User).filter(User.department.in_(dept_names))
|
||||||
|
kw = (keyword or '').strip()
|
||||||
|
if kw:
|
||||||
|
like = f"%{kw}%"
|
||||||
|
query = query.filter(
|
||||||
|
db.or_(
|
||||||
|
User.real_name.ilike(like),
|
||||||
|
User.username.ilike(like),
|
||||||
|
User.employee_id.ilike(like),
|
||||||
|
User.email.ilike(like),
|
||||||
|
User.phone_number.ilike(like),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
total = query.count()
|
||||||
|
page = max(int(page or 1), 1)
|
||||||
|
page_size = min(max(int(page_size or 20), 1), 100)
|
||||||
|
users = (
|
||||||
|
query.order_by(User.real_name.asc(), User.username.asc())
|
||||||
|
.offset((page - 1) * page_size)
|
||||||
|
.limit(page_size)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
return {
|
return {
|
||||||
'department': serialize_department(dept),
|
'department': serialize_department(dept),
|
||||||
'count': len(users),
|
'total': total,
|
||||||
|
'page': page,
|
||||||
|
'page_size': page_size,
|
||||||
'members': [
|
'members': [
|
||||||
{
|
{
|
||||||
'id': user.id,
|
'id': user.id,
|
||||||
@@ -61,6 +208,8 @@ def list_department_members(dept_id: int) -> dict:
|
|||||||
'real_name': user.real_name,
|
'real_name': user.real_name,
|
||||||
'employee_id': user.employee_id,
|
'employee_id': user.employee_id,
|
||||||
'email': user.email,
|
'email': user.email,
|
||||||
|
'phone_number': user.phone_number,
|
||||||
|
'department': user.department,
|
||||||
'status': user.status,
|
'status': user.status,
|
||||||
}
|
}
|
||||||
for user in users
|
for user in users
|
||||||
@@ -68,25 +217,104 @@ def list_department_members(dept_id: int) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_parent(parent_id: Any) -> Optional[Department]:
|
||||||
|
"""校验上级部门存在性;None/空表示顶级。返回上级 ORM 或 None。"""
|
||||||
|
if parent_id in (None, ''):
|
||||||
|
return None
|
||||||
|
parent = db.session.get(Department, int(parent_id))
|
||||||
|
if not parent:
|
||||||
|
raise ValidationError('Parent department not found', code=ERR_PARENT_INVALID)
|
||||||
|
return parent
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_parent_change(dept: Department, new_parent_id: Any) -> Optional[Department]:
|
||||||
|
"""
|
||||||
|
校验修改上级的合法性:上级必须存在,且不能是自己或自己的子孙(防成环)。
|
||||||
|
[STEP 1] 沿新上级逐层向上走。
|
||||||
|
[STEP 2] 途中遇到本部门 id 即说明会把子树挂到自己下面,抛 CYCLE_FORBIDDEN。
|
||||||
|
"""
|
||||||
|
parent = _validate_parent(new_parent_id)
|
||||||
|
if parent is None:
|
||||||
|
return None
|
||||||
|
if parent.id == dept.id:
|
||||||
|
raise ValidationError('Parent cannot be itself or its descendant', code=ERR_CYCLE_FORBIDDEN)
|
||||||
|
seen = {dept.id}
|
||||||
|
cur_id: Optional[int] = parent.parent_id
|
||||||
|
while cur_id:
|
||||||
|
if cur_id in seen:
|
||||||
|
raise ValidationError('Parent cannot be itself or its descendant', code=ERR_CYCLE_FORBIDDEN)
|
||||||
|
seen.add(cur_id)
|
||||||
|
cursor = db.session.get(Department, cur_id)
|
||||||
|
if not cursor:
|
||||||
|
break
|
||||||
|
cur_id = cursor.parent_id
|
||||||
|
return parent
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_sibling_name(
|
||||||
|
name: str,
|
||||||
|
parent_id: Optional[int],
|
||||||
|
company: Optional[str] = None,
|
||||||
|
exclude_id: Optional[int] = None,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
同级查重:同一上级下 name 唯一(树形下允许不同分支同名)。
|
||||||
|
顶级部门(parent_id 为空)按 company 分桶查重——树顶公司层为虚拟分组,
|
||||||
|
两家公司的顶级部门允许同名(如各公司均有「管理部」)。
|
||||||
|
"""
|
||||||
|
query = db.session.query(Department).filter(Department.name == name)
|
||||||
|
if parent_id:
|
||||||
|
query = query.filter(Department.parent_id == parent_id)
|
||||||
|
else:
|
||||||
|
query = query.filter(Department.parent_id.is_(None))
|
||||||
|
query = query.filter(Department.company == company) if company else query.filter(Department.company.is_(None))
|
||||||
|
if exclude_id:
|
||||||
|
query = query.filter(Department.id != exclude_id)
|
||||||
|
if query.first():
|
||||||
|
raise ValidationError('Sibling department name exists', code=ERR_NAME_EXISTS)
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_str(value: Any) -> str:
|
||||||
|
return (value or '').strip() if isinstance(value, str) else ''
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_int(value: Any) -> int:
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
def create_department(data: dict[str, Any]) -> dict:
|
def create_department(data: dict[str, Any]) -> dict:
|
||||||
"""
|
"""
|
||||||
创建部门。
|
创建部门。
|
||||||
|
|
||||||
|
[STEP 1] 校验名称必填、上级存在、同级不重名、编码全局唯一。
|
||||||
|
[STEP 2] 公司未填时继承上级部门 company(树顶公司分组依赖该字段)。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
{ id, name }。
|
{ id, name }。
|
||||||
Raises:
|
Raises:
|
||||||
ValidationError: name 缺失或 name/code 重复。
|
ValidationError: NAME_REQUIRED / PARENT_INVALID / NAME_EXISTS / CODE_EXISTS。
|
||||||
"""
|
"""
|
||||||
if not data.get('name'):
|
name = _clean_str(data.get('name'))
|
||||||
raise ValidationError('Name is required')
|
if not name:
|
||||||
if db.session.query(Department).filter_by(name=data['name']).first():
|
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
||||||
raise ValidationError('Name exists')
|
parent_id = data.get('parent_id')
|
||||||
if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first():
|
parent = _validate_parent(parent_id)
|
||||||
raise ValidationError('Code exists')
|
company = _clean_str(data.get('company')) or (parent.company if parent else None)
|
||||||
|
_validate_sibling_name(name, parent.id if parent else None, company=company)
|
||||||
|
code = _clean_str(data.get('code')) or None
|
||||||
|
if code and db.session.query(Department).filter_by(code=code).first():
|
||||||
|
raise ValidationError('Department code exists', code=ERR_CODE_EXISTS)
|
||||||
dept = Department(
|
dept = Department(
|
||||||
name=data['name'],
|
name=name,
|
||||||
code=data.get('code'),
|
code=code,
|
||||||
company=data.get('company'),
|
company=company,
|
||||||
description=data.get('description'),
|
description=_clean_str(data.get('description')) or None,
|
||||||
|
parent_id=parent.id if parent else None,
|
||||||
|
sort_order=_clean_int(data.get('sort_order')),
|
||||||
|
is_hidden=bool(data.get('is_hidden')),
|
||||||
)
|
)
|
||||||
db.session.add(dept)
|
db.session.add(dept)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -95,34 +323,64 @@ def create_department(data: dict[str, Any]) -> dict:
|
|||||||
|
|
||||||
def update_department(dept_id: int, data: dict[str, Any]) -> None:
|
def update_department(dept_id: int, data: dict[str, Any]) -> None:
|
||||||
"""
|
"""
|
||||||
更新部门字段。
|
更新部门字段(含上级转移、同级排序、隐藏标记)。
|
||||||
|
|
||||||
|
[STEP 1] 名称变更时按「变更后的上级」做同级查重。
|
||||||
|
[STEP 2] 上级变更时校验存在性并防成环。
|
||||||
|
[STEP 3] 编码变更时全局唯一校验。
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
NotFoundError: 部门不存在。
|
NotFoundError: 部门不存在。
|
||||||
ValidationError: name/code 与其它记录冲突。
|
ValidationError: NAME_EXISTS / PARENT_INVALID / CYCLE_FORBIDDEN / CODE_EXISTS。
|
||||||
"""
|
"""
|
||||||
dept = db.session.get(Department, dept_id)
|
dept = db.session.get(Department, dept_id)
|
||||||
if not dept:
|
if not dept:
|
||||||
raise NotFoundError('Not found')
|
raise NotFoundError('Department not found')
|
||||||
if 'name' in data:
|
|
||||||
if db.session.query(Department).filter(Department.name == data['name'], Department.id != dept_id).first():
|
if 'parent_id' in data:
|
||||||
raise ValidationError('Name exists')
|
parent = _validate_parent_change(dept, data['parent_id'])
|
||||||
dept.name = data['name']
|
dept.parent_id = parent.id if parent else None
|
||||||
if 'code' in data:
|
|
||||||
if data['code'] and db.session.query(Department).filter(
|
|
||||||
Department.code == data['code'], Department.id != dept_id
|
|
||||||
).first():
|
|
||||||
raise ValidationError('Code exists')
|
|
||||||
dept.code = data['code']
|
|
||||||
if 'company' in data:
|
if 'company' in data:
|
||||||
dept.company = data['company']
|
dept.company = _clean_str(data.get('company')) or None
|
||||||
|
|
||||||
|
if 'name' in data:
|
||||||
|
name = _clean_str(data.get('name'))
|
||||||
|
if not name:
|
||||||
|
raise ValidationError('Department name is required', code=ERR_NAME_REQUIRED)
|
||||||
|
_validate_sibling_name(name, dept.parent_id, company=dept.company, exclude_id=dept_id)
|
||||||
|
dept.name = name
|
||||||
|
|
||||||
|
if 'code' in data:
|
||||||
|
code = _clean_str(data.get('code')) or None
|
||||||
|
if code and db.session.query(Department).filter(
|
||||||
|
Department.code == code, Department.id != dept_id
|
||||||
|
).first():
|
||||||
|
raise ValidationError('Department code exists', code=ERR_CODE_EXISTS)
|
||||||
|
dept.code = code
|
||||||
|
|
||||||
if 'description' in data:
|
if 'description' in data:
|
||||||
dept.description = data['description']
|
dept.description = _clean_str(data.get('description')) or None
|
||||||
|
if 'sort_order' in data:
|
||||||
|
dept.sort_order = _clean_int(data.get('sort_order'))
|
||||||
|
if 'is_hidden' in data:
|
||||||
|
dept.is_hidden = bool(data.get('is_hidden'))
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
def delete_department(dept_id: int) -> None:
|
def delete_department(dept_id: int) -> None:
|
||||||
"""删除部门(不存在时静默成功)。"""
|
"""
|
||||||
|
删除部门。
|
||||||
|
Raises:
|
||||||
|
ConflictError: 存在下级部门(HAS_CHILDREN)或名下仍有员工(HAS_MEMBERS)时禁止删除。
|
||||||
|
"""
|
||||||
dept = db.session.get(Department, dept_id)
|
dept = db.session.get(Department, dept_id)
|
||||||
if dept:
|
if not dept:
|
||||||
db.session.delete(dept)
|
return
|
||||||
db.session.commit()
|
if db.session.query(Department).filter(Department.parent_id == dept_id).first():
|
||||||
|
raise ConflictError('Department has child departments', code=ERR_HAS_CHILDREN)
|
||||||
|
if db.session.query(User).filter(User.department == dept.name).first():
|
||||||
|
raise ConflictError('Department still has members', code=ERR_HAS_MEMBERS)
|
||||||
|
db.session.delete(dept)
|
||||||
|
db.session.commit()
|
||||||
@@ -16,8 +16,9 @@ from sqlalchemy import asc, desc, func, or_
|
|||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import NotFoundError
|
from app.core.errors import NotFoundError
|
||||||
from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User
|
from app.models import Agent, ChatLog, Feedback, FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
||||||
from app.models.base import user_agent_permissions
|
from app.models.base import user_agent_permissions
|
||||||
|
from app.services.file_assets.service import read_asset_bytes
|
||||||
|
|
||||||
USAGE_BY_USER_TOP_LIMIT = 50
|
USAGE_BY_USER_TOP_LIMIT = 50
|
||||||
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
|
APPLICATION_REPORT_PAGE_SIZE_MAX = 100
|
||||||
@@ -36,6 +37,16 @@ USAGE_LOW_AGENT_MAX_CHATS = 2
|
|||||||
# 运营提醒:低使用应用最多返回条数
|
# 运营提醒:低使用应用最多返回条数
|
||||||
USAGE_LOW_AGENT_LIST_LIMIT = 5
|
USAGE_LOW_AGENT_LIST_LIMIT = 5
|
||||||
|
|
||||||
|
# 反馈图片响应 Content-Type 白名单:按资产扩展名固定响应类型。
|
||||||
|
# [SECURITY] 存储 mime_type 来自上传时客户端 multipart 头,不可信;代理内联输出时
|
||||||
|
# 若原样透传可被伪造为 text/html 等,构成存储型 XSS 面,故一律按扩展名收敛。
|
||||||
|
FEEDBACK_IMAGE_CONTENT_TYPES = {
|
||||||
|
'png': 'image/png',
|
||||||
|
'jpg': 'image/jpeg',
|
||||||
|
'jpeg': 'image/jpeg',
|
||||||
|
'webp': 'image/webp',
|
||||||
|
}
|
||||||
|
|
||||||
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
# 使用分析时间范围:key → 回溯天数(与前端下拉选项一致)
|
||||||
USAGE_RANGE_DAYS = {
|
USAGE_RANGE_DAYS = {
|
||||||
'7d': 7,
|
'7d': 7,
|
||||||
@@ -557,6 +568,39 @@ def _apply_general_feedback_filters(query, query_params: dict[str, str]):
|
|||||||
return query
|
return query
|
||||||
|
|
||||||
|
|
||||||
|
def _attach_general_feedback_images(rows: list[dict], feedback_ids: list[int]) -> None:
|
||||||
|
"""
|
||||||
|
批量回填每行 images 元数据(单查询,按 sort_order 排序),无图行置空列表。
|
||||||
|
|
||||||
|
用途:通用反馈报表行内附图元数据(前端缩略图入口);单条 IN 查询避免 N+1。
|
||||||
|
逻辑:GeneralFeedbackImage join FileAsset 按 feedback_id 批量取行,
|
||||||
|
按 (sort_order, id) 升序分组后写回各行的 'images' 键。
|
||||||
|
Args:
|
||||||
|
rows: list_general_feedbacks_report 构建出的行字典列表(含 'id' 键),原地修改。
|
||||||
|
feedback_ids: rows 对应的反馈 ID 列表。
|
||||||
|
"""
|
||||||
|
if not feedback_ids:
|
||||||
|
return
|
||||||
|
records = (
|
||||||
|
db.session.query(GeneralFeedbackImage, FileAsset)
|
||||||
|
.join(FileAsset, FileAsset.id == GeneralFeedbackImage.asset_id)
|
||||||
|
.filter(GeneralFeedbackImage.feedback_id.in_(feedback_ids))
|
||||||
|
.order_by(asc(GeneralFeedbackImage.sort_order), asc(GeneralFeedbackImage.id))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
grouped: dict[int, list[dict]] = {}
|
||||||
|
for image, asset in records:
|
||||||
|
grouped.setdefault(int(image.feedback_id), []).append({
|
||||||
|
'image_id': int(image.id),
|
||||||
|
'asset_no': asset.asset_no,
|
||||||
|
'original_filename': asset.original_filename,
|
||||||
|
'file_size': int(asset.file_size or 0),
|
||||||
|
'sort_order': int(image.sort_order or 0),
|
||||||
|
})
|
||||||
|
for row in rows:
|
||||||
|
row['images'] = grouped.get(int(row['id']), [])
|
||||||
|
|
||||||
|
|
||||||
def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
||||||
"""通用反馈列表(报表页)。"""
|
"""通用反馈列表(报表页)。"""
|
||||||
query = (
|
query = (
|
||||||
@@ -586,9 +630,48 @@ def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]:
|
|||||||
row['real_name'] = real_name
|
row['real_name'] = real_name
|
||||||
row['department'] = department
|
row['department'] = department
|
||||||
rows.append(row)
|
rows.append(row)
|
||||||
|
_attach_general_feedback_images(rows, [row['id'] for row in rows])
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def get_general_feedback_image_payload(feedback_id: int, image_id: int) -> dict:
|
||||||
|
"""
|
||||||
|
读取反馈图片字节(管理端代理输出,不走 MinIO 预签名,见 spec D6)。
|
||||||
|
|
||||||
|
用途:管理端报表页内联预览反馈截图;由 api/admin/reports.py 的 raw 路由调用。
|
||||||
|
逻辑:校验 image 归属该 feedback → 校验资产未删除 → read_asset_bytes 读字节
|
||||||
|
(内部再拦过期/已删除的 FILE_ASSET.*),错配一律按不存在处理避免探测他人资产。
|
||||||
|
响应 Content-Type 按扩展名白名单(FEEDBACK_IMAGE_CONTENT_TYPES)固定,
|
||||||
|
不透传存储 mime(其来自客户端上传头,不可信)。
|
||||||
|
Args:
|
||||||
|
feedback_id: 反馈 ID;image 必须归属该反馈,错配按不存在处理。
|
||||||
|
image_id: 反馈附件图片 ID。
|
||||||
|
Returns:
|
||||||
|
{'data': bytes, 'mime_type': str, 'filename': str};mime_type 由扩展名白名单决定,
|
||||||
|
未知扩展名(历史/边界行)降级 application/octet-stream。
|
||||||
|
Raises:
|
||||||
|
NotFoundError: code=FEEDBACK.IMAGE_NOT_FOUND——image 不存在、不属于该反馈或资产已删除。
|
||||||
|
"""
|
||||||
|
image = (
|
||||||
|
db.session.query(GeneralFeedbackImage)
|
||||||
|
.filter_by(id=image_id, feedback_id=feedback_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if image is None:
|
||||||
|
raise NotFoundError(code='FEEDBACK.IMAGE_NOT_FOUND', message='反馈图片不存在')
|
||||||
|
asset = db.session.get(FileAsset, image.asset_id)
|
||||||
|
if asset is None or asset.deleted_at is not None:
|
||||||
|
raise NotFoundError(code='FEEDBACK.IMAGE_NOT_FOUND', message='反馈图片不存在')
|
||||||
|
data = read_asset_bytes(asset)
|
||||||
|
# [SECURITY] 提交时仅校验扩展名白名单,存储 mime 仍是客户端自报值;响应类型只能信扩展名
|
||||||
|
mime_type = FEEDBACK_IMAGE_CONTENT_TYPES.get(str(asset.extension or '').lower(), 'application/octet-stream')
|
||||||
|
return {
|
||||||
|
'data': data,
|
||||||
|
'mime_type': mime_type,
|
||||||
|
'filename': asset.original_filename,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def count_general_feedbacks_report(query_params: dict[str, str]) -> dict:
|
def count_general_feedbacks_report(query_params: dict[str, str]) -> dict:
|
||||||
"""通用反馈计数。"""
|
"""通用反馈计数。"""
|
||||||
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id)
|
||||||
|
|||||||
@@ -3,19 +3,22 @@ backend/app/services/admin/user_service.py
|
|||||||
|
|
||||||
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。
|
||||||
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service、permission_roles。
|
依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service、permission_roles。
|
||||||
逻辑:由 api/admin/users.py 调用;权限组启用后创建/改角色只同步角色包,不再按人勾应用。
|
逻辑:由 api/admin/users.py 调用;权限组启用后创建/改角色按角色集合重算并集,不再按人勾应用。
|
||||||
|
提交 roles 时替换该用户的全部业务角色;只提交 role 时改成这一个角色。
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
import re
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import or_
|
||||||
from sqlalchemy.exc import IntegrityError
|
from sqlalchemy.exc import IntegrityError
|
||||||
from sqlalchemy.orm import joinedload
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||||
from app.models import Agent, User
|
from app.models import Agent, User
|
||||||
|
from app.models.permission_role import PermissionRole, user_permission_roles
|
||||||
from app.services.auth import casdoor_service
|
from app.services.auth import casdoor_service
|
||||||
from app.services.permission_roles import service as role_service
|
from app.services.permission_roles import service as role_service
|
||||||
from app.services.user_admin import delete_admin_users
|
from app.services.user_admin import delete_admin_users
|
||||||
@@ -69,15 +72,22 @@ def assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None)
|
|||||||
raise ConflictError(message, code=code, details={'field': field})
|
raise ConflictError(message, code=code, details={'field': field})
|
||||||
|
|
||||||
|
|
||||||
def serialize_admin_user(user: User, role_names: dict[str, str] | None = None) -> dict:
|
def serialize_admin_user(
|
||||||
|
user: User,
|
||||||
|
role_names: dict[str, str] | None = None,
|
||||||
|
assigned: list | None = None,
|
||||||
|
) -> dict:
|
||||||
|
"""管理端用户行。role 是主角色,role_name / role_codes 覆盖全部已挂角色。"""
|
||||||
names = role_names if role_names is not None else role_service.list_role_name_map()
|
names = role_names if role_names is not None else role_service.list_role_name_map()
|
||||||
|
described = role_service.describe_user_roles(user, assigned=assigned, role_names=names)
|
||||||
return {
|
return {
|
||||||
'id': user.id,
|
'id': user.id,
|
||||||
'username': user.username,
|
'username': user.username,
|
||||||
'email': user.email,
|
'email': user.email,
|
||||||
'department': user.department,
|
'department': user.department,
|
||||||
'role': user.role,
|
'role': described['role'],
|
||||||
'role_name': names.get(user.role) or user.role,
|
'role_name': described['role_name'],
|
||||||
|
'role_codes': described['role_codes'],
|
||||||
'is_platform_admin': user.is_platform_admin(),
|
'is_platform_admin': user.is_platform_admin(),
|
||||||
'status': user.status,
|
'status': user.status,
|
||||||
'real_name': user.real_name,
|
'real_name': user.real_name,
|
||||||
@@ -95,12 +105,23 @@ def apply_users_filters(query, query_params: dict[str, str]):
|
|||||||
'username': User.username,
|
'username': User.username,
|
||||||
'email': User.email,
|
'email': User.email,
|
||||||
'department': User.department,
|
'department': User.department,
|
||||||
'role': User.role,
|
|
||||||
'status': User.status,
|
'status': User.status,
|
||||||
'real_name': User.real_name,
|
'real_name': User.real_name,
|
||||||
'employee_id': User.employee_id,
|
'employee_id': User.employee_id,
|
||||||
'phone_number': User.phone_number,
|
'phone_number': User.phone_number,
|
||||||
}
|
}
|
||||||
|
role_value = (query_params.get('role') or '').strip()
|
||||||
|
if role_value:
|
||||||
|
# [STEP 1] 角色筛选同时命中主角色和成员表里的其他角色
|
||||||
|
if role_service.roles_configured():
|
||||||
|
member_ids = (
|
||||||
|
db.session.query(user_permission_roles.c.user_id)
|
||||||
|
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||||
|
.filter(PermissionRole.code.ilike(f'%{role_value}%'))
|
||||||
|
)
|
||||||
|
query = query.filter(or_(User.role.ilike(f'%{role_value}%'), User.id.in_(member_ids)))
|
||||||
|
else:
|
||||||
|
query = query.filter(User.role.ilike(f'%{role_value}%'))
|
||||||
for key, column in filter_columns.items():
|
for key, column in filter_columns.items():
|
||||||
value = (query_params.get(key) or '').strip()
|
value = (query_params.get(key) or '').strip()
|
||||||
if value:
|
if value:
|
||||||
@@ -142,7 +163,8 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
|||||||
if 'page' not in query_params:
|
if 'page' not in query_params:
|
||||||
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
users = query.options(joinedload(User.agents)).order_by(*order_by).all()
|
||||||
names = role_service.list_role_name_map()
|
names = role_service.list_role_name_map()
|
||||||
return [serialize_admin_user(u, names) for u in users]
|
assigned = role_service.roles_by_user_ids([user.id for user in users])
|
||||||
|
return [serialize_admin_user(user, names, assigned.get(user.id)) for user in users]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
page = int(query_params.get('page') or 1)
|
page = int(query_params.get('page') or 1)
|
||||||
@@ -168,8 +190,9 @@ def list_users(query_params: dict[str, str]) -> list[dict] | dict:
|
|||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
names = role_service.list_role_name_map()
|
names = role_service.list_role_name_map()
|
||||||
|
assigned = role_service.roles_by_user_ids([user.id for user in users])
|
||||||
return {
|
return {
|
||||||
'items': [serialize_admin_user(u, names) for u in users],
|
'items': [serialize_admin_user(user, names, assigned.get(user.id)) for user in users],
|
||||||
'total': int(total),
|
'total': int(total),
|
||||||
'page': page,
|
'page': page,
|
||||||
'page_size': page_size,
|
'page_size': page_size,
|
||||||
@@ -200,10 +223,17 @@ def create_user(data: dict[str, Any]) -> dict:
|
|||||||
employee_id=empty_to_none(data.get('employee_id')),
|
employee_id=empty_to_none(data.get('employee_id')),
|
||||||
phone_number=empty_to_none(data.get('phone_number')),
|
phone_number=empty_to_none(data.get('phone_number')),
|
||||||
)
|
)
|
||||||
role_code = role_service.assert_role_assignable(
|
if isinstance(data.get('roles'), list) and data.get('roles'):
|
||||||
data.get('role') or role_service.default_role_code(),
|
role_codes = [
|
||||||
allow_admin=True,
|
role_service.assert_role_assignable(code, allow_admin=True)
|
||||||
)
|
for code in data.get('roles') or []
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
role_codes = [role_service.assert_role_assignable(
|
||||||
|
data.get('role') or role_service.default_role_code(),
|
||||||
|
allow_admin=True,
|
||||||
|
)]
|
||||||
|
role_code = role_codes[0]
|
||||||
user = User(
|
user = User(
|
||||||
username=data['username'],
|
username=data['username'],
|
||||||
email=email,
|
email=email,
|
||||||
@@ -220,7 +250,7 @@ def create_user(data: dict[str, Any]) -> dict:
|
|||||||
db.session.add(user)
|
db.session.add(user)
|
||||||
try:
|
try:
|
||||||
if role_service.roles_configured():
|
if role_service.roles_configured():
|
||||||
role_service.sync_user_grants_from_role(user)
|
role_service.assign_role_codes(user, role_codes)
|
||||||
elif data.get('agent_ids'):
|
elif data.get('agent_ids'):
|
||||||
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all()
|
||||||
user.agents = agents
|
user.agents = agents
|
||||||
@@ -279,20 +309,25 @@ def update_user(user_id: int, data: dict[str, Any]) -> dict:
|
|||||||
assert_user_unique_fields(user_id, **unique_updates)
|
assert_user_unique_fields(user_id, **unique_updates)
|
||||||
new_password = empty_to_none(data.get('password'))
|
new_password = empty_to_none(data.get('password'))
|
||||||
try:
|
try:
|
||||||
for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']:
|
for key in ['email', 'department', 'status', 'real_name', 'employee_id', 'phone_number']:
|
||||||
if key in data:
|
if key in data:
|
||||||
if key == 'role':
|
if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
||||||
next_role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
|
||||||
role_service.ensure_not_last_admin(user, next_role)
|
|
||||||
user.role = next_role
|
|
||||||
elif key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']:
|
|
||||||
setattr(user, key, empty_to_none(data[key]))
|
setattr(user, key, empty_to_none(data[key]))
|
||||||
else:
|
else:
|
||||||
setattr(user, key, data[key])
|
setattr(user, key, data[key])
|
||||||
if role_service.roles_configured():
|
if role_service.roles_configured() and ('role' in data or 'roles' in data):
|
||||||
|
if isinstance(data.get('roles'), list):
|
||||||
|
codes = [
|
||||||
|
role_service.assert_role_assignable(code, allow_admin=True)
|
||||||
|
for code in data.get('roles') or []
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
codes = [role_service.assert_role_assignable(data.get('role'), allow_admin=True)]
|
||||||
|
role_service.ensure_role_codes_keep_admin(user, codes)
|
||||||
|
role_service.assign_role_codes(user, codes)
|
||||||
|
elif not role_service.roles_configured():
|
||||||
if 'role' in data:
|
if 'role' in data:
|
||||||
role_service.sync_user_grants_from_role(user)
|
user.role = role_service.assert_role_assignable(data.get('role'), allow_admin=True)
|
||||||
else:
|
|
||||||
if 'feature_permissions' in data or 'role' in data:
|
if 'feature_permissions' in data or 'role' in data:
|
||||||
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
permissions_payload = data.get('feature_permissions', user.feature_permissions)
|
||||||
user.set_feature_permissions(permissions_payload)
|
user.set_feature_permissions(permissions_payload)
|
||||||
@@ -340,8 +375,11 @@ def batch_update_users(user_ids: list[Any], data: dict[str, Any]) -> dict:
|
|||||||
user.status = payload.get('status')
|
user.status = payload.get('status')
|
||||||
if next_role:
|
if next_role:
|
||||||
role_service.ensure_not_last_admin(user, next_role)
|
role_service.ensure_not_last_admin(user, next_role)
|
||||||
user.role = next_role
|
if role_service.roles_configured():
|
||||||
role_service.sync_user_grants_from_role(user)
|
role_service.assign_role_codes(user, [next_role])
|
||||||
|
else:
|
||||||
|
user.role = next_role
|
||||||
|
role_service.sync_user_grants_from_role(user)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return {'status': 'ok', 'updated_count': len(users)}
|
return {'status': 'ok', 'updated_count': len(users)}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""
|
||||||
|
services/chat/capability_list.py
|
||||||
|
|
||||||
|
用途:查询指定智能体在常用问题(QuickQuestion)中的「能力清单」条目标准答案。
|
||||||
|
依赖:models.QuickQuestion、core.errors.AppError、SQLAlchemy db。
|
||||||
|
逻辑:Dify 知识库未命中兜底回复会在前端展示【知识库内容清单】按钮;按钮点击后由
|
||||||
|
api/chat/capability_list.py 调用本模块,按 agent_id 过滤全局条目并返回标准答案。
|
||||||
|
管理端维护约定:条目标题形如「<应用名>·能力清单条目」,因此以标题含「能力清单」
|
||||||
|
作为识别关键字,应用归属仍以 agent_id 外键为准(禁止按标题前缀解析应用名)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.errors import AppError
|
||||||
|
from app.models import QuickQuestion
|
||||||
|
|
||||||
|
# 能力清单条目的标题识别关键字(管理端维护约定,见模块 docstring)。
|
||||||
|
CAPABILITY_LIST_TITLE_KEYWORD = '能力清单'
|
||||||
|
|
||||||
|
|
||||||
|
def get_agent_capability_list(agent: Any) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
查询智能体的知识库内容清单条目。
|
||||||
|
|
||||||
|
用途:聊天端兜底回复【知识库内容清单】按钮的数据来源。
|
||||||
|
核心逻辑:
|
||||||
|
1. 仅匹配全局条目(user_id 为空)且归属当前 agent_id;
|
||||||
|
2. 标题须含「能力清单」关键字,且标准答案非空;
|
||||||
|
3. 多条命中时按 sort_order、id 取第一条,保证返回稳定。
|
||||||
|
Args:
|
||||||
|
agent: 已通过 require_agent_permission 鉴权的 Agent 模型实例,禁止传 None。
|
||||||
|
Returns:
|
||||||
|
含 id/agent_id/title/question/answer 的条目字典,answer 为标准答案原文。
|
||||||
|
Raises:
|
||||||
|
AppError: code=CHAT.CAPABILITY_LIST_NOT_FOUND,表示该应用尚未配置能力清单条目。
|
||||||
|
"""
|
||||||
|
agent_id = getattr(agent, 'id', None)
|
||||||
|
if not agent_id:
|
||||||
|
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing agent id', http_status=500)
|
||||||
|
|
||||||
|
entry = (
|
||||||
|
db.session.query(QuickQuestion)
|
||||||
|
.filter(
|
||||||
|
QuickQuestion.agent_id == agent_id,
|
||||||
|
QuickQuestion.user_id.is_(None),
|
||||||
|
QuickQuestion.title.contains(CAPABILITY_LIST_TITLE_KEYWORD),
|
||||||
|
QuickQuestion.answer.isnot(None),
|
||||||
|
QuickQuestion.answer != '',
|
||||||
|
)
|
||||||
|
.order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc())
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if entry is None:
|
||||||
|
raise AppError(
|
||||||
|
code='CHAT.CAPABILITY_LIST_NOT_FOUND',
|
||||||
|
message='capability list entry is not configured for this agent',
|
||||||
|
http_status=404,
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
'id': entry.id,
|
||||||
|
'agent_id': entry.agent_id,
|
||||||
|
'title': entry.title,
|
||||||
|
'question': entry.question,
|
||||||
|
'answer': entry.answer or '',
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
backend/app/services/equipment_acceptance/schedule_seed.py
|
backend/app/services/equipment_acceptance/schedule_seed.py
|
||||||
|
|
||||||
用途:设备验收预警的默认排程:每日扫描和周五 18:00 发送。
|
用途:设备验收预警的默认排程:每日 06:30 扫描和周五 18:30 发送。
|
||||||
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
依赖:ScheduleTask、permission_roles.service.first_schedule_owner_user、timezone_util。
|
||||||
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
|
逻辑:应用启动时幂等创建。已有同编号或同任务键时不覆盖管理员改过的 Cron。
|
||||||
"""
|
"""
|
||||||
@@ -17,8 +17,10 @@ from app.services.schedule.timezone_util import compute_next_run_at
|
|||||||
|
|
||||||
|
|
||||||
_DEFAULTS = (
|
_DEFAULTS = (
|
||||||
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批)", "0 6 * * *"),
|
# 每天 06:30,错开合同付款预警扫描的 06:00
|
||||||
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:00)", "0 18 * * 5"),
|
("SCH-EQUIPMENT-ACCEPTANCE-SCAN", "equipment-acceptance-alert-scan", "设备验收预警扫描(日批 06:30)", "30 6 * * *"),
|
||||||
|
# 周五 18:30,错开合同付款预警的周五 18:00
|
||||||
|
("SCH-EQUIPMENT-ACCEPTANCE-WEEKLY", "equipment-acceptance-alert-weekly", "设备验收预警发送(周五 18:30)", "30 18 * * 5"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -26,7 +28,7 @@ def ensure_default_equipment_acceptance_schedules(*, commit: bool = True):
|
|||||||
"""
|
"""
|
||||||
幂等创建设备验收每日扫描和周五发送两个排程。
|
幂等创建设备验收每日扫描和周五发送两个排程。
|
||||||
|
|
||||||
核心逻辑:发送时刻不在预警配置表。默认与合同付款一样,周五 18:00,时区 Asia/Shanghai。
|
核心逻辑:发送时刻不在预警配置表。默认每天 06:30、周五 18:30(错开合同付款 06:00 / 18:00),时区 Asia/Shanghai。
|
||||||
Args:
|
Args:
|
||||||
commit: 为 False 时只 flush,交给外层事务提交。
|
commit: 为 False 时只 flush,交给外层事务提交。
|
||||||
Returns:
|
Returns:
|
||||||
|
|||||||
@@ -129,6 +129,10 @@ def build_feedback_markdown(feedback: GeneralFeedback, user: User | None) -> str
|
|||||||
lines.append(f'>来源页面:{feedback.source_page}')
|
lines.append(f'>来源页面:{feedback.source_page}')
|
||||||
if feedback.chat_log_id:
|
if feedback.chat_log_id:
|
||||||
lines.append(f'>关联对话:{feedback.chat_log_id}')
|
lines.append(f'>关联对话:{feedback.chat_log_id}')
|
||||||
|
# 附图行:仅在有截图时展示数量,置于「反馈内容」之前,便于处理人先感知附件再读正文
|
||||||
|
image_count = len(feedback.images or [])
|
||||||
|
if image_count:
|
||||||
|
lines.append(f'>附图:{image_count} 张')
|
||||||
lines.extend(['', '**反馈内容:**', content or '-'])
|
lines.extend(['', '**反馈内容:**', content or '-'])
|
||||||
if report_url:
|
if report_url:
|
||||||
lines.extend(['', f'[打开后台报表]({report_url})'])
|
lines.extend(['', f'[打开后台报表]({report_url})'])
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ backend/app/services/lean_training_service.py
|
|||||||
|
|
||||||
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
用途:精益管理培训的周任务、员工提交、看板和提醒规则服务。
|
||||||
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
依赖:TrainingConfig/Resource、精益培训模型、User、统一 ValidationError。
|
||||||
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;学员端"本期视频"口径为本任务首次推送的
|
逻辑:管理端冻结每周视频列表、每周推送数量与受训对象;受训角色按用户已挂的全部权限组匹配。
|
||||||
视频(已推送前缀扣除其它更早期任务已推送部分,推过的视频不重复展示、不要求重学);
|
学员端「本期视频」口径为本任务首次推送的视频(已推送前缀扣除其它更早期任务已推送部分,推过的视频不重复展示、不要求重学);
|
||||||
员工仅对本期视频提交观看事实与学习感悟,服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
员工仅对本期视频提交观看事实与学习感悟,服务端按 50 字门槛判定完成,管理看板只读取已授权范围。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -23,10 +23,12 @@ from app.models import (
|
|||||||
Agent,
|
Agent,
|
||||||
LeanTrainingCompletion,
|
LeanTrainingCompletion,
|
||||||
LeanTrainingWeeklyTask,
|
LeanTrainingWeeklyTask,
|
||||||
|
PermissionRole,
|
||||||
TrainingConfig,
|
TrainingConfig,
|
||||||
TrainingConfigResource,
|
TrainingConfigResource,
|
||||||
User,
|
User,
|
||||||
)
|
)
|
||||||
|
from app.models.permission_role import user_permission_roles
|
||||||
from app.services.integrations.minio import minio_service
|
from app.services.integrations.minio import minio_service
|
||||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
|
||||||
|
|
||||||
@@ -252,20 +254,38 @@ def _normalize_target_user_ids(value: Any) -> list[int]:
|
|||||||
|
|
||||||
|
|
||||||
def target_user_ids_for_task(task: LeanTrainingWeeklyTask) -> set[int]:
|
def target_user_ids_for_task(task: LeanTrainingWeeklyTask) -> set[int]:
|
||||||
"""返回周任务的在职受训对象,角色和用户指定对象按并集处理。"""
|
"""返回周任务的在职受训对象。指定用户,以及主角色或任一已挂角色命中的人,按并集处理。"""
|
||||||
predicates = []
|
predicates = []
|
||||||
if task.target_user_ids:
|
if task.target_user_ids:
|
||||||
predicates.append(User.id.in_(list(task.target_user_ids)))
|
predicates.append(User.id.in_(list(task.target_user_ids)))
|
||||||
if task.target_roles:
|
if task.target_roles:
|
||||||
predicates.append(User.role.in_(list(task.target_roles)))
|
role_codes = list(task.target_roles)
|
||||||
|
member_ids = (
|
||||||
|
select(user_permission_roles.c.user_id)
|
||||||
|
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||||
|
.where(PermissionRole.code.in_(role_codes))
|
||||||
|
)
|
||||||
|
predicates.append(or_(User.role.in_(role_codes), User.id.in_(member_ids)))
|
||||||
if not predicates:
|
if not predicates:
|
||||||
return set()
|
return set()
|
||||||
return set(db.session.execute(select(User.id).where(User.status == "active", or_(*predicates))).scalars())
|
return set(db.session.execute(select(User.id).where(User.status == "active", or_(*predicates))).scalars())
|
||||||
|
|
||||||
|
|
||||||
def is_task_targeted_to_user(task: LeanTrainingWeeklyTask, user: User) -> bool:
|
def is_task_targeted_to_user(task: LeanTrainingWeeklyTask, user: User) -> bool:
|
||||||
"""判断员工是否属于周任务对象,角色匹配或显式指定任一成立即可学习。"""
|
"""判断员工是否属于周任务对象。任一已挂角色命中,或显式指定用户,即可学习。"""
|
||||||
return user.status == "active" and (user.id in set(task.target_user_ids or []) or user.role in set(task.target_roles or []))
|
if user.status != "active":
|
||||||
|
return False
|
||||||
|
if user.id in set(task.target_user_ids or []):
|
||||||
|
return True
|
||||||
|
codes = set(task.target_roles or [])
|
||||||
|
if not codes:
|
||||||
|
return False
|
||||||
|
from app.services.permission_roles.service import list_assigned_roles, roles_configured
|
||||||
|
|
||||||
|
assigned = {str(user.role or "")}
|
||||||
|
if roles_configured():
|
||||||
|
assigned.update(role.code for role in list_assigned_roles(user))
|
||||||
|
return bool(assigned & codes)
|
||||||
|
|
||||||
|
|
||||||
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False, own_pushed_ids: list[int] | None = None) -> dict[str, Any]:
|
def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool = False, own_pushed_ids: list[int] | None = None) -> dict[str, Any]:
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
"""
|
"""
|
||||||
services/permission_roles/service.py
|
services/permission_roles/service.py
|
||||||
|
|
||||||
用途:权限组 CRUD、成员预览/确认调整、把角色包同步到 users.role 与 user_agent_permissions。
|
用途:权限组 CRUD、成员预览/确认调整、把多个角色包的并集同步到用户授权。
|
||||||
依赖:PermissionRole、User、Agent、catalog。
|
依赖:PermissionRole、user_permission_roles、User、Agent、catalog。
|
||||||
逻辑:由 api/admin/permission_roles 调用;用户创建/改角色时 sync_user_grants_from_role。
|
逻辑:由 api/admin/permission_roles 调用;用户创建/改角色时 sync_user_grants_from_role。
|
||||||
|
一个用户可挂多个业务角色,应用入口与能力取并集;平台管理员不与其他角色叠加。
|
||||||
|
拿掉最后一个业务角色时回到默认权限组。users.role 只记主角色。
|
||||||
排程种子/告警用 first_platform_admin_user 按 is_platform_admin join,不写死 role='admin'。
|
排程种子/告警用 first_platform_admin_user 按 is_platform_admin join,不写死 role='admin'。
|
||||||
未种子角色表时保持旧的按人勾选,避免单测全量改夹具。
|
未种子角色表时保持旧的按人勾选,避免单测全量改夹具。
|
||||||
"""
|
"""
|
||||||
@@ -14,12 +16,13 @@ import re
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
|
|
||||||
|
from sqlalchemy import delete, insert, select
|
||||||
from sqlalchemy.orm import joinedload
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||||
from app.models import Agent, User
|
from app.models import Agent, User
|
||||||
from app.models.permission_role import PermissionRole
|
from app.models.permission_role import PermissionRole, user_permission_roles
|
||||||
from app.services.permission_roles.catalog import (
|
from app.services.permission_roles.catalog import (
|
||||||
FEATURE_CATALOG,
|
FEATURE_CATALOG,
|
||||||
KNOWN_FEATURE_KEYS,
|
KNOWN_FEATURE_KEYS,
|
||||||
@@ -75,6 +78,187 @@ def list_role_name_map() -> dict[str, str]:
|
|||||||
return {row.code: row.name for row in rows}
|
return {row.code: row.name for row in rows}
|
||||||
|
|
||||||
|
|
||||||
|
def list_assigned_roles(user: User, sess: Any | None = None) -> list[PermissionRole]:
|
||||||
|
"""
|
||||||
|
读取用户已挂的权限组。
|
||||||
|
|
||||||
|
核心逻辑:有成员表行时以成员表为准;还没回填时回退 users.role,兼容只写 role 的旧数据和测试。
|
||||||
|
"""
|
||||||
|
session = _orm_session(sess)
|
||||||
|
if user is None or getattr(user, 'id', None) is None or not _permission_roles_exist(session):
|
||||||
|
return []
|
||||||
|
linked = (
|
||||||
|
session.query(PermissionRole)
|
||||||
|
.join(user_permission_roles, user_permission_roles.c.role_id == PermissionRole.id)
|
||||||
|
.filter(user_permission_roles.c.user_id == user.id)
|
||||||
|
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
if linked:
|
||||||
|
return linked
|
||||||
|
code = str(getattr(user, 'role', '') or '').strip()
|
||||||
|
if not code:
|
||||||
|
return []
|
||||||
|
fallback = session.query(PermissionRole).filter(PermissionRole.code == code).one_or_none()
|
||||||
|
return [fallback] if fallback else []
|
||||||
|
|
||||||
|
|
||||||
|
def roles_by_user_ids(user_ids: list[int]) -> dict[int, list[PermissionRole]]:
|
||||||
|
"""批量读取成员关系,避免用户列表逐人查询。"""
|
||||||
|
if not user_ids or not roles_configured():
|
||||||
|
return {}
|
||||||
|
rows = (
|
||||||
|
db.session.query(user_permission_roles.c.user_id, PermissionRole)
|
||||||
|
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||||
|
.filter(user_permission_roles.c.user_id.in_(user_ids))
|
||||||
|
.order_by(PermissionRole.sort_order.asc(), PermissionRole.id.asc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
grouped: dict[int, list[PermissionRole]] = {}
|
||||||
|
for user_id, role in rows:
|
||||||
|
grouped.setdefault(int(user_id), []).append(role)
|
||||||
|
return grouped
|
||||||
|
|
||||||
|
|
||||||
|
def _primary_role(roles: list[PermissionRole]) -> PermissionRole | None:
|
||||||
|
"""主角色:平台管理员优先,否则取非默认角色里排序最前的一个。"""
|
||||||
|
if not roles:
|
||||||
|
return None
|
||||||
|
admins = [role for role in roles if role.is_platform_admin]
|
||||||
|
pool = admins or [role for role in roles if not role.is_default] or roles
|
||||||
|
return sorted(pool, key=lambda role: (role.sort_order, role.id or 0))[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _role_label(roles: list[PermissionRole], role_names: dict[str, str], fallback: str) -> str:
|
||||||
|
"""多个角色显示名用顿号拼接;没有成员行时回退主角色名。"""
|
||||||
|
if roles:
|
||||||
|
return '、'.join(role.name for role in roles)
|
||||||
|
return role_names.get(fallback) or fallback
|
||||||
|
|
||||||
|
|
||||||
|
def describe_user_roles(
|
||||||
|
user: User,
|
||||||
|
assigned: list[PermissionRole] | None = None,
|
||||||
|
role_names: dict[str, str] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
用户当前的主角色与全部角色。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
assigned: 已批量查出的角色;None 时再查成员表。空列表表示调用方确认没有成员行。
|
||||||
|
"""
|
||||||
|
names = role_names if role_names is not None else list_role_name_map()
|
||||||
|
if assigned is None and roles_configured():
|
||||||
|
roles = list_assigned_roles(user)
|
||||||
|
else:
|
||||||
|
roles = list(assigned or [])
|
||||||
|
primary = _primary_role(roles)
|
||||||
|
fallback = str(user.role or '')
|
||||||
|
return {
|
||||||
|
'role': primary.code if primary else fallback,
|
||||||
|
'role_name': _role_label(roles, names, fallback),
|
||||||
|
'role_codes': [role.code for role in roles] or ([fallback] if fallback else []),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def role_auth_payload(user: User) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
登录态里的角色展示。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
role_name: 全部角色名,顿号拼接。
|
||||||
|
role_codes: 全部角色 code;未配置权限组时只有 users.role。
|
||||||
|
"""
|
||||||
|
described = describe_user_roles(user)
|
||||||
|
return {
|
||||||
|
'role_name': described['role_name'],
|
||||||
|
'role_codes': described['role_codes'],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _has_membership_rows(user: User) -> bool:
|
||||||
|
"""该用户是否已有成员表行。"""
|
||||||
|
if user.id is None:
|
||||||
|
return False
|
||||||
|
found = db.session.execute(
|
||||||
|
select(user_permission_roles.c.user_id)
|
||||||
|
.where(user_permission_roles.c.user_id == user.id)
|
||||||
|
.limit(1)
|
||||||
|
).first()
|
||||||
|
return found is not None
|
||||||
|
|
||||||
|
|
||||||
|
def replace_user_roles(user: User, roles: list[PermissionRole]) -> list[PermissionRole]:
|
||||||
|
"""
|
||||||
|
用给定权限组替换成员关系,并回写 users.role 主角色。
|
||||||
|
|
||||||
|
核心逻辑:出现平台管理员时只保留该角色。空列表回落到默认权限组。
|
||||||
|
"""
|
||||||
|
if user.id is None:
|
||||||
|
db.session.flush()
|
||||||
|
unique: list[PermissionRole] = []
|
||||||
|
seen: set[int] = set()
|
||||||
|
for role in roles:
|
||||||
|
if role is None or role.id in seen:
|
||||||
|
continue
|
||||||
|
seen.add(role.id)
|
||||||
|
unique.append(role)
|
||||||
|
admins = [role for role in unique if role.is_platform_admin]
|
||||||
|
if admins:
|
||||||
|
unique = [sorted(admins, key=lambda role: (role.sort_order, role.id or 0))[0]]
|
||||||
|
elif not unique:
|
||||||
|
default = get_default_role()
|
||||||
|
unique = [default] if default else []
|
||||||
|
db.session.execute(
|
||||||
|
delete(user_permission_roles).where(user_permission_roles.c.user_id == user.id)
|
||||||
|
)
|
||||||
|
if unique:
|
||||||
|
db.session.execute(
|
||||||
|
insert(user_permission_roles),
|
||||||
|
[{'user_id': user.id, 'role_id': role.id} for role in unique],
|
||||||
|
)
|
||||||
|
primary = _primary_role(unique)
|
||||||
|
user.role = primary.code if primary else default_role_code()
|
||||||
|
user._is_platform_admin_cached = None
|
||||||
|
db.session.flush()
|
||||||
|
return unique
|
||||||
|
|
||||||
|
|
||||||
|
def roles_after_grant(current: list[PermissionRole], incoming: PermissionRole) -> list[PermissionRole]:
|
||||||
|
"""
|
||||||
|
追加一个角色后的成员集合。
|
||||||
|
|
||||||
|
核心逻辑:业务角色会拿掉默认角色,避免「普通用户」人数把已有专属角色的人再计一次;
|
||||||
|
其他业务角色保留。追加默认角色时不拿掉已有业务角色。平台管理员独占。
|
||||||
|
"""
|
||||||
|
if incoming.is_platform_admin:
|
||||||
|
return [incoming]
|
||||||
|
if incoming.is_default:
|
||||||
|
if any(role.id == incoming.id for role in current):
|
||||||
|
return list(current)
|
||||||
|
return [*current, incoming]
|
||||||
|
kept = [
|
||||||
|
role for role in current
|
||||||
|
if not role.is_default and not role.is_platform_admin and role.id != incoming.id
|
||||||
|
]
|
||||||
|
return [*kept, incoming]
|
||||||
|
|
||||||
|
|
||||||
|
def roles_after_revoke(current: list[PermissionRole], incoming: PermissionRole) -> list[PermissionRole]:
|
||||||
|
"""
|
||||||
|
移出一个角色后的成员集合。
|
||||||
|
|
||||||
|
核心逻辑:还剩别的角色就只移出这一个。一个都不剩时回到默认权限组。
|
||||||
|
默认角色是唯一角色时保持不变。
|
||||||
|
"""
|
||||||
|
kept = [role for role in current if role.id != incoming.id]
|
||||||
|
if not kept:
|
||||||
|
default = get_default_role()
|
||||||
|
if default is not None:
|
||||||
|
return [default]
|
||||||
|
return kept
|
||||||
|
|
||||||
|
|
||||||
def _orm_session(sess: Any | None):
|
def _orm_session(sess: Any | None):
|
||||||
"""排程种子 after_commit 可能传入独立 Session,查询必须落在同一会话。"""
|
"""排程种子 after_commit 可能传入独立 Session,查询必须落在同一会话。"""
|
||||||
return sess if sess is not None else db.session
|
return sess if sess is not None else db.session
|
||||||
@@ -158,7 +342,7 @@ def user_is_platform_admin(user: User | None, sess: Any | None = None) -> bool:
|
|||||||
"""
|
"""
|
||||||
判断用户是否属于 is_platform_admin 权限组。
|
判断用户是否属于 is_platform_admin 权限组。
|
||||||
|
|
||||||
核心逻辑:已种子时按 users.role join permission_roles;否则回退 role=admin。
|
核心逻辑:已种子时看全部已挂角色里是否有平台管理组;否则回退 role=admin。
|
||||||
同一 User 实例在一次请求内缓存结果,避免货代工作台重复查询。
|
同一 User 实例在一次请求内缓存结果,避免货代工作台重复查询。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -172,22 +356,20 @@ def user_is_platform_admin(user: User | None, sess: Any | None = None) -> bool:
|
|||||||
return False
|
return False
|
||||||
session = _orm_session(sess)
|
session = _orm_session(sess)
|
||||||
role_code = str(getattr(user, 'role', '') or '').strip()
|
role_code = str(getattr(user, 'role', '') or '').strip()
|
||||||
|
assigned = list_assigned_roles(user, session) if _permission_roles_exist(session) else []
|
||||||
|
cache_key = (role_code, tuple(role.code for role in assigned))
|
||||||
cached = getattr(user, '_is_platform_admin_cached', None)
|
cached = getattr(user, '_is_platform_admin_cached', None)
|
||||||
if isinstance(cached, tuple) and len(cached) == 2 and cached[0] == role_code:
|
if isinstance(cached, tuple) and len(cached) == 2 and cached[0] == cache_key:
|
||||||
return bool(cached[1])
|
return bool(cached[1])
|
||||||
if not role_code:
|
if assigned:
|
||||||
user._is_platform_admin_cached = (role_code, False)
|
result = any(role.is_platform_admin for role in assigned)
|
||||||
return False
|
elif not role_code:
|
||||||
if _permission_roles_exist(session):
|
result = False
|
||||||
role = (
|
elif _permission_roles_exist(session):
|
||||||
session.query(PermissionRole)
|
result = False
|
||||||
.filter(PermissionRole.code == role_code)
|
|
||||||
.one_or_none()
|
|
||||||
)
|
|
||||||
result = bool(role and role.is_platform_admin)
|
|
||||||
else:
|
else:
|
||||||
result = role_code == PLATFORM_ADMIN_CODE
|
result = role_code == PLATFORM_ADMIN_CODE
|
||||||
user._is_platform_admin_cached = (role_code, result)
|
user._is_platform_admin_cached = (cache_key, result)
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
@@ -211,46 +393,92 @@ def _normalize_feature_map(raw: Any) -> dict[str, bool]:
|
|||||||
|
|
||||||
def effective_feature_permissions(user: User) -> dict[str, bool] | None:
|
def effective_feature_permissions(user: User) -> dict[str, bool] | None:
|
||||||
"""
|
"""
|
||||||
若已配置权限组,返回该用户角色包的有效功能权限;否则 None 表示走 User 旧默认值。
|
若已配置权限组,返回该用户全部角色的有效功能权限;否则 None 表示走 User 旧默认值。
|
||||||
|
|
||||||
|
核心逻辑:任一业务角色打开的能力即生效。平台管理员仍默认全开,再用该组上的显式值覆盖。
|
||||||
"""
|
"""
|
||||||
if not roles_configured():
|
if not roles_configured():
|
||||||
return None
|
return None
|
||||||
role = get_role_by_code(user.role)
|
roles = list_assigned_roles(user)
|
||||||
stored = _normalize_feature_map(role.feature_permissions if role else {})
|
admin = next((role for role in roles if role.is_platform_admin), None)
|
||||||
if role and role.is_platform_admin:
|
if admin is not None:
|
||||||
result = {key: True for key in KNOWN_FEATURE_KEYS}
|
result = {key: True for key in KNOWN_FEATURE_KEYS}
|
||||||
result.update(stored)
|
result.update(_normalize_feature_map(admin.feature_permissions))
|
||||||
return result
|
return result
|
||||||
result = {key: False for key in KNOWN_FEATURE_KEYS}
|
result = {key: False for key in KNOWN_FEATURE_KEYS}
|
||||||
result.update(stored)
|
for role in roles:
|
||||||
|
for key, enabled in _normalize_feature_map(role.feature_permissions).items():
|
||||||
|
if enabled:
|
||||||
|
result[key] = True
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def sync_user_grants_from_role(user: User) -> None:
|
def sync_user_grants_from_role(user: User) -> None:
|
||||||
"""
|
"""
|
||||||
按用户当前 role 重写 Agent 授权与个人功能覆盖。
|
按用户已挂的全部角色重算 Agent 授权与个人功能覆盖。
|
||||||
|
|
||||||
核心逻辑:管理员不写 user_agent_permissions(入口隐式全开);
|
核心逻辑:还没有成员行时先按 users.role 写入一行。管理员不写 user_agent_permissions(入口隐式全开);
|
||||||
其他角色用权限组勾选的 Agent 全量替换;个人 feature_permissions 清空,改由角色包计算。
|
其他角色把各权限组勾选的 Agent 取并集。个人 feature_permissions 清空,改由角色包计算。
|
||||||
未配置权限组时不改。
|
未配置权限组时不改。
|
||||||
"""
|
"""
|
||||||
if not roles_configured():
|
if not roles_configured():
|
||||||
return
|
return
|
||||||
role = get_role_by_code(user.role)
|
if user.id is None:
|
||||||
if role is None:
|
db.session.flush()
|
||||||
|
roles = list_assigned_roles(user)
|
||||||
|
if not roles:
|
||||||
fallback = get_default_role()
|
fallback = get_default_role()
|
||||||
if fallback is None:
|
if fallback is None:
|
||||||
return
|
return
|
||||||
user.role = fallback.code
|
roles = [fallback]
|
||||||
role = fallback
|
if not _has_membership_rows(user):
|
||||||
|
roles = replace_user_roles(user, roles)
|
||||||
|
admins = [role for role in roles if role.is_platform_admin]
|
||||||
user.feature_permissions = {}
|
user.feature_permissions = {}
|
||||||
if role.is_platform_admin:
|
user._is_platform_admin_cached = None
|
||||||
|
if admins:
|
||||||
|
if len(roles) != 1:
|
||||||
|
replace_user_roles(user, [admins[0]])
|
||||||
return
|
return
|
||||||
user.agents = list(role.agents)
|
primary = _primary_role(roles)
|
||||||
|
if primary is not None and user.role != primary.code:
|
||||||
|
user.role = primary.code
|
||||||
|
seen: dict[int, Agent] = {}
|
||||||
|
for role in roles:
|
||||||
|
for agent in role.agents:
|
||||||
|
seen[agent.id] = agent
|
||||||
|
user.agents = list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
|
def _users_for_role(role: PermissionRole, *, active_only: bool = False) -> list[User]:
|
||||||
|
"""
|
||||||
|
某权限组的成员。
|
||||||
|
|
||||||
|
核心逻辑:成员表里挂了该角色的人,加上尚未回填、users.role 仍等于该 code 的人。
|
||||||
|
"""
|
||||||
|
linked_ids = select(user_permission_roles.c.user_id).where(
|
||||||
|
user_permission_roles.c.role_id == role.id
|
||||||
|
)
|
||||||
|
any_membership = select(user_permission_roles.c.user_id)
|
||||||
|
linked = db.session.query(User).filter(User.id.in_(linked_ids))
|
||||||
|
unlinked = db.session.query(User).filter(
|
||||||
|
User.role == role.code,
|
||||||
|
~User.id.in_(any_membership),
|
||||||
|
)
|
||||||
|
if active_only:
|
||||||
|
linked = linked.filter(User.status == 'active')
|
||||||
|
unlinked = unlinked.filter(User.status == 'active')
|
||||||
|
found: dict[int, User] = {}
|
||||||
|
for user in [*linked.all(), *unlinked.all()]:
|
||||||
|
found[user.id] = user
|
||||||
|
return list(found.values())
|
||||||
|
|
||||||
|
|
||||||
def _count_members(code: str) -> int:
|
def _count_members(code: str) -> int:
|
||||||
return db.session.query(User).filter(User.role == code).count()
|
role = get_role_by_code(code)
|
||||||
|
if role is None:
|
||||||
|
return db.session.query(User).filter(User.role == code).count()
|
||||||
|
return len(_users_for_role(role))
|
||||||
|
|
||||||
|
|
||||||
def _serialize_role(role: PermissionRole, *, with_agents: bool = True) -> dict[str, Any]:
|
def _serialize_role(role: PermissionRole, *, with_agents: bool = True) -> dict[str, Any]:
|
||||||
@@ -437,9 +665,9 @@ def create_role(data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
|
|
||||||
def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
保存权限组。仅当应用勾选或能力开关变化时,才同步该组用户的应用授权。
|
保存权限组。仅当应用勾选或能力开关变化时,才按并集重算该组用户的应用授权。
|
||||||
|
|
||||||
管理员不可改应用入口勾选。只改名称/说明不重写成员权限。
|
管理员不可改应用入口勾选。只改名称/说明不重写成员权限。其他人身上的其他角色保留。
|
||||||
"""
|
"""
|
||||||
role = get_role_by_code(code)
|
role = get_role_by_code(code)
|
||||||
if not role:
|
if not role:
|
||||||
@@ -447,7 +675,7 @@ def update_role(code: str, data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
allow_agents = not role.is_platform_admin
|
allow_agents = not role.is_platform_admin
|
||||||
grants_changed = _grants_changed(role, data, allow_agents=allow_agents)
|
grants_changed = _grants_changed(role, data, allow_agents=allow_agents)
|
||||||
_apply_package(role, data, allow_agents=allow_agents)
|
_apply_package(role, data, allow_agents=allow_agents)
|
||||||
users = db.session.query(User).filter(User.role == role.code).all() if grants_changed else []
|
users = _users_for_role(role) if grants_changed else []
|
||||||
for user in users:
|
for user in users:
|
||||||
sync_user_grants_from_role(user)
|
sync_user_grants_from_role(user)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -470,28 +698,67 @@ def delete_role(code: str) -> dict[str, Any]:
|
|||||||
return {'status': 'ok'}
|
return {'status': 'ok'}
|
||||||
|
|
||||||
|
|
||||||
def _person_payload(user: User, role_names: dict[str, str]) -> dict[str, Any]:
|
def _person_payload(
|
||||||
|
user: User,
|
||||||
|
role_names: dict[str, str],
|
||||||
|
assigned: list[PermissionRole] | None = None,
|
||||||
|
*,
|
||||||
|
retained_role_names: list[str] | None = None,
|
||||||
|
returns_to_default: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""选人与确认框共用的人员行。role 是主角色,role_codes 是全部角色。"""
|
||||||
|
roles = list_assigned_roles(user) if assigned is None else assigned
|
||||||
|
primary = _primary_role(roles)
|
||||||
|
fallback = str(user.role or '')
|
||||||
return {
|
return {
|
||||||
'id': user.id,
|
'id': user.id,
|
||||||
'username': user.username,
|
'username': user.username,
|
||||||
'real_name': user.real_name,
|
'real_name': user.real_name,
|
||||||
'employee_id': user.employee_id,
|
'employee_id': user.employee_id,
|
||||||
'department': user.department,
|
'department': user.department,
|
||||||
'role': user.role,
|
'role': primary.code if primary else fallback,
|
||||||
'role_name': role_names.get(user.role) or user.role,
|
'role_name': _role_label(roles, role_names, fallback),
|
||||||
|
'role_codes': [role.code for role in roles] or ([fallback] if fallback else []),
|
||||||
|
'retained_role_names': list(retained_role_names or []),
|
||||||
|
'returns_to_default': returns_to_default,
|
||||||
'wecom_bound': bool(user.wecom_userid),
|
'wecom_bound': bool(user.wecom_userid),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def assign_role_codes(user: User, codes: list[str]) -> None:
|
||||||
|
"""
|
||||||
|
按 code 列表替换该用户的全部角色并重算授权。
|
||||||
|
|
||||||
|
核心逻辑:空列表回落到默认权限组。平台管理员 code 会清掉其他角色。
|
||||||
|
"""
|
||||||
|
roles: list[PermissionRole] = []
|
||||||
|
for code in codes:
|
||||||
|
role = get_role_by_code(code)
|
||||||
|
if role is not None:
|
||||||
|
roles.append(role)
|
||||||
|
replace_user_roles(user, roles)
|
||||||
|
sync_user_grants_from_role(user)
|
||||||
|
|
||||||
|
|
||||||
def list_picker_people() -> list[dict[str, Any]]:
|
def list_picker_people() -> list[dict[str, Any]]:
|
||||||
"""选人弹窗候选人:启用用户且排除平台管理员。"""
|
"""选人弹窗候选人:启用用户且排除平台管理员。"""
|
||||||
role_names = list_role_name_map()
|
role_names = list_role_name_map()
|
||||||
query = db.session.query(User).filter(User.status == 'active')
|
query = db.session.query(User).filter(User.status == 'active')
|
||||||
admin_codes = platform_admin_role_codes()
|
admin_codes = platform_admin_role_codes()
|
||||||
if admin_codes:
|
if admin_codes:
|
||||||
query = query.filter(User.role.notin_(admin_codes))
|
admin_ids = (
|
||||||
|
select(user_permission_roles.c.user_id)
|
||||||
|
.join(PermissionRole, PermissionRole.id == user_permission_roles.c.role_id)
|
||||||
|
.where(PermissionRole.is_platform_admin.is_(True))
|
||||||
|
)
|
||||||
|
query = query.filter(User.role.notin_(admin_codes), ~User.id.in_(admin_ids))
|
||||||
users = query.order_by(User.id.asc()).all()
|
users = query.order_by(User.id.asc()).all()
|
||||||
return [_person_payload(user, role_names) for user in users]
|
assigned = roles_by_user_ids([user.id for user in users])
|
||||||
|
payloads = []
|
||||||
|
for user in users:
|
||||||
|
roles = assigned.get(user.id) or list_assigned_roles(user)
|
||||||
|
payloads.append(_person_payload(user, role_names, roles))
|
||||||
|
return payloads
|
||||||
|
|
||||||
|
|
||||||
def _normalize_selected_ids(raw: Any) -> list[int]:
|
def _normalize_selected_ids(raw: Any) -> list[int]:
|
||||||
@@ -511,7 +778,10 @@ def _normalize_selected_ids(raw: Any) -> list[int]:
|
|||||||
|
|
||||||
def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
计算勾选草稿相对当前成员的增减,供确认框展示来源角色。
|
计算勾选草稿相对当前成员的增减。
|
||||||
|
|
||||||
|
核心逻辑:加入是追加本角色,不拿走其他业务角色。移出只拿掉本角色;
|
||||||
|
一个业务角色都不剩时回到默认权限组。默认角色若已是唯一角色,取消勾选不算变更。
|
||||||
"""
|
"""
|
||||||
role = get_role_by_code(code)
|
role = get_role_by_code(code)
|
||||||
if not role:
|
if not role:
|
||||||
@@ -520,35 +790,59 @@ def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
|||||||
raise ForbiddenError('Platform admin members cannot be changed here', code='ROLE.ADMIN_LOCKED')
|
raise ForbiddenError('Platform admin members cannot be changed here', code='ROLE.ADMIN_LOCKED')
|
||||||
default_code = default_role_code()
|
default_code = default_role_code()
|
||||||
selected = set(_normalize_selected_ids(selected_ids))
|
selected = set(_normalize_selected_ids(selected_ids))
|
||||||
current_members = (
|
current_members = _users_for_role(role, active_only=True)
|
||||||
db.session.query(User)
|
|
||||||
.filter(User.role == role.code)
|
|
||||||
.filter(User.status == 'active')
|
|
||||||
.all()
|
|
||||||
)
|
|
||||||
current_ids = {user.id for user in current_members}
|
current_ids = {user.id for user in current_members}
|
||||||
added_ids = [item for item in selected if item not in current_ids]
|
added_ids = [item for item in selected if item not in current_ids]
|
||||||
removed_ids = [item for item in current_ids if item not in selected]
|
removed_ids = [item for item in current_ids if item not in selected]
|
||||||
if role.code == default_code:
|
|
||||||
removed_ids = []
|
|
||||||
users_by_id = {
|
users_by_id = {
|
||||||
user.id: user
|
user.id: user
|
||||||
for user in db.session.query(User).filter(User.id.in_(added_ids + removed_ids)).all()
|
for user in db.session.query(User).filter(User.id.in_(added_ids + removed_ids)).all()
|
||||||
} if added_ids or removed_ids else {}
|
} if added_ids or removed_ids else {}
|
||||||
role_names = list_role_name_map()
|
role_names = list_role_name_map()
|
||||||
|
assigned_map = roles_by_user_ids(added_ids + removed_ids)
|
||||||
|
|
||||||
def _rows(ids: list[int]) -> list[dict[str, Any]]:
|
def _assigned(person: User) -> list[PermissionRole]:
|
||||||
rows = []
|
rows = assigned_map.get(person.id)
|
||||||
for user_id in ids:
|
if rows:
|
||||||
user = users_by_id.get(user_id)
|
return rows
|
||||||
if not user or user_is_platform_admin(user):
|
return list_assigned_roles(person)
|
||||||
continue
|
|
||||||
rows.append(_person_payload(user, role_names))
|
|
||||||
return rows
|
|
||||||
|
|
||||||
added = _rows(added_ids)
|
added = []
|
||||||
removed = _rows(removed_ids)
|
for user_id in added_ids:
|
||||||
stolen = [row for row in added if row['role'] not in {default_code, role.code}]
|
user = users_by_id.get(user_id)
|
||||||
|
if not user or user_is_platform_admin(user):
|
||||||
|
continue
|
||||||
|
current = _assigned(user)
|
||||||
|
nxt = roles_after_grant(current, role)
|
||||||
|
if role.is_default:
|
||||||
|
retained = [item.name for item in nxt if item.id != role.id]
|
||||||
|
else:
|
||||||
|
retained = [item.name for item in nxt if item.id != role.id and not item.is_default]
|
||||||
|
added.append(_person_payload(
|
||||||
|
user,
|
||||||
|
role_names,
|
||||||
|
current,
|
||||||
|
retained_role_names=retained,
|
||||||
|
))
|
||||||
|
removed = []
|
||||||
|
for user_id in removed_ids:
|
||||||
|
user = users_by_id.get(user_id)
|
||||||
|
if not user or user_is_platform_admin(user):
|
||||||
|
continue
|
||||||
|
current = _assigned(user)
|
||||||
|
nxt = roles_after_revoke(current, role)
|
||||||
|
if {item.id for item in nxt} == {item.id for item in current}:
|
||||||
|
continue
|
||||||
|
returns = bool(nxt) and all(item.is_default for item in nxt)
|
||||||
|
retained = [] if returns else [item.name for item in nxt]
|
||||||
|
removed.append(_person_payload(
|
||||||
|
user,
|
||||||
|
role_names,
|
||||||
|
current,
|
||||||
|
retained_role_names=retained,
|
||||||
|
returns_to_default=returns,
|
||||||
|
))
|
||||||
|
stolen = [row for row in added if row['retained_role_names']]
|
||||||
return {
|
return {
|
||||||
'role_code': role.code,
|
'role_code': role.code,
|
||||||
'role_name': role.name,
|
'role_name': role.name,
|
||||||
@@ -562,26 +856,28 @@ def preview_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
|||||||
|
|
||||||
def apply_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
def apply_role_members(code: str, selected_ids: Any) -> dict[str, Any]:
|
||||||
"""
|
"""
|
||||||
确认后写回成员:勾选的人改入本角色;取消勾选的人回到默认角色。
|
确认后写回成员:勾选的人追加本角色;取消勾选的人只移出本角色。
|
||||||
排除管理员;默认角色忽略移出。
|
|
||||||
|
核心逻辑:其他业务角色保留。移出后没有任何角色时回到默认权限组。排除管理员。
|
||||||
"""
|
"""
|
||||||
preview = preview_role_members(code, selected_ids)
|
preview = preview_role_members(code, selected_ids)
|
||||||
role = get_role_by_code(code)
|
role = get_role_by_code(code)
|
||||||
default_code = preview['default_role_code']
|
|
||||||
skipped_admin = 0
|
skipped_admin = 0
|
||||||
for row in preview['added']:
|
for row in preview['added']:
|
||||||
user = db.session.get(User, row['id'])
|
user = db.session.get(User, row['id'])
|
||||||
if not user or user_is_platform_admin(user):
|
if not user or user_is_platform_admin(user):
|
||||||
skipped_admin += 1
|
skipped_admin += 1
|
||||||
continue
|
continue
|
||||||
user.role = role.code
|
current = list_assigned_roles(user)
|
||||||
|
replace_user_roles(user, roles_after_grant(current, role))
|
||||||
sync_user_grants_from_role(user)
|
sync_user_grants_from_role(user)
|
||||||
for row in preview['removed']:
|
for row in preview['removed']:
|
||||||
user = db.session.get(User, row['id'])
|
user = db.session.get(User, row['id'])
|
||||||
if not user or user_is_platform_admin(user):
|
if not user or user_is_platform_admin(user):
|
||||||
skipped_admin += 1
|
skipped_admin += 1
|
||||||
continue
|
continue
|
||||||
user.role = default_code
|
current = list_assigned_roles(user)
|
||||||
|
replace_user_roles(user, roles_after_revoke(current, role))
|
||||||
sync_user_grants_from_role(user)
|
sync_user_grants_from_role(user)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return {
|
return {
|
||||||
@@ -614,13 +910,24 @@ def assert_role_assignable(code: str | None, *, allow_admin: bool) -> str:
|
|||||||
|
|
||||||
def ensure_not_last_admin(user: User, new_role: str) -> None:
|
def ensure_not_last_admin(user: User, new_role: str) -> None:
|
||||||
"""禁止撤掉最后一名启用中的平台管理员。"""
|
"""禁止撤掉最后一名启用中的平台管理员。"""
|
||||||
|
ensure_role_codes_keep_admin(user, [new_role])
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_role_codes_keep_admin(user: User, codes: list[str]) -> None:
|
||||||
|
"""
|
||||||
|
禁止把最后一名启用中的平台管理员改成不含管理组的角色集合。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
codes: 即将写入的角色 code。空列表视为卸下管理身份。
|
||||||
|
"""
|
||||||
if not user_is_platform_admin(user):
|
if not user_is_platform_admin(user):
|
||||||
return
|
return
|
||||||
incoming = get_role_by_code(new_role)
|
for code in codes:
|
||||||
if incoming and incoming.is_platform_admin:
|
incoming = get_role_by_code(code) if roles_configured() else None
|
||||||
return
|
if incoming and incoming.is_platform_admin:
|
||||||
if not roles_configured() and new_role == PLATFORM_ADMIN_CODE:
|
return
|
||||||
return
|
if not roles_configured() and str(code or '') == PLATFORM_ADMIN_CODE:
|
||||||
|
return
|
||||||
others = platform_admin_users_query().filter(User.id != user.id).first()
|
others = platform_admin_users_query().filter(User.id != user.id).first()
|
||||||
if others is None:
|
if others is None:
|
||||||
raise ValidationError('Cannot demote the last platform admin', code='ROLE.LAST_ADMIN')
|
raise ValidationError('Cannot demote the last platform admin', code='ROLE.LAST_ADMIN')
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ backend/app/services/voucher_check/notification.py
|
|||||||
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||||
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
||||||
卡片标题为「销售开票附件缺件提醒」,不写业务方代号和批次号;
|
卡片标题为「销售开票附件缺件提醒」,不写业务方代号和批次号;
|
||||||
|
卡片发出后紧跟本批检核结果 Excel,收件人不用进详情才知道缺哪张票;
|
||||||
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -59,7 +60,7 @@ def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[s
|
|||||||
_friendly_period_label(period_month),
|
_friendly_period_label(period_month),
|
||||||
"销售开票附件已检核,你负责的类型还有缺件:",
|
"销售开票附件已检核,你负责的类型还有缺件:",
|
||||||
*[_missing_type_line(item) for item in items],
|
*[_missing_type_line(item) for item in items],
|
||||||
"请尽快补齐。完整清单见详情里的 Excel。",
|
"请尽快补齐。缺件明细见下一条 Excel。",
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
return "销售开票附件缺件提醒", body
|
return "销售开票附件缺件提醒", body
|
||||||
@@ -113,6 +114,36 @@ def _persist_skip(
|
|||||||
return send_status
|
return send_status
|
||||||
|
|
||||||
|
|
||||||
|
def _send_excel_file(wecom_userid: str, media_id: str) -> bool:
|
||||||
|
"""
|
||||||
|
把已上传的检核结果 Excel 发给一个收件人。
|
||||||
|
核心逻辑:企微文件消息与 textcard 是两条消息,失败只记日志,不回滚已发出的卡片。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
企业微信 errcode 为 0 时为 True。
|
||||||
|
"""
|
||||||
|
from app.services.integrations.wecom.notify import send_wecom_file_message
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = send_wecom_file_message(wecom_userid, media_id)
|
||||||
|
except Exception as exc:
|
||||||
|
current_app.logger.warning(
|
||||||
|
"[voucher-check] excel file failed user=%s err=%s",
|
||||||
|
wecom_userid,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
if data.get("errcode") == 0:
|
||||||
|
return True
|
||||||
|
current_app.logger.warning(
|
||||||
|
"[voucher-check] excel file failed user=%s errcode=%s errmsg=%s",
|
||||||
|
wecom_userid,
|
||||||
|
data.get("errcode"),
|
||||||
|
data.get("errmsg"),
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def send_batch_missing_summary(
|
def send_batch_missing_summary(
|
||||||
*,
|
*,
|
||||||
task: ScheduleTask,
|
task: ScheduleTask,
|
||||||
@@ -122,11 +153,17 @@ def send_batch_missing_summary(
|
|||||||
period_month: str,
|
period_month: str,
|
||||||
stats: dict[str, Any],
|
stats: dict[str, Any],
|
||||||
excel_filename: str | None,
|
excel_filename: str | None,
|
||||||
|
excel_bytes: bytes | None = None,
|
||||||
enabled: bool,
|
enabled: bool,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""
|
"""
|
||||||
按文件类型接收人发送缺件 textcard。
|
按文件类型接收人发送缺件 textcard,并附上本批检核结果 Excel。
|
||||||
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。无缺件或无人可发则写审计不发空消息。
|
核心逻辑:每人一封,只列出该人负责且本批缺失的类型;标题写明销售开票附件,不写业务方代号和批次号。
|
||||||
|
Excel 全批共用一份,上传一次后随卡片发给每个收件人。附件失败不挡住卡片,原因写入审计。
|
||||||
|
无缺件或无人可发则写审计不发空消息。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
excel_bytes: 与排程落库同一份检核结果。为空时只发卡片。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
send_status:sent / skipped_no_missing / skipped_no_recipients / skipped_disabled / failed
|
||||||
@@ -213,9 +250,20 @@ def send_batch_missing_summary(
|
|||||||
_build_jump_url,
|
_build_jump_url,
|
||||||
_create_audit,
|
_create_audit,
|
||||||
send_wecom_textcard_message,
|
send_wecom_textcard_message,
|
||||||
|
upload_wecom_temp_media,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
media_id = None
|
||||||
|
file_note = None
|
||||||
|
if excel_bytes and excel_filename:
|
||||||
|
try:
|
||||||
|
media_id = upload_wecom_temp_media(excel_bytes, excel_filename)
|
||||||
|
except Exception as exc:
|
||||||
|
file_note = "Excel 附件上传失败"
|
||||||
|
current_app.logger.warning("[voucher-check] excel upload failed: %s", exc)
|
||||||
|
|
||||||
ok_any = False
|
ok_any = False
|
||||||
|
file_failed = False
|
||||||
sent_ids: list[int] = []
|
sent_ids: list[int] = []
|
||||||
for user in users:
|
for user in users:
|
||||||
items = plan["user_rules"].get(int(user.id)) or []
|
items = plan["user_rules"].get(int(user.id)) or []
|
||||||
@@ -234,6 +282,8 @@ def send_batch_missing_summary(
|
|||||||
audit.status = "sent"
|
audit.status = "sent"
|
||||||
ok_any = True
|
ok_any = True
|
||||||
sent_ids.append(int(user.id))
|
sent_ids.append(int(user.id))
|
||||||
|
if media_id and not _send_excel_file(user.wecom_userid, media_id):
|
||||||
|
file_failed = True
|
||||||
else:
|
else:
|
||||||
audit.error_code = str(data.get("errcode"))
|
audit.error_code = str(data.get("errcode"))
|
||||||
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
|
audit.error_message = str(data.get("errmsg", "unknown"))[:255]
|
||||||
@@ -244,11 +294,16 @@ def send_batch_missing_summary(
|
|||||||
exc,
|
exc,
|
||||||
)
|
)
|
||||||
|
|
||||||
skip_reason = None
|
if file_failed and not file_note:
|
||||||
|
file_note = "部分 Excel 附件发送失败"
|
||||||
|
reasons: list[str] = []
|
||||||
if not ok_any:
|
if not ok_any:
|
||||||
skip_reason = "企业微信发送失败"
|
reasons.append("企业微信发送失败")
|
||||||
elif plan["unmapped_codes"]:
|
elif plan["unmapped_codes"]:
|
||||||
skip_reason = "部分文件类型未配置接收人"
|
reasons.append("部分文件类型未配置接收人")
|
||||||
|
if file_note:
|
||||||
|
reasons.append(file_note)
|
||||||
|
skip_reason = ";".join(reasons) or None
|
||||||
persist_notification(
|
persist_notification(
|
||||||
run_id=engine_run_id,
|
run_id=engine_run_id,
|
||||||
excel_filename=excel_filename,
|
excel_filename=excel_filename,
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ backend/app/services/voucher_check/runner.py
|
|||||||
用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。
|
用途:销售一期周批次编排(上月清单、目录扫描、按票归档、缺件聚合、Excel、企微汇总)。
|
||||||
依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。
|
依赖:profile_loader、adapters、dms_client、aggregator、engine_persistence、excel_rows、notification。
|
||||||
逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;PO PDF 由 accounting-voucher-po-print(周二 05:00)、销货放行单由 accounting-voucher-oa-sales-release(周二 05:30)提前写入类型目录。
|
逻辑:不调用 erp_po_print.fetch / oa_sales_release.fetch;PO PDF 由 accounting-voucher-po-print(周二 05:00)、销货放行单由 accounting-voucher-oa-sales-release(周二 05:30)提前写入类型目录。
|
||||||
命中文件复制到所有归档,同名跳过仍记 archived。
|
命中文件复制到所有归档,同名跳过仍记 archived。缺件通知附带与排程落库相同的检核结果 Excel。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -28,7 +28,11 @@ from app.services.voucher_check.engine_persistence import (
|
|||||||
persist_engine_results,
|
persist_engine_results,
|
||||||
)
|
)
|
||||||
from app.services.voucher_check.erp_repository import previous_period_bounds
|
from app.services.voucher_check.erp_repository import previous_period_bounds
|
||||||
from app.services.voucher_check.excel_rows import to_excel_invoice_row
|
from app.services.voucher_check.excel_rows import (
|
||||||
|
VOUCHER_CHECK_HEADER_LABELS,
|
||||||
|
VOUCHER_CHECK_HEADER_ORDER,
|
||||||
|
to_excel_invoice_row,
|
||||||
|
)
|
||||||
from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert
|
from app.services.voucher_check.notification import send_batch_missing_summary, send_failure_alert
|
||||||
from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition
|
from app.services.voucher_check.profile_loader import ensure_published_profile, load_profile_definition
|
||||||
from app.services.voucher_check.profiles.sales import required_file_rules
|
from app.services.voucher_check.profiles.sales import required_file_rules
|
||||||
@@ -369,8 +373,18 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
|
|||||||
to_excel_invoice_row(item, period=period, executed_at=executed_at)
|
to_excel_invoice_row(item, period=period, executed_at=executed_at)
|
||||||
for item in stats["excel_rows"]
|
for item in stats["excel_rows"]
|
||||||
]
|
]
|
||||||
|
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||||
|
|
||||||
# [STEP 4] 按文件类型接收人拆成每人一封缺件通知
|
# 与排程落库用同一导出,保证企微附件和事后下载是同一张表。
|
||||||
|
excel_bytes, _, _ = export_schedule_result_excel(
|
||||||
|
run_no=run.run_no,
|
||||||
|
summary={"period": period},
|
||||||
|
details=details,
|
||||||
|
header_order=list(VOUCHER_CHECK_HEADER_ORDER),
|
||||||
|
header_labels=VOUCHER_CHECK_HEADER_LABELS,
|
||||||
|
)
|
||||||
|
|
||||||
|
# [STEP 4] 按文件类型接收人拆成每人一封缺件通知,并附上本批 Excel
|
||||||
notify_status = send_batch_missing_summary(
|
notify_status = send_batch_missing_summary(
|
||||||
task=task,
|
task=task,
|
||||||
schedule_run=run,
|
schedule_run=run,
|
||||||
@@ -379,6 +393,7 @@ def run_voucher_check_batch(task: ScheduleTask, run: ScheduleRun) -> ScheduleExe
|
|||||||
period_month=period,
|
period_month=period,
|
||||||
stats=stats,
|
stats=stats,
|
||||||
excel_filename=excel_filename,
|
excel_filename=excel_filename,
|
||||||
|
excel_bytes=excel_bytes,
|
||||||
enabled=config.notify_missing_enabled,
|
enabled=config.notify_missing_enabled,
|
||||||
)
|
)
|
||||||
step_logs.append(
|
step_logs.append(
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""合并意见反馈附图表与设备验收评审两条 Alembic 头
|
||||||
|
|
||||||
|
Revision ID: 7e5bc4bc0cbc
|
||||||
|
Revises: mh24f5a6b7c8, sxw4m73amjyh
|
||||||
|
Create Date: 2026-10-29 11:00:46.546116
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '7e5bc4bc0cbc'
|
||||||
|
down_revision = ('mh24f5a6b7c8', 'sxw4m73amjyh')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""合并用户多角色与意见反馈附图两条 Alembic 头
|
||||||
|
|
||||||
|
Revision ID: c375467a21f9
|
||||||
|
Revises: 7e5bc4bc0cbc, pr0a1b2c3d4e5
|
||||||
|
Create Date: 2026-10-29 12:41:08.055302
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'c375467a21f9'
|
||||||
|
down_revision = ('7e5bc4bc0cbc', 'pr0a1b2c3d4e5')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""merge migration heads: 合并「用户多角色/意见反馈附图」与「部门树」两条迁移头
|
||||||
|
|
||||||
|
用途:c375467a21f9 与 eff84b4f6171 两条并行迁移链各自成头,导致
|
||||||
|
``flask db upgrade`` 报 Multiple head revisions(见 scripts/check_migration_heads.py)。
|
||||||
|
本迁移仅归并两条链,无任何表结构变更,upgrade/downgrade 均为空操作。
|
||||||
|
|
||||||
|
依赖关系:down_revision 同时挂载两条待归并的迁移头
|
||||||
|
- c375467a21f9(合并用户多角色与意见反馈附图两条 alembic 头)
|
||||||
|
- eff84b4f6171(合并部门树与最新 dev 迁移头)
|
||||||
|
|
||||||
|
逻辑关系:作为迁移图的新唯一 head,位于两条链收敛点之后,
|
||||||
|
后续新迁移应以本 revision 为 down_revision。
|
||||||
|
|
||||||
|
Revision ID: d143df04ab5a
|
||||||
|
Revises: c375467a21f9, eff84b4f6171
|
||||||
|
Create Date: 2026-10-30
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'd143df04ab5a'
|
||||||
|
down_revision = ('c375467a21f9', 'eff84b4f6171')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
"""纯 merge 迁移:仅收敛迁移图,无结构变更。"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
"""拆开 merge 点即回到原两条并行头,无需回滚任何结构。"""
|
||||||
|
pass
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
"""Add department tree columns
|
||||||
|
|
||||||
|
Revision ID: dp1a2b3c4d5e6
|
||||||
|
Revises: 9e5045511198
|
||||||
|
Create Date: 2026-10-08 10:00:00.000000
|
||||||
|
|
||||||
|
用途:departments 表升级为树形结构(parent_id 邻接表 + 同级排序 + 隐藏标记),
|
||||||
|
并放开 name 全局唯一约束(多公司允许同名部门,改由 service 层做同级查重)。
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'dp1a2b3c4d5e6'
|
||||||
|
down_revision = '9e5045511198'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
conn = op.get_bind()
|
||||||
|
insp = sa.inspect(conn)
|
||||||
|
tables = set(insp.get_table_names())
|
||||||
|
|
||||||
|
if 'departments' not in tables:
|
||||||
|
# 防御:空库直接按新结构建表
|
||||||
|
op.create_table(
|
||||||
|
'departments',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('code', sa.String(length=50), nullable=True),
|
||||||
|
sa.Column('company', sa.String(length=100), nullable=True),
|
||||||
|
sa.Column('description', sa.Text(), nullable=True),
|
||||||
|
sa.Column('parent_id', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'),
|
||||||
|
sa.Column('is_hidden', sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('code'),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
['parent_id'], ['departments.id'], name='fk_departments_parent_id_departments'
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
cols = {c['name'] for c in insp.get_columns('departments')}
|
||||||
|
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||||
|
if 'parent_id' not in cols:
|
||||||
|
batch_op.add_column(sa.Column('parent_id', sa.Integer(), nullable=True))
|
||||||
|
if 'sort_order' not in cols:
|
||||||
|
batch_op.add_column(sa.Column('sort_order', sa.Integer(), nullable=False, server_default='0'))
|
||||||
|
if 'is_hidden' not in cols:
|
||||||
|
batch_op.add_column(sa.Column('is_hidden', sa.Boolean(), nullable=False, server_default=sa.false()))
|
||||||
|
|
||||||
|
# 重新内省后再补自关联外键(列可能由上一步刚添加)
|
||||||
|
insp2 = sa.inspect(conn)
|
||||||
|
fks = insp2.get_foreign_keys('departments')
|
||||||
|
has_parent_fk = any(
|
||||||
|
'parent_id' in (fk.get('constrained_columns') or []) for fk in fks
|
||||||
|
)
|
||||||
|
if not has_parent_fk:
|
||||||
|
op.create_foreign_key(
|
||||||
|
'fk_departments_parent_id_departments', 'departments', 'departments',
|
||||||
|
['parent_id'], ['id'],
|
||||||
|
)
|
||||||
|
|
||||||
|
# 放开 name 全局唯一:删除覆盖 name 列的 unique 约束(同名约束名在不同库不一致,按列名探测)
|
||||||
|
name_uq_names = [
|
||||||
|
uq['name'] for uq in insp2.get_unique_constraints('departments')
|
||||||
|
if set(uq.get('column_names') or []) == {'name'} and uq.get('name')
|
||||||
|
]
|
||||||
|
if name_uq_names:
|
||||||
|
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||||
|
for uq_name in name_uq_names:
|
||||||
|
batch_op.drop_constraint(uq_name, type_='unique')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
conn = op.get_bind()
|
||||||
|
insp = sa.inspect(conn)
|
||||||
|
if 'departments' not in set(insp.get_table_names()):
|
||||||
|
return
|
||||||
|
|
||||||
|
cols = {c['name'] for c in insp.get_columns('departments')}
|
||||||
|
with op.batch_alter_table('departments', schema=None) as batch_op:
|
||||||
|
if 'is_hidden' in cols:
|
||||||
|
batch_op.drop_column('is_hidden')
|
||||||
|
if 'sort_order' in cols:
|
||||||
|
batch_op.drop_column('sort_order')
|
||||||
|
if 'parent_id' in cols:
|
||||||
|
try:
|
||||||
|
batch_op.drop_constraint('fk_departments_parent_id_departments', type_='foreignkey')
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
batch_op.drop_column('parent_id')
|
||||||
|
# 恢复 name 全局唯一;若历史数据存在重名会失败,需先清洗数据
|
||||||
|
try:
|
||||||
|
batch_op.create_unique_constraint('uq_departments_name', ['name'])
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""merge department tree and latest dev migration heads
|
||||||
|
|
||||||
|
Revision ID: eff84b4f6171
|
||||||
|
Revises: fa1d22f99de9, pr0a1b2c3d4e5
|
||||||
|
Create Date: 2026-10-29 17:06:07.732022
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'eff84b4f6171'
|
||||||
|
down_revision = ('fa1d22f99de9', 'pr0a1b2c3d4e5')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
"""merge department tree and dev migration heads
|
||||||
|
|
||||||
|
Revision ID: fa1d22f99de9
|
||||||
|
Revises: dp1a2b3c4d5e6, eah8c9d0e1f2
|
||||||
|
Create Date: 2026-10-22 13:19:23.491330
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'fa1d22f99de9'
|
||||||
|
down_revision = ('dp1a2b3c4d5e6', 'eah8c9d0e1f2')
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
"""Add user-to-permission-role membership.
|
||||||
|
|
||||||
|
Revision ID: pr0a1b2c3d4e5
|
||||||
|
Revises: mh24f5a6b7c8
|
||||||
|
Create Date: 2026-10-29 09:55:00.000000
|
||||||
|
|
||||||
|
用途:用户与权限组改为一对多,支持同时挂多个业务角色。
|
||||||
|
依赖:users、permission_roles。
|
||||||
|
逻辑:建 user_permission_roles,并按现有 users.role 回填一行成员关系。users.role 保留为主角色。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
revision = "pr0a1b2c3d4e5"
|
||||||
|
down_revision = "mh24f5a6b7c8"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.create_table(
|
||||||
|
"user_permission_roles",
|
||||||
|
sa.Column("user_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("role_id", sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(["role_id"], ["permission_roles.id"], ondelete="CASCADE"),
|
||||||
|
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
|
||||||
|
sa.PrimaryKeyConstraint("user_id", "role_id"),
|
||||||
|
)
|
||||||
|
op.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO user_permission_roles (user_id, role_id)
|
||||||
|
SELECT u.id, pr.id
|
||||||
|
FROM users u
|
||||||
|
JOIN permission_roles pr ON pr.code = u.role
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_table("user_permission_roles")
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
"""add general_feedback_images table
|
||||||
|
|
||||||
|
backend/migrations/versions/sxw4m73amjyh_add_general_feedback_images.py
|
||||||
|
用途:创建意见反馈截图附件关联表 general_feedback_images,一条反馈可挂多张截图(asset_id 唯一,一图只挂一条反馈)。
|
||||||
|
依赖:mh23e4f5a6b7(FAQ 模糊匹配与库存异动自然键两条迁移头的合并节点,当前唯一 head)。
|
||||||
|
逻辑:upgrade 仅建表(id/feedback_id/asset_id/sort_order/created_at + feedback_id 索引 + asset_id 唯一约束);
|
||||||
|
downgrade 按相反顺序删索引、删表;删除反馈时级联删除附件为 ORM 层行为(GeneralFeedback.images cascade)。
|
||||||
|
|
||||||
|
Revision ID: sxw4m73amjyh
|
||||||
|
Revises: mh23e4f5a6b7
|
||||||
|
Create Date: 2026-10-26 16:11:31.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'sxw4m73amjyh'
|
||||||
|
down_revision = 'mh23e4f5a6b7'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table(
|
||||||
|
'general_feedback_images',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('feedback_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('asset_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('sort_order', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['asset_id'], ['file_assets.id'], ),
|
||||||
|
sa.ForeignKeyConstraint(['feedback_id'], ['general_feedbacks.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('asset_id'),
|
||||||
|
)
|
||||||
|
op.create_index(
|
||||||
|
op.f('ix_general_feedback_images_feedback_id'),
|
||||||
|
'general_feedback_images',
|
||||||
|
['feedback_id'],
|
||||||
|
unique=False,
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_index(
|
||||||
|
op.f('ix_general_feedback_images_feedback_id'),
|
||||||
|
table_name='general_feedback_images',
|
||||||
|
)
|
||||||
|
op.drop_table('general_feedback_images')
|
||||||
|
# ### end Alembic commands ###
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"_comment": "hrao00 -> 公司中文名。来源 ERP dc.HRAA_FILE(hraa01=公司编号,hraa02=公司名称)。0000 集团公司无部门,保留映射以备后续。",
|
||||||
|
"0000": "集团公司",
|
||||||
|
"0001": "电子",
|
||||||
|
"0002": "科技",
|
||||||
|
"0003": "和信",
|
||||||
|
"0004": "泰国合欣",
|
||||||
|
"0005": "台湾尊场",
|
||||||
|
"0006": "无锡和宏智",
|
||||||
|
"0007": "上海数智"
|
||||||
|
}
|
||||||
@@ -0,0 +1,358 @@
|
|||||||
|
"""Import ERP HRAO_FILE departments into the local department tree.
|
||||||
|
|
||||||
|
Purpose: one-shot import of the Tiptop department master (ERP `dc.HRAO_FILE`) exported as
|
||||||
|
CSV from DBeaver into the local `departments` tree, upserting by department code (hrao01).
|
||||||
|
Dependencies: Flask app context, SQLAlchemy models, csv/json stdlib (no Oracle driver).
|
||||||
|
Flow: dry-run is the default and only prints a validation report; pass `--apply` to write.
|
||||||
|
hrao06 parent codes resolve to hrao01 after all rows are upserted; dangling parents and
|
||||||
|
cycles fall back to top-level with a report. Local rows whose code is absent from the ERP
|
||||||
|
file are kept untouched (per the agreed merge policy). `users.department` links by name
|
||||||
|
text, so renames are reported for manual re-linking instead of being rewritten here.
|
||||||
|
|
||||||
|
Usage (from backend/):
|
||||||
|
python scripts/import_departments_from_hrao.py --file scripts/data/hrao_departments.csv
|
||||||
|
python scripts/import_departments_from_hrao.py --file ... --apply
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from collections import Counter
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
if str(BACKEND_ROOT) not in sys.path:
|
||||||
|
sys.path.insert(0, str(BACKEND_ROOT))
|
||||||
|
|
||||||
|
from app import create_app
|
||||||
|
from app.extensions import db
|
||||||
|
from app.models import Department, User
|
||||||
|
|
||||||
|
DEFAULT_CSV = Path("scripts/data/hrao_departments.csv")
|
||||||
|
DEFAULT_COMPANY_MAP = Path("scripts/data/hrao_company_map.json")
|
||||||
|
HIDDEN_MODES = ("ignore", "n_is_hidden", "not_y_is_hidden")
|
||||||
|
|
||||||
|
|
||||||
|
def _clean(value: Any) -> str:
|
||||||
|
"""Trim a CSV cell to a normalized string ('' for None)."""
|
||||||
|
return str(value or "").strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _read_csv(path: Path) -> list[dict[str, str]]:
|
||||||
|
"""Read the DBeaver CSV export; headers are normalized to lowercase (utf-8 with BOM tolerated).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: CSV file exported from `SELECT hrao00, hrao01, hrao02, hrao03, hrao06, hrao09, ... FROM dc.HRAO_FILE`.
|
||||||
|
Returns:
|
||||||
|
List of row dicts keyed by lowercase column names (hrao00 ...).
|
||||||
|
Raises:
|
||||||
|
SystemExit: file missing or no recognizable hrao01 header.
|
||||||
|
"""
|
||||||
|
if not path.exists():
|
||||||
|
raise SystemExit(f"CSV not found: {path}\n先在 DBeaver 导出 HRAO 查询结果为 CSV(UTF-8),再放到该路径。")
|
||||||
|
import csv
|
||||||
|
|
||||||
|
with path.open(encoding="utf-8-sig", newline="") as fh:
|
||||||
|
reader = csv.DictReader(fh)
|
||||||
|
rows = [
|
||||||
|
{(k or "").strip().lower(): (v or "") for k, v in raw.items()}
|
||||||
|
for raw in reader
|
||||||
|
]
|
||||||
|
if rows and not any("hrao01" in row for row in rows[:1]):
|
||||||
|
raise SystemExit(f"CSV 首行未找到 hrao01 列头,请确认导出来自 HRAO_FILE 查询:{path}")
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def _load_company_map(path: Path) -> dict[str, str]:
|
||||||
|
"""Load hrao00 -> company display name mapping from a JSON file.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
SystemExit: mapping file missing (with a template hint).
|
||||||
|
"""
|
||||||
|
if not path.exists():
|
||||||
|
raise SystemExit(
|
||||||
|
f"公司映射文件不存在:{path}\n"
|
||||||
|
'请创建 JSON:{"0002": "苏州和信精密科技有限公司", ...}(hrao00 -> 公司中文名)。'
|
||||||
|
)
|
||||||
|
data = json.loads(path.read_text(encoding="utf-8"))
|
||||||
|
return {_clean(k): _clean(v) for k, v in data.items() if _clean(k)}
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_hidden(hrao08: str, mode: str) -> bool:
|
||||||
|
"""Map hrao08 (在组织框架图中显示否) to is_hidden per the chosen mode.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
mode: ignore(默认,全部不隐藏)| n_is_hidden(N=不显示→隐藏)| not_y_is_hidden(非 Y 即隐藏)。
|
||||||
|
"""
|
||||||
|
flag = _clean(hrao08).upper()
|
||||||
|
if mode == "n_is_hidden":
|
||||||
|
return flag == "N"
|
||||||
|
if mode == "not_y_is_hidden":
|
||||||
|
return flag != "Y"
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_rows(
|
||||||
|
raw_rows: list[dict[str, str]], hidden_mode: str
|
||||||
|
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||||
|
"""Normalize CSV rows into import payloads; duplicate hrao01 keeps the first occurrence.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(rows, problems) — rows keyed by code with name/company_code/parent_code/sort_order/is_hidden.
|
||||||
|
"""
|
||||||
|
rows: dict[str, dict[str, Any]] = {}
|
||||||
|
problems: list[str] = []
|
||||||
|
for raw in raw_rows:
|
||||||
|
code = _clean(raw.get("hrao01"))
|
||||||
|
name = _clean(raw.get("hrao02")) or _clean(raw.get("hrao03"))
|
||||||
|
if not code:
|
||||||
|
problems.append(f"跳过:hrao01 为空(hrao02={_clean(raw.get('hrao02'))!r})")
|
||||||
|
continue
|
||||||
|
if not name:
|
||||||
|
problems.append(f"跳过:{code} 部门名称为空(hrao02/hrao03 均空)")
|
||||||
|
continue
|
||||||
|
if code in rows:
|
||||||
|
problems.append(f"跳过重复编码:{code} 第二次出现({name!r}),保留首行")
|
||||||
|
continue
|
||||||
|
sort_raw = _clean(raw.get("hrao09"))
|
||||||
|
parent = _clean(raw.get("hrao06"))
|
||||||
|
rows[code] = {
|
||||||
|
"code": code,
|
||||||
|
"name": name,
|
||||||
|
"company_code": _clean(raw.get("hrao00")),
|
||||||
|
"parent_code": parent if parent and parent != "0" else None,
|
||||||
|
"sort_order": int(sort_raw) if sort_raw.isdigit() else 0,
|
||||||
|
"is_hidden": _parse_hidden(raw.get("hrao08"), hidden_mode),
|
||||||
|
}
|
||||||
|
return list(rows.values()), problems
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_parents(rows: list[dict[str, Any]]) -> tuple[dict[str, Optional[str]], list[str]]:
|
||||||
|
"""Resolve each row's parent code; dangling/self references fall back to top-level.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(parent_by_code, problems) — parent codes or None for top-level.
|
||||||
|
"""
|
||||||
|
codes = {r["code"] for r in rows}
|
||||||
|
parent_by_code: dict[str, Optional[str]] = {}
|
||||||
|
problems: list[str] = []
|
||||||
|
for row in rows:
|
||||||
|
parent = row["parent_code"]
|
||||||
|
if parent is not None and (parent not in codes or parent == row["code"]):
|
||||||
|
problems.append(f"悬空上级:{row['code']} {row['name']} 的 hrao06={parent!r} 匹配不到 hrao01,按顶级导入")
|
||||||
|
parent = None
|
||||||
|
parent_by_code[row["code"]] = parent
|
||||||
|
return parent_by_code, problems
|
||||||
|
|
||||||
|
|
||||||
|
def _break_cycles(
|
||||||
|
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
|
||||||
|
) -> tuple[dict[str, Optional[str]], list[str]]:
|
||||||
|
"""Rows caught in a parent cycle (e.g. A->B->A) are detached to top-level.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(parent_by_code, problems)
|
||||||
|
"""
|
||||||
|
problems: list[str] = []
|
||||||
|
for row in rows:
|
||||||
|
seen: set[str] = set()
|
||||||
|
cursor: Optional[str] = row["code"]
|
||||||
|
cyclic = False
|
||||||
|
while cursor and parent_by_code.get(cursor):
|
||||||
|
if cursor in seen:
|
||||||
|
cyclic = True
|
||||||
|
break
|
||||||
|
seen.add(cursor)
|
||||||
|
cursor = parent_by_code[cursor]
|
||||||
|
if cyclic:
|
||||||
|
name = next(r["name"] for r in rows if r["code"] == row["code"])
|
||||||
|
problems.append(f"成环:{row['code']} {name} 的上级链形成环,整链按顶级导入")
|
||||||
|
parent_by_code[row["code"]] = None
|
||||||
|
return parent_by_code, problems
|
||||||
|
|
||||||
|
|
||||||
|
def _find_name_conflicts(
|
||||||
|
rows: list[dict[str, Any]], parent_by_code: dict[str, Optional[str]]
|
||||||
|
) -> list[str]:
|
||||||
|
"""Same-parent (or same-company top-level) duplicate names would fail sibling validation."""
|
||||||
|
buckets: Counter = Counter()
|
||||||
|
for row in rows:
|
||||||
|
parent = parent_by_code[row["code"]]
|
||||||
|
company = row["company_code"] if parent is None else parent
|
||||||
|
buckets[(company, parent, row["name"])] += 1
|
||||||
|
return [
|
||||||
|
f"同级重名:{name!r}(公司/父={key})出现 {count} 次,需人工改名后再导入"
|
||||||
|
for (key, _, name), count in buckets.items()
|
||||||
|
if count > 1
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def plan_import(
|
||||||
|
rows: list[dict[str, Any]],
|
||||||
|
company_map: dict[str, str],
|
||||||
|
allow_unmapped: bool,
|
||||||
|
) -> tuple[dict[str, Any], list[str]]:
|
||||||
|
"""Diff ERP rows against local departments into an upsert plan.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
rows: normalized ERP rows.
|
||||||
|
company_map: hrao00 -> company display name.
|
||||||
|
allow_unmapped: when False, unmapped hrao00 aborts the plan (apply refuses).
|
||||||
|
Returns:
|
||||||
|
(plan, problems) — plan holds inserts/updates/kept/dangling etc. for the reporter.
|
||||||
|
"""
|
||||||
|
problems: list[str] = []
|
||||||
|
unmapped = sorted({r["company_code"] for r in rows if r["company_code"] and r["company_code"] not in company_map})
|
||||||
|
if unmapped and not allow_unmapped:
|
||||||
|
problems.append(f"未映射的公司编码:{unmapped}(补 hrao_company_map.json 或加 --allow-unmapped)")
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
row["company"] = company_map.get(row["company_code"])
|
||||||
|
|
||||||
|
local_by_code = {d.code: d for d in db.session.query(Department).all()}
|
||||||
|
inserts = [r for r in rows if r["code"] not in local_by_code]
|
||||||
|
updates = [
|
||||||
|
{"local": local_by_code[r["code"]], "row": r}
|
||||||
|
for r in rows
|
||||||
|
if r["code"] in local_by_code
|
||||||
|
]
|
||||||
|
kept = sorted(set(local_by_code) - {r["code"] for r in rows})
|
||||||
|
|
||||||
|
renames = []
|
||||||
|
for item in updates:
|
||||||
|
old_name = item["local"].name
|
||||||
|
if old_name != item["row"]["name"]:
|
||||||
|
linked = db.session.query(User).filter(User.department == old_name).count()
|
||||||
|
renames.append((old_name, item["row"]["name"], linked))
|
||||||
|
|
||||||
|
plan = {
|
||||||
|
"inserts": inserts,
|
||||||
|
"updates": updates,
|
||||||
|
"kept": kept,
|
||||||
|
"renames": renames,
|
||||||
|
"unmapped": unmapped,
|
||||||
|
}
|
||||||
|
return plan, problems
|
||||||
|
|
||||||
|
|
||||||
|
def apply_plan(plan: dict[str, Any], parent_by_code: dict[str, Optional[str]]) -> tuple[int, int]:
|
||||||
|
"""Execute the plan in one transaction; parents are linked after ids exist.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
(created, updated) row counts.
|
||||||
|
"""
|
||||||
|
code_to_id = {d.code: d.id for d in db.session.query(Department).all()}
|
||||||
|
created = updated = 0
|
||||||
|
# [STEP 1] 先落行(parent_id 暂空),拿到主键后再统一挂父,避免插入顺序依赖
|
||||||
|
for row in plan["inserts"]:
|
||||||
|
dept = Department(
|
||||||
|
name=row["name"],
|
||||||
|
code=row["code"],
|
||||||
|
company=row["company"],
|
||||||
|
parent_id=None,
|
||||||
|
sort_order=row["sort_order"],
|
||||||
|
is_hidden=row["is_hidden"],
|
||||||
|
)
|
||||||
|
db.session.add(dept)
|
||||||
|
db.session.flush()
|
||||||
|
code_to_id[row["code"]] = dept.id
|
||||||
|
created += 1
|
||||||
|
# [STEP 2] 更新已存在行(按编码 upsert,保留本地多余行)
|
||||||
|
for item in plan["updates"]:
|
||||||
|
local, row = item["local"], item["row"]
|
||||||
|
local.name = row["name"]
|
||||||
|
local.company = row["company"]
|
||||||
|
local.sort_order = row["sort_order"]
|
||||||
|
local.is_hidden = row["is_hidden"]
|
||||||
|
updated += 1
|
||||||
|
# [STEP 3] 挂上级:本地已有编码或本次新插入的编码都可作为父
|
||||||
|
for row in plan["inserts"] + [i["row"] for i in plan["updates"]]:
|
||||||
|
parent_code = parent_by_code[row["code"]]
|
||||||
|
if parent_code:
|
||||||
|
db.session.get(Department, code_to_id[row["code"]]).parent_id = code_to_id.get(parent_code)
|
||||||
|
db.session.commit()
|
||||||
|
return created, updated
|
||||||
|
|
||||||
|
|
||||||
|
def _print_report(
|
||||||
|
rows: list[dict[str, Any]],
|
||||||
|
plan: dict[str, Any],
|
||||||
|
problems: list[str],
|
||||||
|
company_map: dict[str, str],
|
||||||
|
raw_rows: list[dict[str, str]],
|
||||||
|
) -> None:
|
||||||
|
"""Print the dry-run/apply report; problem lines always warn before the summary."""
|
||||||
|
companies = Counter(r["company_code"] for r in rows)
|
||||||
|
print("== 公司分布(hrao00 -> 行数)==")
|
||||||
|
for code, count in sorted(companies.items()):
|
||||||
|
print(f" {code or '(空)'} x{count} -> {company_map.get(code, '(未映射)')}")
|
||||||
|
if plan["unmapped"]:
|
||||||
|
print(f" ⚠ 未映射编码:{plan['unmapped']}")
|
||||||
|
print(f"== 汇总 == ERP 行 {len(rows)};插入 {len(plan['inserts'])};更新 {len(plan['updates'])};本地保留 {len(plan['kept'])}")
|
||||||
|
if plan["renames"]:
|
||||||
|
print("== 更名(users.department 按名称关联,需人工重挂)==")
|
||||||
|
for old, new, linked in plan["renames"]:
|
||||||
|
print(f" {old!r} -> {new!r}(名下员工 {linked} 人)")
|
||||||
|
for line in problems:
|
||||||
|
print(f" ⚠ {line}")
|
||||||
|
if not any("⚠" in line for line in problems) and not plan["renames"]:
|
||||||
|
print(" (无告警)")
|
||||||
|
# hrao 标志位分布,帮助确认 is_hidden 映射是否正确
|
||||||
|
for col in ("hrao05", "hrao07", "hrao08"):
|
||||||
|
dist = Counter(_clean(r.get(col)).upper() for r in raw_rows)
|
||||||
|
print(f"== {col} 取值分布 == {dict(dist)}")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""Parse args, build the plan, and write only with --apply (single transaction)."""
|
||||||
|
parser = argparse.ArgumentParser(description="Import ERP HRAO_FILE departments (CSV) into the local tree")
|
||||||
|
parser.add_argument("--file", type=Path, default=DEFAULT_CSV, help="DBeaver 导出的 HRAO CSV 路径")
|
||||||
|
parser.add_argument("--company-map", type=Path, default=DEFAULT_COMPANY_MAP, help="hrao00 -> 公司名 JSON")
|
||||||
|
parser.add_argument("--hidden-mode", choices=HIDDEN_MODES, default="ignore",
|
||||||
|
help="hrao08 -> is_hidden 映射;默认 ignore(不隐藏)")
|
||||||
|
parser.add_argument("--allow-unmapped", action="store_true", help="允许未映射公司编码(company 置空)")
|
||||||
|
parser.add_argument("--company", action="append", default=None,
|
||||||
|
help="只导入指定 hrao00 的公司(可多次传入,如 --company 0003);缺省导入全部")
|
||||||
|
parser.add_argument("--apply", action="store_true", help="真正写库;缺省仅 dry-run 预览")
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
company_map = _load_company_map(args.company_map)
|
||||||
|
raw_rows = _read_csv(args.file)
|
||||||
|
rows, problems = _normalize_rows(raw_rows, args.hidden_mode)
|
||||||
|
if args.company:
|
||||||
|
wanted = {c.strip() for c in args.company}
|
||||||
|
missing = wanted - {r["company_code"] for r in rows}
|
||||||
|
if missing:
|
||||||
|
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
|
||||||
|
rows = [r for r in rows if r["company_code"] in wanted]
|
||||||
|
if args.company:
|
||||||
|
wanted = {c.strip() for c in args.company}
|
||||||
|
missing = wanted - {r["company_code"] for r in rows}
|
||||||
|
if missing:
|
||||||
|
raise SystemExit(f"CSV 中不存在这些公司编码:{sorted(missing)}")
|
||||||
|
rows = [r for r in rows if r["company_code"] in wanted]
|
||||||
|
parent_by_code, parent_problems = _resolve_parents(rows)
|
||||||
|
parent_by_code, cycle_problems = _break_cycles(rows, parent_by_code)
|
||||||
|
problems += parent_problems + cycle_problems
|
||||||
|
problems += _find_name_conflicts(rows, parent_by_code)
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
|
with app.app_context():
|
||||||
|
plan, plan_problems = plan_import(rows, company_map, args.allow_unmapped)
|
||||||
|
problems += plan_problems
|
||||||
|
_print_report(rows, plan, problems, company_map, raw_rows)
|
||||||
|
fatal = [p for p in problems if "需人工" in p or "未映射的公司编码" in p]
|
||||||
|
if args.apply and not fatal:
|
||||||
|
created, updated = apply_plan(plan, parent_by_code)
|
||||||
|
print(f"✅ 已写入:插入 {created},更新 {updated}(事务已提交)")
|
||||||
|
elif args.apply:
|
||||||
|
raise SystemExit("存在需人工处理的告警,已阻止写库;处理后重试或加对应参数。")
|
||||||
|
else:
|
||||||
|
print("(dry-run 未写库;确认无误后加 --apply 执行)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
"""通用意见反馈提交 API 契约测试(POST /api/user/feedback 携带图片资产)。
|
||||||
|
|
||||||
|
用途:锁定反馈提交接口外部契约——image_asset_nos 按顺序落 general_feedback_images
|
||||||
|
并把 FileAsset 置为 referenced(reference_count+1、expires_at 清空),
|
||||||
|
他人资产/非图片/已被引用/超 5 张等非法输入整单拒绝且不落任何行
|
||||||
|
(FILE_ASSET.* 与 FEEDBACK.IMAGE_* 错误码),纯文本提交保持旧契约。
|
||||||
|
依赖:app/client 夹具(create_app('testing') + create_all)、issue_local_access_token、
|
||||||
|
parse_api_error(错误 envelope 断言);前置数据直接落 User/FileAsset 行。
|
||||||
|
逻辑:校验逻辑由 handlers.submit_general_feedback 承载,本文件只测 API 壳
|
||||||
|
(鉴权/状态码/错误码/落库副作用/回归路径)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.core.auth.jwt import issue_local_access_token
|
||||||
|
from app.models import FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
||||||
|
from tests.conftest import parse_api_error
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _disable_wecom_feedback_notify(app):
|
||||||
|
"""测试绝不触发真实企微群通知(2026-10-26 曾因未隔离 webhook 向真实群发出消息)。"""
|
||||||
|
app.config["WECOM_FEEDBACK_NOTIFY_ENABLED"] = False
|
||||||
|
|
||||||
|
|
||||||
|
def _headers(user: User) -> dict:
|
||||||
|
"""为指定用户签发 Bearer JWT 请求头(须在 app context 内调用)。"""
|
||||||
|
token = issue_local_access_token(user)
|
||||||
|
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||||
|
|
||||||
|
|
||||||
|
def _create_user(username: str, role: str = "user") -> User:
|
||||||
|
"""按用户名幂等落一个测试用户。"""
|
||||||
|
user = db.session.query(User).filter_by(username=username).first()
|
||||||
|
if not user:
|
||||||
|
user = User(username=username, email=f"{username}@example.com", role=role, status="active")
|
||||||
|
user.set_password("x")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def user_headers(app):
|
||||||
|
"""普通用户 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
return _headers(_create_user("fbuser"))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def admin_headers(app):
|
||||||
|
"""平台管理员 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
return _headers(_create_user("fbadmin", role="admin"))
|
||||||
|
|
||||||
|
|
||||||
|
def _make_asset(user_id: int, ext: str = "png", mime: str = "image/png", *, reference_count: int = 0, lifecycle: str = "temporary") -> FileAsset:
|
||||||
|
"""直接落一条 ready/temporary 的 FileAsset 行(不经过 MinIO)。"""
|
||||||
|
asset = FileAsset(
|
||||||
|
asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id),
|
||||||
|
original_filename=f"screenshot.{ext}", storage_provider="minio", storage_bucket="test",
|
||||||
|
storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024,
|
||||||
|
mime_type=mime, extension=ext, upload_status="ready",
|
||||||
|
lifecycle_status=lifecycle, reference_count=reference_count,
|
||||||
|
)
|
||||||
|
db.session.add(asset)
|
||||||
|
db.session.commit()
|
||||||
|
return asset
|
||||||
|
|
||||||
|
|
||||||
|
def _submit_payload(**overrides) -> dict:
|
||||||
|
"""合法反馈提交载荷基线(纯文本,不带图片)。"""
|
||||||
|
payload = {
|
||||||
|
"feedback_type": "问题反馈", "feedback_module": "知识库", "content": "测试反馈内容",
|
||||||
|
"source_page": "workspace",
|
||||||
|
}
|
||||||
|
payload.update(overrides)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_with_images_claims_assets(app, client, user_headers):
|
||||||
|
"""带图提交:两图按顺序落库,资产被引用(reference_count=1、referenced、expires_at 清空)。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
a2 = _make_asset(u.id, ext="jpg", mime="image/jpeg")
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
asset_nos = [a1.asset_no, a2.asset_no]
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json={
|
||||||
|
"feedback_type": "问题反馈", "feedback_module": "知识库", "content": "带上截图",
|
||||||
|
"source_page": "workspace", "image_asset_nos": asset_nos,
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
with app.app_context():
|
||||||
|
imgs = GeneralFeedbackImage.query.order_by(GeneralFeedbackImage.sort_order).all()
|
||||||
|
assert [i.sort_order for i in imgs] == [0, 1]
|
||||||
|
for i in imgs:
|
||||||
|
asset = db.session.get(FileAsset, i.asset_id)
|
||||||
|
assert asset.reference_count == 1
|
||||||
|
assert asset.lifecycle_status == "referenced"
|
||||||
|
assert asset.expires_at is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_foreign_asset(app, client, user_headers):
|
||||||
|
"""他人资产 → 403 FILE_ASSET.FORBIDDEN,反馈不落库。"""
|
||||||
|
with app.app_context():
|
||||||
|
other = _create_user("fbother")
|
||||||
|
foreign = _make_asset(other.id)
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
foreign_no = foreign.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="挂别人资产", image_asset_nos=[foreign_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 403
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FILE_ASSET.FORBIDDEN"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行:反馈与图片关联均为零
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_non_image(app, client, user_headers):
|
||||||
|
"""ext='pdf' 的资产 → 400 FEEDBACK.IMAGE_INVALID。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
pdf_asset = _make_asset(u.id, ext="pdf", mime="application/pdf")
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
pdf_no = pdf_asset.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="挂非图片", image_asset_nos=[pdf_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_INVALID"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_referenced_asset(app, client, user_headers):
|
||||||
|
"""reference_count=1 的图片资产 → 400 FEEDBACK.IMAGE_INVALID(防挂已被业务引用资产)。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
used = _make_asset(u.id, reference_count=1)
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
used_no = used.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="挂已引用资产", image_asset_nos=[used_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_INVALID"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_rejects_too_many(app, client, user_headers):
|
||||||
|
"""6 个 asset_no → 400 FEEDBACK.IMAGE_TOO_MANY,反馈不落库。"""
|
||||||
|
asset_nos = [f"FA-TEST-{i:04d}" for i in range(6)]
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="一次挂六张", image_asset_nos=asset_nos,
|
||||||
|
))
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_TOO_MANY"
|
||||||
|
with app.app_context():
|
||||||
|
# 拒绝路径不落任何行
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_submit_text_only_keeps_legacy(app, client, user_headers):
|
||||||
|
"""不带 image_asset_nos:200,general_feedback_images 零行(回归)。"""
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload())
|
||||||
|
assert resp.status_code == 200
|
||||||
|
body = resp.get_json()
|
||||||
|
assert body.get("status") == "ok"
|
||||||
|
assert isinstance(body.get("id"), int)
|
||||||
|
with app.app_context():
|
||||||
|
assert GeneralFeedbackImage.query.count() == 0
|
||||||
|
assert GeneralFeedback.query.count() == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_rows_include_images(app, client, user_headers, admin_headers):
|
||||||
|
"""报表行含 images 元数据;无图行 images==[]。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
# asset_no 须在 app context 内取出:context 弹出后 ORM 实例已脱管,属性不可再读
|
||||||
|
asset_no = a1.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="带图反馈", image_asset_nos=[asset_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
with_image_id = resp.get_json()["id"]
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(content="纯文本反馈"))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
text_only_id = resp.get_json()["id"]
|
||||||
|
|
||||||
|
resp = client.get("/api/admin/reports/general-feedbacks", headers=admin_headers)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
rows = resp.get_json()
|
||||||
|
rows_by_id = {row["id"]: row for row in rows}
|
||||||
|
# 有图行:images[0] 键集合恰为 5 个元数据键,asset_no 与提交资产一致
|
||||||
|
with_image_row = rows_by_id[with_image_id]
|
||||||
|
assert len(with_image_row["images"]) == 1
|
||||||
|
assert set(with_image_row["images"][0].keys()) == {
|
||||||
|
"image_id", "asset_no", "original_filename", "file_size", "sort_order",
|
||||||
|
}
|
||||||
|
assert with_image_row["images"][0]["asset_no"] == asset_no
|
||||||
|
# 无图行:images 置空列表而非缺键
|
||||||
|
assert rows_by_id[text_only_id]["images"] == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_admin_image_raw_streams(app, client, user_headers, admin_headers, monkeypatch):
|
||||||
|
"""管理员经 raw 接口取到图片字节(Content-Type 按扩展名固定 + nosniff);错配 feedback_id → 404 FEEDBACK.IMAGE_NOT_FOUND;非管理员 → 403。"""
|
||||||
|
# 隔离 MinIO:读取字节走本地假实现,提交仍只落库不触对象存储
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"app.services.file_assets.service.file_asset_storage.get_bytes",
|
||||||
|
lambda key: b"\x89PNG\r\n\x1a\nfake",
|
||||||
|
)
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
asset_no = a1.asset_no
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json=_submit_payload(
|
||||||
|
content="取图反馈", image_asset_nos=[asset_no],
|
||||||
|
))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
fb_id = resp.get_json()["id"]
|
||||||
|
with app.app_context():
|
||||||
|
img = GeneralFeedbackImage.query.filter_by(feedback_id=fb_id).first()
|
||||||
|
image_id = img.id
|
||||||
|
|
||||||
|
resp = client.get(f"/api/admin/reports/general-feedbacks/{fb_id}/images/{image_id}/raw", headers=admin_headers)
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.data == b"\x89PNG\r\n\x1a\nfake"
|
||||||
|
assert resp.content_type.startswith("image/png")
|
||||||
|
# 安全响应头:Content-Type 按扩展名白名单固定后,仍禁用浏览器 MIME 嗅探(防伪造内容内联渲染)
|
||||||
|
assert resp.headers.get("X-Content-Type-Options") == "nosniff"
|
||||||
|
|
||||||
|
# 错配 feedback_id:image 不属于该反馈 → FEEDBACK.IMAGE_NOT_FOUND(而非 FILE_ASSET.*)
|
||||||
|
resp = client.get(
|
||||||
|
f"/api/admin/reports/general-feedbacks/{fb_id + 99999}/images/{image_id}/raw", headers=admin_headers,
|
||||||
|
)
|
||||||
|
assert resp.status_code == 404
|
||||||
|
assert parse_api_error(resp.get_json())["code"] == "FEEDBACK.IMAGE_NOT_FOUND"
|
||||||
|
|
||||||
|
# 非管理员访问 raw 接口 → 403
|
||||||
|
resp = client.get(f"/api/admin/reports/general-feedbacks/{fb_id}/images/{image_id}/raw", headers=user_headers)
|
||||||
|
assert resp.status_code == 403
|
||||||
@@ -1,45 +1,180 @@
|
|||||||
"""
|
"""
|
||||||
tests/services/admin/test_department_service.py
|
tests/services/admin/test_department_service.py
|
||||||
|
|
||||||
用途:department_service CRUD 单元测试。
|
用途:department_service 部门树 CRUD、树组装、成员口径单元测试。
|
||||||
|
覆盖:父子挂接 / 同级查重 / 编码唯一 / 防成环 / 删除保护(有下级、有员工)/ 成员数含下级汇总。
|
||||||
"""
|
"""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.core.errors import NotFoundError, ValidationError
|
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||||
from app.models import Department
|
from app.models import Department, User
|
||||||
from app.services.admin.department_service import (
|
from app.services.admin.department_service import (
|
||||||
create_department,
|
create_department,
|
||||||
delete_department,
|
delete_department,
|
||||||
|
list_department_members,
|
||||||
|
list_department_tree,
|
||||||
list_departments,
|
list_departments,
|
||||||
update_department,
|
update_department,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_department_crud(app):
|
def test_department_crud_with_parent(app):
|
||||||
|
"""断言:父子挂接进树、字段可更新、有下级禁删、无下级可删。"""
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
created = create_department({'name': 'R&D', 'code': 'RD', 'company': 'HX'})
|
parent = create_department({'name': '品保部', 'code': 'QA', 'company': 'HX'})
|
||||||
assert created['name'] == 'R&D'
|
child = create_department({'name': '品保课', 'code': 'QA1', 'parent_id': parent['id'], 'sort_order': 2})
|
||||||
|
assert child['name'] == '品保课'
|
||||||
|
|
||||||
items = list_departments()
|
items = list_departments()
|
||||||
assert any(item['code'] == 'RD' for item in items)
|
assert any(item['code'] == 'QA1' and item['parent_id'] == parent['id'] for item in items)
|
||||||
|
|
||||||
update_department(created['id'], {'description': 'Research'})
|
update_department(child['id'], {'sort_order': 9, 'is_hidden': True})
|
||||||
dept = db.session.get(Department, created['id'])
|
dept = db.session.get(Department, child['id'])
|
||||||
assert dept.description == 'Research'
|
assert dept.sort_order == 9
|
||||||
|
assert dept.is_hidden is True
|
||||||
|
|
||||||
delete_department(created['id'])
|
# 分支测试意图:存在下级部门时删除必须被 HAS_CHILDREN 拦截
|
||||||
assert db.session.get(Department, created['id']) is None
|
with pytest.raises(ConflictError, match='child'):
|
||||||
|
delete_department(parent['id'])
|
||||||
|
delete_department(child['id'])
|
||||||
|
delete_department(parent['id'])
|
||||||
|
assert db.session.get(Department, parent['id']) is None
|
||||||
|
|
||||||
|
|
||||||
def test_create_department_rejects_duplicate_name(app):
|
def test_create_department_rejects_same_parent_duplicate_name(app):
|
||||||
|
"""断言:同一上级下同名部门被拒(同级查重)。"""
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
create_department({'name': 'Sales'})
|
create_department({'name': 'Sales'})
|
||||||
with pytest.raises(ValidationError, match='Name exists'):
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
create_department({'name': 'Sales'})
|
create_department({'name': 'Sales'})
|
||||||
|
# 断言业务错误码而非消息文本(str(exc) 仅含 message,不含 code)
|
||||||
|
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_department_allows_same_name_under_different_parents(app):
|
||||||
|
"""断言:不同分支(多公司)允许同名部门——name 全局唯一已放开。"""
|
||||||
|
with app.app_context():
|
||||||
|
root_a = create_department({'name': '和信', 'company': '和信'})
|
||||||
|
root_b = create_department({'name': '泰国合欣', 'company': '泰国合欣'})
|
||||||
|
create_department({'name': '管理部', 'parent_id': root_a['id']})
|
||||||
|
create_department({'name': '管理部', 'parent_id': root_b['id']})
|
||||||
|
tree = list_department_tree()
|
||||||
|
assert len(tree) == 2
|
||||||
|
assert all(len([c for c in root['children'] if c['name'] == '管理部']) == 1 for root in tree)
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_department_allows_same_name_root_across_companies(app):
|
||||||
|
"""分支测试意图:两家公司的顶级部门允许同名(按 company 分桶查重),同公司顶级同名仍拒绝。"""
|
||||||
|
with app.app_context():
|
||||||
|
create_department({'name': '管理部', 'company': '苏州和信'})
|
||||||
|
create_department({'name': '管理部', 'company': '泰国合欣'})
|
||||||
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
|
create_department({'name': '管理部', 'company': '苏州和信'})
|
||||||
|
assert exc_info.value.code == 'DEPT.NAME_EXISTS'
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_department_inherits_company_from_parent(app):
|
||||||
|
"""断言:未填公司时继承上级部门 company(公司虚拟分组依赖)。"""
|
||||||
|
with app.app_context():
|
||||||
|
root = create_department({'name': '和信', 'company': '苏州和信'})
|
||||||
|
child = create_department({'name': '财务部', 'parent_id': root['id']})
|
||||||
|
dept = db.session.get(Department, child['id'])
|
||||||
|
assert dept.company == '苏州和信'
|
||||||
|
|
||||||
|
|
||||||
|
def test_create_department_rejects_duplicate_code(app):
|
||||||
|
"""断言:部门编码全局唯一。"""
|
||||||
|
with app.app_context():
|
||||||
|
create_department({'name': 'A', 'code': 'C1'})
|
||||||
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
|
create_department({'name': 'B', 'code': 'C1'})
|
||||||
|
assert exc_info.value.code == 'DEPT.CODE_EXISTS'
|
||||||
|
|
||||||
|
|
||||||
|
def test_update_parent_cycle_rejected(app):
|
||||||
|
"""分支测试意图:把部门挂到自己或自己的子孙下必须被 CYCLE_FORBIDDEN 拦截。"""
|
||||||
|
with app.app_context():
|
||||||
|
root = create_department({'name': 'Root'})
|
||||||
|
child = create_department({'name': 'Child', 'parent_id': root['id']})
|
||||||
|
grand = create_department({'name': 'Grand', 'parent_id': child['id']})
|
||||||
|
assert grand['name'] == 'Grand'
|
||||||
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
|
update_department(root['id'], {'parent_id': grand['id']})
|
||||||
|
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
|
||||||
|
with pytest.raises(ValidationError) as exc_info:
|
||||||
|
update_department(root['id'], {'parent_id': root['id']})
|
||||||
|
assert exc_info.value.code == 'DEPT.CYCLE_FORBIDDEN'
|
||||||
|
|
||||||
|
|
||||||
def test_update_department_not_found(app):
|
def test_update_department_not_found(app):
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
with pytest.raises(NotFoundError):
|
with pytest.raises(NotFoundError):
|
||||||
update_department(99999, {'name': 'X'})
|
update_department(99999, {'name': 'X'})
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_department_with_members_rejected(app):
|
||||||
|
"""断言:名下仍有员工(users.department 文本命中)时删除被 HAS_MEMBERS 拦截。"""
|
||||||
|
with app.app_context():
|
||||||
|
dept = create_department({'name': '品保部'})
|
||||||
|
db.session.add(User(username='u1', email='u1@example.com', department='品保部', role='user', status='active'))
|
||||||
|
db.session.commit()
|
||||||
|
with pytest.raises(ConflictError, match='members'):
|
||||||
|
delete_department(dept['id'])
|
||||||
|
|
||||||
|
|
||||||
|
def test_member_count_tree_rollup_and_members_scope(app):
|
||||||
|
"""断言:树节点 member_count 为直属人数、total_member_count 递归含下级;成员接口按口径过滤。"""
|
||||||
|
with app.app_context():
|
||||||
|
root = create_department({'name': '物料部'})
|
||||||
|
child = create_department({'name': '仓储课', 'parent_id': root['id']})
|
||||||
|
db.session.add_all([
|
||||||
|
User(username='r1', email='r1@example.com', department='物料部', role='user', status='active'),
|
||||||
|
User(username='c1', email='c1@example.com', department='仓储课', role='user', status='active'),
|
||||||
|
User(username='c2', email='c2@example.com', department='仓储课', role='user', status='active'),
|
||||||
|
])
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
tree = list_department_tree()
|
||||||
|
node = tree[0]
|
||||||
|
assert node['member_count'] == 1
|
||||||
|
assert node['total_member_count'] == 3
|
||||||
|
assert node['children'][0]['total_member_count'] == 2
|
||||||
|
|
||||||
|
direct = list_department_members(child['id'])
|
||||||
|
assert direct['total'] == 2
|
||||||
|
subtree = list_department_members(root['id'], include_descendants=True)
|
||||||
|
assert subtree['total'] == 3
|
||||||
|
assert all(member.get('department') in ('物料部', '仓储课') for member in subtree['members'])
|
||||||
|
|
||||||
|
|
||||||
|
def test_members_keyword_search_and_pagination(app):
|
||||||
|
"""分支测试意图:成员接口按 姓名/工号/手机 模糊搜索,并按 page/page_size 分页。"""
|
||||||
|
with app.app_context():
|
||||||
|
dept = create_department({'name': '品保部'})
|
||||||
|
db.session.add_all([
|
||||||
|
User(username='u1', real_name='张一', employee_id='E001', phone_number='13800000001',
|
||||||
|
email='u1@example.com', department='品保部', role='user', status='active'),
|
||||||
|
User(username='u2', real_name='张二', employee_id='E002', phone_number='13800000002',
|
||||||
|
email='u2@example.com', department='品保部', role='user', status='active'),
|
||||||
|
User(username='u3', real_name='李三', employee_id='E003', phone_number='13800000003',
|
||||||
|
email='u3@example.com', department='品保部', role='user', status='active'),
|
||||||
|
])
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
# 关键词命中工号
|
||||||
|
by_emp = list_department_members(dept['id'], keyword='E003')
|
||||||
|
assert by_emp['total'] == 1
|
||||||
|
assert by_emp['members'][0]['real_name'] == '李三'
|
||||||
|
# 关键词命中手机号
|
||||||
|
by_phone = list_department_members(dept['id'], keyword='13800000002')
|
||||||
|
assert by_phone['total'] == 1
|
||||||
|
assert by_phone['members'][0]['username'] == 'u2'
|
||||||
|
# 关键词命中姓名(同姓两人)
|
||||||
|
by_name = list_department_members(dept['id'], keyword='张')
|
||||||
|
assert by_name['total'] == 2
|
||||||
|
# 分页:page_size=2 时第 2 页只剩 1 条
|
||||||
|
paged = list_department_members(dept['id'], page=2, page_size=2)
|
||||||
|
assert paged['total'] == 3
|
||||||
|
assert paged['page'] == 2
|
||||||
|
assert len(paged['members']) == 1
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
"""
|
||||||
|
backend/tests/services/test_feedback_notify.py
|
||||||
|
|
||||||
|
用途:锁定企微反馈通知 markdown 组装契约——有图反馈在「反馈内容」段之前
|
||||||
|
多一行「附图:N 张」(N>0 时),无图反馈不得出现「附图」字样,
|
||||||
|
且其余既有行内容与顺序零改动。
|
||||||
|
依赖:app 夹具(create_app('testing') + db.create_all,不走迁移)、
|
||||||
|
GeneralFeedback/GeneralFeedbackImage/User/FileAsset 模型、
|
||||||
|
app.services.feedback_notify.build_feedback_markdown。
|
||||||
|
逻辑:build_feedback_markdown 为纯组装函数(不发网络请求),测试直接落
|
||||||
|
User/FileAsset/GeneralFeedback/GeneralFeedbackImage 行后调用并断言文本,
|
||||||
|
覆盖有图(2 张)与无图两条路径。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from app import db
|
||||||
|
from app.models import FileAsset, GeneralFeedback, GeneralFeedbackImage, User
|
||||||
|
from app.services.feedback_notify import build_feedback_markdown
|
||||||
|
|
||||||
|
|
||||||
|
def _create_user(username: str) -> User:
|
||||||
|
"""按用户名幂等落一个测试用户(GeneralFeedback.user_id 外键依赖)。"""
|
||||||
|
user = db.session.query(User).filter_by(username=username).first()
|
||||||
|
if not user:
|
||||||
|
user = User(username=username, email=f"{username}@example.com", role="user", status="active")
|
||||||
|
user.set_password("x")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def _make_asset(user_id: int) -> FileAsset:
|
||||||
|
"""直接落一条 ready/temporary 的图片 FileAsset 行(GeneralFeedbackImage.asset_id 外键依赖)。"""
|
||||||
|
asset = FileAsset(
|
||||||
|
asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id),
|
||||||
|
original_filename="screenshot.png", storage_provider="minio", storage_bucket="test",
|
||||||
|
storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024,
|
||||||
|
mime_type="image/png", extension="png", upload_status="ready",
|
||||||
|
lifecycle_status="temporary", reference_count=0,
|
||||||
|
)
|
||||||
|
db.session.add(asset)
|
||||||
|
db.session.commit()
|
||||||
|
return asset
|
||||||
|
|
||||||
|
|
||||||
|
def _create_feedback(user: User, content: str) -> GeneralFeedback:
|
||||||
|
"""落一条最小可用的 GeneralFeedback 行(必填字段齐全)。"""
|
||||||
|
feedback = GeneralFeedback(
|
||||||
|
user_id=user.id, username=user.username,
|
||||||
|
feedback_type="问题反馈", feedback_module="知识库", content=content,
|
||||||
|
source_page="workspace",
|
||||||
|
)
|
||||||
|
db.session.add(feedback)
|
||||||
|
db.session.commit()
|
||||||
|
return feedback
|
||||||
|
|
||||||
|
|
||||||
|
def test_markdown_includes_image_count(app):
|
||||||
|
"""有图反馈:markdown 含「附图:2 张」行;无图反馈:不含「附图」。"""
|
||||||
|
with app.app_context():
|
||||||
|
user = _create_user("notifyuser")
|
||||||
|
# 有图反馈:2 条图片关联(asset_id 唯一,各自独立 FileAsset),走真实 images relationship
|
||||||
|
fb_with_images = _create_feedback(user, "这条反馈带两张截图")
|
||||||
|
db.session.add_all([
|
||||||
|
GeneralFeedbackImage(feedback_id=fb_with_images.id, asset_id=_make_asset(user.id).id, sort_order=0),
|
||||||
|
GeneralFeedbackImage(feedback_id=fb_with_images.id, asset_id=_make_asset(user.id).id, sort_order=1),
|
||||||
|
])
|
||||||
|
db.session.commit()
|
||||||
|
# 无图反馈:不落任何 GeneralFeedbackImage
|
||||||
|
fb_without_images = _create_feedback(user, "这条反馈没有截图")
|
||||||
|
|
||||||
|
md_with_images = build_feedback_markdown(fb_with_images, None)
|
||||||
|
md_without_images = build_feedback_markdown(fb_without_images, None)
|
||||||
|
|
||||||
|
# 有图:附图行存在,且必须位于「反馈内容」块之前
|
||||||
|
assert "附图:2 张" in md_with_images
|
||||||
|
assert md_with_images.index("附图:2 张") < md_with_images.index("**反馈内容:**")
|
||||||
|
# 无图:不得出现「附图」字样
|
||||||
|
assert "附图" not in md_without_images
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
tests/test_permission_roles.py
|
tests/test_permission_roles.py
|
||||||
|
|
||||||
用途:可配置权限组种子路径:角色包同步、成员确认、禁止按人授权、最后一名管理员、平台管理员查询。
|
用途:可配置权限组种子路径:角色包同步、多角色并集、成员确认、禁止按人授权、最后一名管理员、平台管理员查询。
|
||||||
依赖:PermissionRole、User、Agent、permission_roles.service、user_service、permission_service。
|
依赖:PermissionRole、User、Agent、permission_roles.service、user_service、permission_service。
|
||||||
逻辑:未种子时旧测试仍走按人授权;本文件显式写入权限组后断言新路径。
|
逻辑:未种子时旧测试仍走按人授权;本文件显式写入权限组后断言新路径。
|
||||||
"""
|
"""
|
||||||
@@ -202,8 +202,10 @@ def test_preview_and_apply_role_members(app):
|
|||||||
assert {agent.id for agent in staff.agents} == {entrance.id, training.id}
|
assert {agent.id for agent in staff.agents} == {entrance.id, training.id}
|
||||||
assert admin.role == 'admin'
|
assert admin.role == 'admin'
|
||||||
|
|
||||||
steal_preview = role_service.preview_role_members('user', [other.id, staff.id])
|
retain_preview = role_service.preview_role_members('user', [other.id, staff.id])
|
||||||
assert [row['id'] for row in steal_preview['stolen']] == [staff.id]
|
# 断言:再挂上默认角色时保留培训 HR,不再把原角色抢走。
|
||||||
|
assert [row['id'] for row in retain_preview['stolen']] == [staff.id]
|
||||||
|
assert retain_preview['stolen'][0]['retained_role_names'] == ['培训 HR']
|
||||||
|
|
||||||
|
|
||||||
def test_default_role_ignores_removal(app):
|
def test_default_role_ignores_removal(app):
|
||||||
@@ -222,6 +224,57 @@ def test_default_role_ignores_removal(app):
|
|||||||
assert staff.role == 'user'
|
assert staff.role == 'user'
|
||||||
|
|
||||||
|
|
||||||
|
def test_business_roles_union_until_last_role_removed(app):
|
||||||
|
"""一个人可同时挂两个业务角色;拿掉最后一个才回到普通用户。"""
|
||||||
|
with app.app_context():
|
||||||
|
entrance = _agent('ent-union', profile='generic_entrance')
|
||||||
|
training = _agent('train-union', profile='training')
|
||||||
|
patent = _agent('patent-union', code='patent_tool')
|
||||||
|
db.session.add_all([entrance, training, patent])
|
||||||
|
db.session.flush()
|
||||||
|
roles = _seed_standard_roles(entrance, training)
|
||||||
|
rd = PermissionRole(
|
||||||
|
code='rd',
|
||||||
|
name='研发',
|
||||||
|
is_default=False,
|
||||||
|
is_system=False,
|
||||||
|
is_platform_admin=False,
|
||||||
|
sort_order=20,
|
||||||
|
feature_permissions={'shipping_notice_force_create': True},
|
||||||
|
)
|
||||||
|
rd.agents = [entrance, patent]
|
||||||
|
db.session.add(rd)
|
||||||
|
staff = _user('union-staff', role='user')
|
||||||
|
db.session.add(staff)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
role_service.apply_role_members('hr', [staff.id])
|
||||||
|
role_service.apply_role_members('rd', [staff.id])
|
||||||
|
db.session.refresh(staff)
|
||||||
|
codes = {role.code for role in role_service.list_assigned_roles(staff)}
|
||||||
|
# 断言:两个业务角色并存,应用和能力取并集,普通用户不再占用名额。
|
||||||
|
assert codes == {'hr', 'rd'}
|
||||||
|
assert {agent.id for agent in staff.agents} == {entrance.id, training.id, patent.id}
|
||||||
|
perms = staff.get_feature_permissions()
|
||||||
|
assert perms['training_hr_manage'] is True
|
||||||
|
assert perms['shipping_notice_force_create'] is True
|
||||||
|
assert roles['user'].id not in {role.id for role in role_service.list_assigned_roles(staff)}
|
||||||
|
|
||||||
|
role_service.apply_role_members('hr', [])
|
||||||
|
db.session.refresh(staff)
|
||||||
|
# 断言:移出培训后仍保留研发。
|
||||||
|
assert {role.code for role in role_service.list_assigned_roles(staff)} == {'rd'}
|
||||||
|
assert staff.get_feature_permissions()['training_hr_manage'] is False
|
||||||
|
assert staff.get_feature_permissions()['shipping_notice_force_create'] is True
|
||||||
|
|
||||||
|
role_service.apply_role_members('rd', [])
|
||||||
|
db.session.refresh(staff)
|
||||||
|
# 断言:最后一个业务角色拿掉后回到默认普通用户。
|
||||||
|
assert {role.code for role in role_service.list_assigned_roles(staff)} == {'user'}
|
||||||
|
assert staff.role == 'user'
|
||||||
|
assert [agent.id for agent in staff.agents] == [entrance.id]
|
||||||
|
|
||||||
|
|
||||||
def test_picker_excludes_platform_admin(app):
|
def test_picker_excludes_platform_admin(app):
|
||||||
with app.app_context():
|
with app.app_context():
|
||||||
entrance = _agent('ent-pick', profile='generic_entrance')
|
entrance = _agent('ent-pick', profile='generic_entrance')
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_notify_config.py
|
|||||||
|
|
||||||
用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。
|
用途:按文件类型配置缺件接收人,以及把缺件类型拆成每人一封。
|
||||||
依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。
|
依赖:pytest、Flask client、notify_config_service、notification.send_batch_missing_summary。
|
||||||
逻辑:GET/PUT 仅 is_platform_admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型。
|
逻辑:GET/PUT 仅 is_platform_admin;未知规则码丢弃;发送时每人只看到自己负责且本批缺失的类型,并收到同一份 Excel。
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -179,14 +179,26 @@ def test_notify_config_rejects_non_admin_headers(app, client, user_headers):
|
|||||||
|
|
||||||
|
|
||||||
def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
||||||
"""缺件通知按人拆信,正文只含该人负责的缺失类型。"""
|
"""缺件通知按人拆信,正文只含该人负责的缺失类型,并给每人附上同一份 Excel。"""
|
||||||
sent: list[tuple[str, str, str]] = []
|
sent: list[tuple[str, str, str]] = []
|
||||||
|
uploaded: list[tuple[bytes, str]] = []
|
||||||
|
files: list[tuple[str, str]] = []
|
||||||
|
|
||||||
def _fake_send(wecom_userid, title, description, jump_url):
|
def _fake_send(wecom_userid, title, description, jump_url):
|
||||||
sent.append((wecom_userid, title, description))
|
sent.append((wecom_userid, title, description))
|
||||||
return {"errcode": 0}
|
return {"errcode": 0}
|
||||||
|
|
||||||
|
def _fake_upload(data, filename):
|
||||||
|
uploaded.append((data, filename))
|
||||||
|
return "media-vc-1"
|
||||||
|
|
||||||
|
def _fake_file(wecom_userid, media_id):
|
||||||
|
files.append((wecom_userid, media_id))
|
||||||
|
return {"errcode": 0}
|
||||||
|
|
||||||
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_textcard_message", _fake_send)
|
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_textcard_message", _fake_send)
|
||||||
|
monkeypatch.setattr("app.services.integrations.wecom.notify.upload_wecom_temp_media", _fake_upload)
|
||||||
|
monkeypatch.setattr("app.services.integrations.wecom.notify.send_wecom_file_message", _fake_file)
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
"app.services.integrations.wecom.notify._create_audit",
|
"app.services.integrations.wecom.notify._create_audit",
|
||||||
lambda *args, **kwargs: SimpleNamespace(
|
lambda *args, **kwargs: SimpleNamespace(
|
||||||
@@ -279,6 +291,7 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
excel_filename="voucher_check_sales_2026-08.xlsx",
|
excel_filename="voucher_check_sales_2026-08.xlsx",
|
||||||
|
excel_bytes=b"voucher-xlsx",
|
||||||
enabled=True,
|
enabled=True,
|
||||||
)
|
)
|
||||||
assert status == "sent"
|
assert status == "sent"
|
||||||
@@ -306,3 +319,7 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
|||||||
assert "发票:缺" not in po_body
|
assert "发票:缺" not in po_body
|
||||||
assert "提单" in bl_body
|
assert "提单" in bl_body
|
||||||
assert "PO订单:缺" not in bl_body
|
assert "PO订单:缺" not in bl_body
|
||||||
|
# 关键断言:同一份 Excel 只上传一次,两个收件人都收到文件消息。
|
||||||
|
assert uploaded == [(b"voucher-xlsx", "voucher_check_sales_2026-08.xlsx")]
|
||||||
|
assert files == [("wx-po-recv", "media-vc-1"), ("wx-bl-recv", "media-vc-1")]
|
||||||
|
assert "下一条 Excel" in po_body
|
||||||
+4
-4
@@ -19,8 +19,8 @@
|
|||||||
|
|
||||||
## 可配置权限组(2026-09)
|
## 可配置权限组(2026-09)
|
||||||
|
|
||||||
- 每位用户只选一个权限组(角色包);角色 = 可用应用入口 + 应用内能力。部门只用于选人筛选,不自动授权。
|
- 每位用户可同时挂多个业务角色(权限组);生效权限是这些角色的应用与能力并集。平台管理员不与其他角色叠加。拿掉最后一个业务角色后回到默认「普通用户」。部门只用于选人筛选,不自动授权。
|
||||||
- 新建用户由管理员选角色,默认「普通用户」。新增应用时先勾到需要的角色,再按人数弹窗选人;全选只勾草稿,确定后必须确认增减(含来源角色)。
|
- 新建用户由管理员选角色,可多选,默认「普通用户」。新增应用时先勾到需要的角色,再按人数弹窗选人;全选只勾草稿,确定后必须确认追加或移出。
|
||||||
- 管理员为锁定角色(`code=admin`):应用入口隐式全开,选人弹窗不能添加或移出;用户管理改到/改出管理员须额外确认,且不能撤掉最后一名启用中的管理员。
|
- 管理员为锁定角色(`code=admin`):应用入口隐式全开,选人弹窗不能添加或移出;用户管理改到/改出管理员须额外确认,且不能撤掉最后一名启用中的管理员。
|
||||||
- 平台管理员从 AI 工作台进入管理控制台:侧栏底部「返回聊天」上方展示入口,普通用户不显示;对话页齿轮入口保持不变。
|
- 平台管理员从 AI 工作台进入管理控制台:侧栏底部「返回聊天」上方展示入口,普通用户不显示;对话页齿轮入口保持不变。
|
||||||
- 迁移按现网 `users.role` 枚举套标准包(普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员);不再种子设备维保专员,原 `maintenance_manager` 收口到普通用户。个人额外 Agent 勾选丢弃。原型见 [platform/role-permission-prototype.md](platform/role-permission-prototype.md)。
|
- 迁移按现网 `users.role` 枚举套标准包(普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员);不再种子设备维保专员,原 `maintenance_manager` 收口到普通用户。个人额外 Agent 勾选丢弃。原型见 [platform/role-permission-prototype.md](platform/role-permission-prototype.md)。
|
||||||
@@ -33,8 +33,8 @@
|
|||||||
## 设备验收预警(2026-09)
|
## 设备验收预警(2026-09)
|
||||||
|
|
||||||
- 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。
|
- 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。
|
||||||
- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人;E8 与 E10 相同,不取当前节点未办人。采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人发送汇总卡片和 Excel 明细。
|
- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人;E8 与 E10 相同,不取当前节点未办人。采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:30 按收件人发送汇总卡片和 Excel 明细(错开合同付款 18:00)。
|
||||||
- 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。
|
- 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:30 扫描、每周五 18:30 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
||||||
- E8 补抓已接上(2026-10-26)。与 E10 分来源保存。暂停按撤销停表。没有作废、强制结束。见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md)、[technical.md](features/equipment-acceptance-warning/technical.md)。
|
- E8 补抓已接上(2026-10-26)。与 E10 分来源保存。暂停按撤销停表。没有作废、强制结束。见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md)、[technical.md](features/equipment-acceptance-warning/technical.md)。
|
||||||
|
|
||||||
## 合同付款预警 Agent(2026-08)
|
## 合同付款预警 Agent(2026-08)
|
||||||
|
|||||||
@@ -244,7 +244,7 @@ flowchart TD
|
|||||||
| -------- | ------------------------------------------------------------------------------------------------------- |
|
| -------- | ------------------------------------------------------------------------------------------------------- |
|
||||||
| 触发 | 本批存在必检文件缺件 |
|
| 触发 | 本批存在必检文件缺件 |
|
||||||
| 聚合 | 审计仍是一个检核批次一条;企微按接收人拆信,不在正文逐票展开缺失明细 |
|
| 聚合 | 审计仍是一个检核批次一条;企微按接收人拆信,不在正文逐票展开缺失明细 |
|
||||||
| 内容 | 标题为「销售开票附件缺件提醒」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示到详情 Excel 补齐。不写业务方代号和批次号 |
|
| 内容 | 标题为「销售开票附件缺件提醒」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示下一条消息是本批 Excel。不写业务方代号和批次号。卡片发出后另发本批检核结果 Excel 文件 |
|
||||||
| 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 |
|
| 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 |
|
||||||
| 接收人 | 平台管理员在 Chat「通知配置」按文件类型从系统用户多选。未配置任何接收人时不发送空通知,并在发送记录标记未发送原因 |
|
| 接收人 | 平台管理员在 Chat「通知配置」按文件类型从系统用户多选。未配置任何接收人时不发送空通知,并在发送记录标记未发送原因 |
|
||||||
| 技术失败 | 不作为缺件通知;按排程通知人单独告警 |
|
| 技术失败 | 不作为缺件通知;按排程通知人单独告警 |
|
||||||
@@ -268,7 +268,7 @@ flowchart TD
|
|||||||
1. 每周二任务仅处理上一个自然月,支持跨年期间计算和增量跳过。
|
1. 每周二任务仅处理上一个自然月,支持跨年期间计算和增量跳过。
|
||||||
2. 同一 `invoice` 缺少多个文件时,Excel 的“缺件文件总数”正确累计,“缺件 invoice 数”只计一次。
|
2. 同一 `invoice` 缺少多个文件时,Excel 的“缺件文件总数”正确累计,“缺件 invoice 数”只计一次。
|
||||||
3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。
|
3. Excel 报告顶部可按资料所属期间选择年月,并单独展示执行时间;每个 `invoice` 一行,直接展示各必检文件为“有 / 缺件 / 未检核”和总体状态;全部必检文件均为“有”时状态为“完整”。
|
||||||
4. 企业微信按文件类型接收人拆成每人一封,正文只含该人负责的缺件类型,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。审计仍是每批一条。
|
4. 企业微信按文件类型接收人拆成每人一封,正文只含该人负责的缺件类型;卡片之后发送本批 Excel 文件。完整 `invoice` 明细不在消息正文展开。审计仍是每批一条。
|
||||||
5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。
|
5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。
|
||||||
6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 销货放行单取数已接线(E10 `ft_xqqgsq` + OpenAPI,独立排程周二 05:30),凭据只进环境变量。
|
6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 销货放行单取数已接线(E10 `ft_xqqgsq` + OpenAPI,独立排程周二 05:30),凭据只进环境变量。
|
||||||
7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。文档库自动加上的「(重命名)」改回原名,同一目录多出来的该后缀副本删除。
|
7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。文档库自动加上的「(重命名)」改回原名,同一目录多出来的该后缀副本删除。
|
||||||
|
|||||||
@@ -318,7 +318,7 @@ ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成
|
|||||||
|
|
||||||
### 6.2 通知聚合
|
### 6.2 通知聚合
|
||||||
|
|
||||||
缺件通知按文件类型接收人拆信:同一人管多类时合并为一封,正文只含该人负责且本批缺失的类型。审计仍以 `run_id` 聚合为一条 `voucher_check_notifications`。接收人由 Chat「通知配置」(仅平台管理员)维护,存在 `voucher_check_notify_configs`,不写进 Profile。未配置则不发送并记录原因。排程「启用通知」与 `notify_missing_enabled` 为总开关;排程选人只用于技术失败告警,不混入缺件通知。
|
缺件通知按文件类型接收人拆信:同一人管多类时合并为一封,正文只含该人负责且本批缺失的类型,卡片之后再发本批检核结果 Excel。审计仍以 `run_id` 聚合为一条 `voucher_check_notifications`。接收人由 Chat「通知配置」(仅平台管理员)维护,存在 `voucher_check_notify_configs`,不写进 Profile。未配置则不发送并记录原因。排程「启用通知」与 `notify_missing_enabled` 为总开关;排程选人只用于技术失败告警,不混入缺件通知。
|
||||||
|
|
||||||
### 6.3 检核任务列表
|
### 6.3 检核任务列表
|
||||||
|
|
||||||
|
|||||||
@@ -38,5 +38,5 @@
|
|||||||
|
|
||||||
## 3. 怎么发
|
## 3. 怎么发
|
||||||
|
|
||||||
- 每天扫描,生成待发送。默认每周五 18:00 按收件人发一条企业微信汇总,并附一份只含该人的 Excel。时刻可改。
|
- 每天 06:30 扫描,生成待发送(错开合同付款 06:00)。默认每周五 18:30 按收件人发一条企业微信汇总,并附一份只含该人的 Excel(错开合同付款周五 18:00)。时刻可改。
|
||||||
- 已发送的不撤回、不重发。
|
- 已发送的不撤回、不重发。
|
||||||
+15
-4
@@ -21,7 +21,7 @@
|
|||||||
| 功能项 | 状态 | 说明 |
|
| 功能项 | 状态 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 权限组表与种子 | 已实现 | `permission_roles` / `permission_role_agents`;标准包为普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员。不再种子设备维保专员。未种子时测试夹具仍走按人授权。 |
|
| 权限组表与种子 | 已实现 | `permission_roles` / `permission_role_agents`;标准包为普通用户 / 培训 HR / 研发应用 / 货代专员 / 管理员。不再种子设备维保专员。未种子时测试夹具仍走按人授权。 |
|
||||||
| 角色包即授权 | 已实现 | 用户只选一个角色;保存角色立即同步该组成员应用入口;功能权限改由角色包计算。`is_platform_admin` 权限组隐式全开应用入口。 |
|
| 角色包即授权 | 已实现 | 用户可同时挂多个业务角色,生效权限取并集;拿掉最后一个业务角色回到默认组。平台管理员不与其他角色叠加。保存角色立即重算该组成员应用入口。`is_platform_admin` 权限组隐式全开应用入口。 |
|
||||||
| 管理端角色配置 | 已实现 | `/admin/permissions` 以角色列表为主:编辑时应用卡片内嵌功能权限短标签;点人数打开公共选人弹窗,确定后确认增减才写库。矩阵只读核对。 |
|
| 管理端角色配置 | 已实现 | `/admin/permissions` 以角色列表为主:编辑时应用卡片内嵌功能权限短标签;点人数打开公共选人弹窗,确定后确认增减才写库。矩阵只读核对。 |
|
||||||
| 用户只选角色 | 已实现 | 新建用户默认普通用户;改角色须确认;按人勾应用、应用页按人授权、权限申请通过加应用,在角色包启用后一律拒绝(`ROLE.DIRECT_GRANT_DISABLED`)。 |
|
| 用户只选角色 | 已实现 | 新建用户默认普通用户;改角色须确认;按人勾应用、应用页按人授权、权限申请通过加应用,在角色包启用后一律拒绝(`ROLE.DIRECT_GRANT_DISABLED`)。 |
|
||||||
| 工作台进入管理控制台 | 已实现 | AI 工作台侧栏底部「返回聊天」上方,仅平台管理员(`is_platform_admin`)显示「管理控制台」并跳转 `/admin`;普通用户不渲染入口。 |
|
| 工作台进入管理控制台 | 已实现 | AI 工作台侧栏底部「返回聊天」上方,仅平台管理员(`is_platform_admin`)显示「管理控制台」并跳转 `/admin`;普通用户不渲染入口。 |
|
||||||
@@ -56,9 +56,9 @@
|
|||||||
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。未归档且已开始计时的单据,可以验收为是或未标明都监控,明确为否才不监控。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 |
|
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。未归档且已开始计时的单据,可以验收为是或未标明都监控,明确为否才不监控。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 |
|
||||||
| 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 与 E8 未归档验收单、流程状态、当前节点和操作人。不抓归档(E10 `flowstatus = 3`,E8 `currentnodetype = 3`)。按 `sfkyzcys`、`sfzfth`、`flowstatus` 4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。本次结果里没有的本地单删除,并取消未发送预警。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 |
|
| 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 与 E8 未归档验收单、流程状态、当前节点和操作人。不抓归档(E10 `flowstatus = 3`,E8 `currentnodetype = 3`)。按 `sfkyzcys`、`sfzfth`、`flowstatus` 4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。本次结果里没有的本地单删除,并取消未发送预警。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 |
|
||||||
| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。只列出未归档单据,并展示流程编号、标题和创建时间。有权限的用户看列表和详情,同步按钮只给平台管理员。 |
|
| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。只列出未归档单据,并展示流程编号、标题和创建时间。有权限的用户看列表和详情,同步按钮只给平台管理员。 |
|
||||||
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:00。 |
|
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:30(错开合同付款 18:00)。 |
|
||||||
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 |
|
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员「扫描预警 / 发送预警」入队由 schedule worker 执行(避免 HTTP 504),页面轮询 Job 后再刷新结果。 |
|
||||||
| 四档企业微信升级 | 已按使用部门担当 | 超过 30/37/44/51 天各发一次。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人。E8 与 E10 相同。采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人发送一条汇总卡片和一份 Excel 明细。停表取消未发送。已发送不撤回、不重发。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
| 四档企业微信升级 | 已按使用部门担当 | 超过 30/37/44/51 天各发一次。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人。E8 与 E10 相同。采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:30 同步并生成待发送,每周五 18:30 按收件人发送一条汇总卡片和一份 Excel 明细(错开合同付款 06:00 / 18:00)。停表取消未发送。已发送不撤回、不重发。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
||||||
| E8 补抓 | 已接上查询 | 读取 `ecology` 上的验收单,与 E10 分来源保存。计时起点 `syddjssj`。暂停 `currentstatus = 0` 按撤销停表。没有作废、强制结束。见 [technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
| E8 补抓 | 已接上查询 | 读取 `ecology` 上的验收单,与 E10 分来源保存。计时起点 `syddjssj`。暂停 `currentstatus = 0` 按撤销停表。没有作废、强制结束。见 [technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
||||||
|
|
||||||
## 知识库同步状态校验
|
## 知识库同步状态校验
|
||||||
@@ -103,6 +103,16 @@
|
|||||||
| ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- |
|
| ------------------ | ------ | ------------------------------------------------------------------------------------------------------------- |
|
||||||
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
|
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
|
||||||
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
|
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
|
||||||
|
| 反馈截图附件 | 已实现 | 意见反馈支持粘贴/上传截图附件(每条最多 5 张),管理端报表可查看附图缩略图与大图预览 |
|
||||||
|
|
||||||
|
## 知识库内容清单按钮(2026-10)
|
||||||
|
|
||||||
|
| 功能项 | 状态 | 说明 |
|
||||||
|
| ---------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| 兜底回复触发识别 | 已实现 | Dify 知识库未命中兜底回复末尾追加 `[知识库能力清单]` 标记(兼容「内容清单」写法)时,前端识别并在语句结尾渲染【知识库内容清单】按钮;对无标记的已发布兜底原句按特征片段兜底识别,历史会话同样生效 |
|
||||||
|
| 标记展示剥离 | 已实现 | 渲染前从正文剥离标记及其前导标点(含流式半截标记裁剪),用户不会看到原始标记符号 |
|
||||||
|
| 能力清单标准答案查询 | 已实现 | `GET /api/chat/capability-list?agent_id=`(`require_agent_permission` 鉴权)返回常用问题中该应用「能力清单条目」(标题含「能力清单」的全局条目)的标准答案;未配置返回 `CHAT.CAPABILITY_LIST_NOT_FOUND` |
|
||||||
|
| 内容清单弹窗 | 已实现 | 点击按钮后按当前会话应用拉取标准答案并弹窗展示(Markdown 渲染);未配置时按错误码本地化提示,文案同步 zh-CN/zh-TW/en/th |
|
||||||
|
|
||||||
## 年度教育训练计划
|
## 年度教育训练计划
|
||||||
|
|
||||||
@@ -682,6 +692,7 @@
|
|||||||
| 管理端运营总览 | 「数据报表」新增「运营总览」入口:展示对话量/活跃用户/活跃应用/好评率、对话趋势与环比、Top 应用与低使用应用、低评分回答与未处理反馈,复用 chat_logs/feedbacks/general_feedbacks/agents/应用授权数据 | 已实现(数据处理) | P1 |
|
| 管理端运营总览 | 「数据报表」新增「运营总览」入口:展示对话量/活跃用户/活跃应用/好评率、对话趋势与环比、Top 应用与低使用应用、低评分回答与未处理反馈,复用 chat_logs/feedbacks/general_feedbacks/agents/应用授权数据 | 已实现(数据处理) | P1 |
|
||||||
| 管理端问题分析 | 「数据报表」新增「问题分析」入口,第一版为页面骨架与空状态,不伪造数据 | 已实现(骨架) | P2 |
|
| 管理端问题分析 | 「数据报表」新增「问题分析」入口,第一版为页面骨架与空状态,不伪造数据 | 已实现(骨架) | P2 |
|
||||||
| 管理端时间范围统一 | 「数据报表」各数据页时间范围筛选器统一为「近 7 天 / 30 天 / 90 天」,并同步四语言文案 | 已实现 | P1 |
|
| 管理端时间范围统一 | 「数据报表」各数据页时间范围筛选器统一为「近 7 天 / 30 天 / 90 天」,并同步四语言文案 | 已实现 | P1 |
|
||||||
|
| 管理端部门管理(组织树) | 部门管理改为树形组织结构(对应 OA 组织架构,层级来源对齐 ERP HRAO:hrao01 编码 / hrao02 名称 / hrao06 上级 / hrao09 同级排序 / hrao08 隐藏标记):`departments` 表增加 `parent_id`(邻接表)/ `sort_order` / `is_hidden`(迁移 `dp1a2b3c4d5e6`),`name` 全局唯一放开为「同一上级下唯一」;页面为左树右成员面板(OA 组织结构口径,控件已按 Element Plus 迁移规范 Element 化:ElTable/ElPagination/ElTag/ElDialog/ElMessageBox,树行为自定义层级结构),树顶公司层为前端按 `company` 字段虚拟分组不入库;节点支持添加子部门/编辑/删除(有下级或有员工禁删)、搜索命中自动展开、全部展开/收起;员工展示改为 OA 组织结构口径(左树右成员面板):树表员工计数列剔除,点击部门节点右侧分页展示成员名单(关键词搜索姓名/工号/邮箱/手机、每页 20/50/100 可调,「含下级部门」口径可切换,成员接口 `members` 支持 keyword/page/page_size);新增错误码 `DEPT.*` 四语言。ERP 一次性导入脚本已提供(`backend/scripts/import_departments_from_hrao.py`:DBeaver 导出 HRAO_FILE CSV + 公司映射取自 HRAA_FILE,dry-run 默认、`--apply` 按编码 upsert 合并、悬空/成环/重名告警兜底),已于 2026-10-08 执行首次全量导入(366 部门 / 7 公司,本地 56 行全部按编码命中更新);持续同步仍未做 | 已实现 | P1 |
|
||||||
| 管理端常用问题模糊匹配 | 「常用问题」编辑弹窗新增「启用模糊匹配」开关与阈值(0.50–1.00,默认 0.80,逐条目独立、以启用 FAQ 缓存为前提):精确未命中时按相似度兜底直答,容忍加前后缀与近义词差异;得分取 max(编辑距离相似度, 包含覆盖率),命中方式与得分写入 ChatLog payload(match_type / match_score / matched_text) | 已实现 | P2 |
|
| 管理端常用问题模糊匹配 | 「常用问题」编辑弹窗新增「启用模糊匹配」开关与阈值(0.50–1.00,默认 0.80,逐条目独立、以启用 FAQ 缓存为前提):精确未命中时按相似度兜底直答,容忍加前后缀与近义词差异;得分取 max(编辑距离相似度, 包含覆盖率),命中方式与得分写入 ChatLog payload(match_type / match_score / matched_text) | 已实现 | P2 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
## 怎么判权
|
## 怎么判权
|
||||||
|
|
||||||
一个人只绑一个角色。角色包决定能进哪些应用,以及进了应用之后能做哪些事。平台管理员是特例:应用入口默认全开,也能进管理后台。部门不授权。
|
一个人可以同时挂多个业务角色。生效权限是这些角色的并集:能进的应用合在一起,任一角色打开的应用内能力都生效。平台管理员不与其他角色叠加,应用入口默认全开,也能进管理后台。拿掉最后一个业务角色后回到默认角色。部门不授权。`users.role` 只保存排序最前的主角色,成员关系在 `user_permission_roles`。
|
||||||
|
|
||||||
登录后后端下发三样东西,前端路由守卫和后端接口用同一份结果:
|
登录后后端下发三样东西,前端路由守卫和后端接口用同一份结果:
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
|
|
||||||
| 层 | 存在哪 | 运行时怎么用 |
|
| 层 | 存在哪 | 运行时怎么用 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| 角色包 | `users.role` 指向 `permission_roles.code` | 每人一个。改角色,或改该角色的勾选,会立刻重写这个人的应用授权 |
|
| 角色包 | `user_permission_roles` 挂到 `permission_roles`;`users.role` 是主角色 | 每人可多个业务角色。改其中一个角色的勾选,会按该人全部角色的并集重算应用授权 |
|
||||||
| 应用入口 | `permission_role_agents`,同步到 `user_agent_permissions` | 聊天和工作台按「有没有这个 Agent」放行。平台管理员不写授权行,入口隐式全开 |
|
| 应用入口 | `permission_role_agents`,同步到 `user_agent_permissions` | 聊天和工作台按「有没有这个 Agent」放行。平台管理员不写授权行,入口隐式全开 |
|
||||||
| 应用内能力 | 角色包上的 `feature_permissions` | 已经进了应用之后,再卡统计、强制新建、台账维护这类动作 |
|
| 应用内能力 | 角色包上的 `feature_permissions` | 已经进了应用之后,再卡统计、强制新建、台账维护这类动作 |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,597 @@
|
|||||||
|
# 意见反馈截图附件 Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||||
|
|
||||||
|
**Goal:** 意见反馈弹窗支持粘贴/选图上传截图(整页换 Element Plus),图片随反馈入库,管理端报表可看缩略图与大图,企微通知加「附图:N 张」文字行。
|
||||||
|
|
||||||
|
**Architecture:** 复用平台文件资产设施(`POST /api/files/assets` → MinIO + 72h 孤儿清理)。用户选图后立即上传,提交时 JSON 携带 `image_asset_nos[]`,后端建子表 `general_feedback_images` 关联并调 `mark_asset_referenced` 防清理。管理端图片由后端 raw 接口代理输出(不走 MinIO 预签名 URL,原因见 spec D6),前端 `requestBlob` 取 blob 展示。
|
||||||
|
|
||||||
|
**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic;Vue 3 + TS + Element Plus 2.14.7;MinIO。
|
||||||
|
|
||||||
|
**Spec:** `docs/superpowers/specs/2026-10-26-feedback-image-attachment-design.md`(执行者必须同时阅读,数值与决策以 spec 为准)
|
||||||
|
|
||||||
|
## Global Constraints
|
||||||
|
|
||||||
|
- 每条反馈最多 **5** 张图,单张 **10MB**,格式仅 png/jpg/jpeg/webp;客户端与服务端双重校验(spec D4)。
|
||||||
|
- 仅允许挂载 `reference_count == 0` 且 `lifecycle_status == 'temporary'` 的资产(spec D9)。
|
||||||
|
- `POST /api/user/feedback` 响应契约不变:`{'status':'ok','id':<int>}`(spec D8)。
|
||||||
|
- 新增错误码 `FEEDBACK.IMAGE_INVALID` / `FEEDBACK.IMAGE_TOO_MANY` / `FEEDBACK.IMAGE_NOT_FOUND` 必须同步四语言 `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json`(键名为下划线风格,如 `FEEDBACK_IMAGE_INVALID`)。
|
||||||
|
- 所有新增文案四语言齐备,禁止硬编码中文。
|
||||||
|
- 反馈弹窗整页 Element Plus,禁止再出现 `btn-*`/`input-field`/`select-field`/手写 `<button>`/`<select>`/`<textarea>`(管理端 ReportsPage 例外:只加展示型 `<img>` 与 overlay,不新增表单控件)。
|
||||||
|
- 不新增任何第三方依赖。
|
||||||
|
- 新文件顶部按 AGENTS.md §5 写文件层块注释;新增/调整的核心函数带 docstring/JSDoc。
|
||||||
|
- 提交信息符合 Conventional Commits:`type(scope): 中文祈使句`(scope 英文 kebab)。
|
||||||
|
|
||||||
|
## Review Focus
|
||||||
|
|
||||||
|
spec 隐含但任务测试未覆盖、最容易咬人的五类输入(人工验证时重点看):
|
||||||
|
|
||||||
|
1. **粘贴内容同时含文本与图片**(聊天工具复制):只有图片项成为附件,文本粘贴进输入框的行为不得被破坏 → Task 5 的 `onPaste` 只在有 image item 时 `preventDefault`;人工验证。
|
||||||
|
2. **同一张图被并发/重复提交到两条反馈**:应被拒(`FEEDBACK.IMAGE_INVALID`),不能 500 → Task 2 的 commit 包 `IntegrityError` 兜底;测试 `test_submit_rejects_referenced_asset` 钉串行路径。
|
||||||
|
3. **报表页满屏 5 图大图**(慢网络):无图行零图片请求,缩略图 `loading="lazy"` → Task 6 人工验证 Network 面板。
|
||||||
|
4. **历史无图反馈**:images 列显示 `-`,排序/筛选/导出不受影响 → Task 4 测试 `test_report_rows_include_images` 含无图行断言。
|
||||||
|
5. **一次粘贴超过 5 张**:整批拒绝并提示 `feedback.upload.maxCount`,不得静默截取前 5 张 → Task 5 `addImages` 的行为钉死;人工验证。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 1: 数据模型与迁移
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/app/models/chat.py`(在 `GeneralFeedback` 类之后追加)
|
||||||
|
- Modify: `backend/app/models/__init__.py:13`(import 行)与 `__all__` 中 `'GeneralFeedback'` 旁
|
||||||
|
- Create: `backend/migrations/versions/<rev>_add_general_feedback_images.py`(由 flask db migrate 生成)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Produces: 模型 `GeneralFeedbackImage`(表 `general_feedback_images`),字段:`id`(PK)、`feedback_id`(FK `general_feedbacks.id`,NOT NULL,index)、`asset_id`(FK `file_assets.id`,NOT NULL,**unique**)、`sort_order`(Integer,NOT NULL,default 0)、`created_at`(DateTime,default `datetime.utcnow`)。`GeneralFeedback` 上新增 `images: Mapped[list['GeneralFeedbackImage']] = relationship(order_by='GeneralFeedbackImage.sort_order', cascade='all, delete-orphan')`。后续所有任务经 `from app.models import GeneralFeedbackImage` 引用。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 在 `backend/app/models/chat.py` 追加模型**
|
||||||
|
|
||||||
|
```python
|
||||||
|
class GeneralFeedbackImage(Base):
|
||||||
|
"""
|
||||||
|
通用意见反馈附件图表
|
||||||
|
用途:关联 general_feedbacks 与 file_assets,一条反馈可带多张截图;asset_id 唯一,一图只挂一条反馈
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = 'general_feedback_images'
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
feedback_id: Mapped[int] = mapped_column(ForeignKey('general_feedbacks.id'), index=True)
|
||||||
|
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), unique=True)
|
||||||
|
sort_order: Mapped[int] = mapped_column(default=0)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||||
|
```
|
||||||
|
|
||||||
|
并在 `GeneralFeedback` 类体内加 `images` relationship(如上 Interfaces 所示,含注释说明级联随反馈删除)。
|
||||||
|
|
||||||
|
- [ ] **Step 2: 在 `backend/app/models/__init__.py` 注册导出**
|
||||||
|
|
||||||
|
第 13 行 import 加入 `GeneralFeedbackImage`;`__all__` 列表在 `'GeneralFeedback'` 后加 `'GeneralFeedbackImage'`。
|
||||||
|
|
||||||
|
- [ ] **Step 3: 生成迁移**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend && source venv/bin/activate # Windows Git Bash: source venv/Scripts/activate
|
||||||
|
flask db migrate -m "add general_feedback_images table"
|
||||||
|
```
|
||||||
|
|
||||||
|
检查生成的文件:`down_revision` 必须为 `'mh23e4f5a6b7'`(当前单 head),upgrade 只含 `create_table('general_feedback_images', ...)`(id/feedback_id/asset_id/sort_order/created_at + 索引 + unique 约束),无其他意外变更。若本地无可用数据库连接,则手写迁移文件(仿 `backend/migrations/versions/dq2e3f4g5h6i_add_per_source_inventory_rpa_attempts.py` 的结构,`revision` 用新随机 12 位 id)。
|
||||||
|
|
||||||
|
- [ ] **Step 4: 验证迁移链与模型可导入**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
flask db heads # 期望:仅一个 head,即新 revision
|
||||||
|
python -c "from app.models import GeneralFeedbackImage; print(GeneralFeedbackImage.__tablename__)"
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: 单 head;打印 `general_feedback_images`。
|
||||||
|
|
||||||
|
- [ ] **Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/app/models/chat.py backend/app/models/__init__.py backend/migrations/versions/
|
||||||
|
git commit -m "feat(feedback): 新增反馈图片关联表与模型"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 2: 提交接口携带图片资产(后端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/app/api/user/handlers.py:122-176`(`submit_general_feedback`)
|
||||||
|
- Test: `backend/tests/api/test_general_feedback_api.py`(新建)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: Task 1 的 `GeneralFeedbackImage`;现有 `get_asset_for_user(asset_no: str, user_id: int) -> FileAsset`(`app/services/file_assets/service.py:119`,NotFoundError/ForbiddenError)、`mark_asset_referenced(asset: FileAsset) -> None`(`service.py:430`)。
|
||||||
|
- Produces: `POST /api/user/feedback` 请求体新增可选 `image_asset_nos: string[]`(顺序即 sort_order)。校验失败抛 `ValidationError(code='FEEDBACK.IMAGE_TOO_MANY'|'FEEDBACK.IMAGE_INVALID', message=...)` / 沿用 `get_asset_for_user` 的 `FILE_ASSET.*` 异常。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 写失败测试**
|
||||||
|
|
||||||
|
新建 `backend/tests/api/test_general_feedback_api.py`。文件头块注释说明用途/依赖/逻辑(AGENTS.md §5.1)。复用全局 `app`/`client` 夹具(`backend/tests/conftest.py:562,692`,`create_app('testing')` + `create_all`)。鉴权仿 `backend/tests/api/test_transfer_type_api.py:60-77`:
|
||||||
|
|
||||||
|
```python
|
||||||
|
from app.core.auth.jwt import issue_local_access_token
|
||||||
|
|
||||||
|
def _headers(user: User) -> dict:
|
||||||
|
"""为指定用户签发 Bearer JWT 请求头(须在 app context 内调用)。"""
|
||||||
|
token = issue_local_access_token(user)
|
||||||
|
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def user_headers(app):
|
||||||
|
"""普通用户 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
user = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
if not user:
|
||||||
|
user = User(username="fbuser", email="fbuser@example.com", role="user", status="active")
|
||||||
|
user.set_password("x")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return _headers(user)
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def admin_headers(app):
|
||||||
|
"""平台管理员 JWT 请求头。"""
|
||||||
|
with app.app_context():
|
||||||
|
user = db.session.query(User).filter_by(username="fbadmin").first()
|
||||||
|
if not user:
|
||||||
|
user = User(username="fbadmin", email="fbadmin@example.com", role="admin", status="active")
|
||||||
|
user.set_password("x")
|
||||||
|
db.session.add(user)
|
||||||
|
db.session.commit()
|
||||||
|
return _headers(user)
|
||||||
|
|
||||||
|
def _make_asset(user_id: int, ext: str = "png", mime: str = "image/png", *, reference_count: int = 0, lifecycle: str = "temporary") -> FileAsset:
|
||||||
|
"""直接落一条 ready/temporary 的 FileAsset 行(不经过 MinIO)。"""
|
||||||
|
asset = FileAsset(
|
||||||
|
asset_no=f"FA-TEST-{uuid4().hex[:8].upper()}", owner_user_id=int(user_id),
|
||||||
|
original_filename=f"screenshot.{ext}", storage_provider="minio", storage_bucket="test",
|
||||||
|
storage_key=f"test/{user_id}/{uuid4().hex}", content_hash="0" * 64, file_size=1024,
|
||||||
|
mime_type=mime, extension=ext, upload_status="ready",
|
||||||
|
lifecycle_status=lifecycle, reference_count=reference_count,
|
||||||
|
)
|
||||||
|
db.session.add(asset)
|
||||||
|
db.session.commit()
|
||||||
|
return asset
|
||||||
|
```
|
||||||
|
|
||||||
|
测试用例(本任务实现前 6 个;断言错误码用 `tests/conftest.py` 的 `parse_api_error`):
|
||||||
|
|
||||||
|
```python
|
||||||
|
def test_submit_with_images_claims_assets(app, client, user_headers):
|
||||||
|
"""带图提交:两图按顺序落库,资产被引用(reference_count=1、referenced、expires_at 清空)。"""
|
||||||
|
with app.app_context():
|
||||||
|
u = db.session.query(User).filter_by(username="fbuser").first()
|
||||||
|
a1 = _make_asset(u.id)
|
||||||
|
a2 = _make_asset(u.id, ext="jpg", mime="image/jpeg")
|
||||||
|
resp = client.post("/api/user/feedback", headers=user_headers, json={
|
||||||
|
"feedback_type": "问题反馈", "feedback_module": "知识库", "content": "带上截图",
|
||||||
|
"source_page": "workspace", "image_asset_nos": [a1.asset_no, a2.asset_no],
|
||||||
|
})
|
||||||
|
assert resp.status_code == 200
|
||||||
|
with app.app_context():
|
||||||
|
imgs = GeneralFeedbackImage.query.order_by(GeneralFeedbackImage.sort_order).all()
|
||||||
|
assert [i.sort_order for i in imgs] == [0, 1]
|
||||||
|
for i in imgs:
|
||||||
|
asset = db.session.get(FileAsset, i.asset_id)
|
||||||
|
assert asset.reference_count == 1
|
||||||
|
assert asset.lifecycle_status == "referenced"
|
||||||
|
assert asset.expires_at is None
|
||||||
|
|
||||||
|
def test_submit_rejects_foreign_asset(app, client, user_headers):
|
||||||
|
"""他人资产 → 403 FILE_ASSET.FORBIDDEN,反馈不落库。"""
|
||||||
|
def test_submit_rejects_non_image(app, client, user_headers):
|
||||||
|
"""ext='pdf' 的资产 → 400 FEEDBACK.IMAGE_INVALID。"""
|
||||||
|
def test_submit_rejects_referenced_asset(app, client, user_headers):
|
||||||
|
"""reference_count=1 的图片资产 → 400 FEEDBACK.IMAGE_INVALID(防挂已被业务引用资产)。"""
|
||||||
|
def test_submit_rejects_too_many(app, client, user_headers):
|
||||||
|
"""6 个 asset_no → 400 FEEDBACK.IMAGE_TOO_MANY,反馈不落库。"""
|
||||||
|
def test_submit_text_only_keeps_legacy(app, client, user_headers):
|
||||||
|
"""不带 image_asset_nos:200,general_feedback_images 零行(回归)。"""
|
||||||
|
```
|
||||||
|
|
||||||
|
省略体断言:非 2xx 时用 `parse_api_error(resp.get_json())["code"]` 断错误码,并断 `GeneralFeedbackImage.query.count() == 0`(拒绝路径不落任何行)。
|
||||||
|
|
||||||
|
- [ ] **Step 2: 运行确认失败**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend && python -m pytest tests/api/test_general_feedback_api.py -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: FAIL/ERROR(接口忽略 `image_asset_nos`,断言 0 行失败)。
|
||||||
|
|
||||||
|
- [ ] **Step 3: 实现接口逻辑**
|
||||||
|
|
||||||
|
`handlers.py` 顶部模块常量与 import:
|
||||||
|
|
||||||
|
```python
|
||||||
|
_FEEDBACK_MAX_IMAGES = 5
|
||||||
|
_FEEDBACK_IMAGE_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'}
|
||||||
|
```
|
||||||
|
|
||||||
|
import 增加 `GeneralFeedbackImage`(第 12 行 models import)与 `from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced`。
|
||||||
|
|
||||||
|
`submit_general_feedback` 中,在现有 chat_log 校验之后、`row = GeneralFeedback(...)` 之前插入 `[STEP]` 注释分块(AGENTS.md §5.3):
|
||||||
|
|
||||||
|
1. 解析:`raw = data.get('image_asset_nos')`;非 list → `ValidationError(code='FEEDBACK.IMAGE_INVALID', message='image_asset_nos must be a list')`;元素转 str 去空白、去重(保序);`len > _FEEDBACK_MAX_IMAGES` → `ValidationError(code='FEEDBACK.IMAGE_TOO_MANY', message='最多附加 5 张图片')`。
|
||||||
|
2. 逐个校验(任一失败整单拒绝):`asset = get_asset_for_user(asset_no, user.id)`;`asset.extension not in _FEEDBACK_IMAGE_EXTENSIONS` → FEEDBACK.IMAGE_INVALID(message 注明仅支持图片);`asset.upload_status != 'ready'` → FEEDBACK.IMAGE_INVALID;`asset.reference_count != 0 or asset.lifecycle_status != 'temporary'` → FEEDBACK.IMAGE_INVALID(message 注明该文件已被使用)。通过者收集为 `assets: list[FileAsset]`。
|
||||||
|
3. 落库:`db.session.add(row)` → `db.session.flush()` 拿 `row.id` → 按枚举序 `GeneralFeedbackImage(feedback_id=row.id, asset_id=a.id, sort_order=idx)` → 逐个 `mark_asset_referenced(a)` → `try: db.session.commit() except IntegrityError: db.session.rollback(); raise ValidationError(code='FEEDBACK.IMAGE_INVALID', message='图片已被使用,请重新添加')`(并发双挂兜底,Review Focus 2;IntegrityError 已在文件头 import)。
|
||||||
|
4. 通知与返回不变(`send_feedback_group_notification(row, user)` 之后,`jsonify({'status': 'ok', 'id': row.id})`)。
|
||||||
|
|
||||||
|
- [ ] **Step 4: 同步错误码四语言**
|
||||||
|
|
||||||
|
`frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json` 的 codes 段(搜 `FILE_ASSET_INVALID_TYPE` 所在对象,同层追加):
|
||||||
|
|
||||||
|
- zh-CN:`"FEEDBACK_IMAGE_INVALID": "反馈图片无效或已被使用。"`,`"FEEDBACK_IMAGE_TOO_MANY": "反馈图片数量超过上限。"`,`"FEEDBACK_IMAGE_NOT_FOUND": "反馈图片不存在。"`
|
||||||
|
- zh-TW:`"FEEDBACK_IMAGE_INVALID": "迴饋圖片無效或已被使用。"`,`"FEEDBACK_IMAGE_TOO_MANY": "迴饋圖片數量超過上限。"`,`"FEEDBACK_IMAGE_NOT_FOUND": "迴饋圖片不存在。"`
|
||||||
|
- en:`"FEEDBACK_IMAGE_INVALID": "The feedback image is invalid or already in use."`,`"FEEDBACK_IMAGE_TOO_MANY": "Too many feedback images."`,`"FEEDBACK_IMAGE_NOT_FOUND": "Feedback image not found."`
|
||||||
|
- th:`"FEEDBACK_IMAGE_INVALID": "รูปภาพข้อเสนอแนะไม่ถูกต้องหรือถูกใช้งานแล้ว"`,`"FEEDBACK_IMAGE_TOO_MANY": "จำนวนรูปภาพข้อเสนอแนะเกินกำหนด"`,`"FEEDBACK_IMAGE_NOT_FOUND": "ไม่พบรูปภาพข้อเสนอแนะ"`
|
||||||
|
|
||||||
|
- [ ] **Step 5: 运行测试确认通过**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pytest tests/api/test_general_feedback_api.py -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: 6 个用例全 PASS。
|
||||||
|
|
||||||
|
- [ ] **Step 6: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/app/api/user/handlers.py backend/tests/api/test_general_feedback_api.py frontend/src/locales/
|
||||||
|
git commit -m "feat(feedback): 提交接口支持携带图片资产并校验引用"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 3: 企微通知附图行(后端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/app/services/feedback_notify.py`(`build_feedback_markdown`,93-135 行)
|
||||||
|
- Test: `backend/tests/services/test_feedback_notify.py`(新建)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: Task 1 的 `GeneralFeedback.images` relationship。
|
||||||
|
- Produces: markdown 在「反馈内容」段之前多一行 `>附图:{N} 张`(仅当 N>0)。消息其余行与顺序不变。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 写失败测试**
|
||||||
|
|
||||||
|
```python
|
||||||
|
def test_markdown_includes_image_count(app):
|
||||||
|
"""有图反馈:markdown 含「附图:2 张」行;无图反馈:不含「附图」。"""
|
||||||
|
# app context 内建 GeneralFeedback + 2 条 GeneralFeedbackImage(feedback_id 指向它),commit;
|
||||||
|
# md = build_feedback_markdown(fb, None)
|
||||||
|
# assert "附图:2 张" in md;再建一条无图反馈断 "附图" not in 其 md
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: 运行确认失败**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pytest tests/services/test_feedback_notify.py -v # Expected: FAIL(无附图行)
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: 实现**
|
||||||
|
|
||||||
|
`build_feedback_markdown` 中 `lines.extend(['', '**反馈内容:**', content or '-'])` 之前插入:
|
||||||
|
|
||||||
|
```python
|
||||||
|
image_count = len(feedback.images or [])
|
||||||
|
if image_count:
|
||||||
|
lines.append(f'>附图:{image_count} 张')
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: 运行确认通过** 同 Step 2 命令,Expected: PASS。
|
||||||
|
|
||||||
|
- [ ] **Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/app/services/feedback_notify.py backend/tests/services/test_feedback_notify.py
|
||||||
|
git commit -m "feat(feedback): 企微反馈通知增加附图数量行"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 4: 报表行附图元数据 + 管理端图片代理接口(后端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `backend/app/services/admin/report_service.py:560-589`(`list_general_feedbacks_report`)与文件内新增函数
|
||||||
|
- Modify: `backend/app/api/admin/reports.py`(追加路由)
|
||||||
|
- Test: `backend/tests/api/test_general_feedback_api.py`(追加用例)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: Task 1 模型;现有 `read_asset_bytes(asset: FileAsset) -> bytes`(`service.py:623`,校验未删除/未过期)。
|
||||||
|
- Produces:
|
||||||
|
- `list_general_feedbacks_report` 每行新增 `images: list[dict]`,元素键恰为 `image_id, asset_no, original_filename, file_size, sort_order`(int/str/str/int/int),按 sort_order 升序;无图行 `images == []`。
|
||||||
|
- `report_service.get_general_feedback_image_payload(feedback_id: int, image_id: int) -> dict`,返回 `{'data': bytes, 'mime_type': str, 'filename': str}`;image 不存在或不属于该 feedback → `NotFoundError(code='FEEDBACK.IMAGE_NOT_FOUND', message='反馈图片不存在')`。
|
||||||
|
- 路由 `GET /api/admin/reports/general-feedbacks/<int:feedback_id>/images/<int:image_id>/raw`,`@require_admin`,响应为图片字节流:`Content-Type` = mime,`Content-Disposition: inline; filename*=UTF-8''<quote(filename)>`(`urllib.parse.quote`)。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 写失败测试**(追加到 `test_general_feedback_api.py`)
|
||||||
|
|
||||||
|
```python
|
||||||
|
def test_report_rows_include_images(app, client, user_headers, admin_headers):
|
||||||
|
"""报表行含 images 元数据;无图行 images==[]。"""
|
||||||
|
# user 提交一条带 a1 的反馈 + 一条纯文本反馈;
|
||||||
|
# admin GET /api/admin/reports/general-feedbacks → 找到两行:
|
||||||
|
# 有图行 images[0] 键集合 == {"image_id","asset_no","original_filename","file_size","sort_order"} 且 asset_no==a1.asset_no;
|
||||||
|
# 无图行 images == []
|
||||||
|
|
||||||
|
def test_admin_image_raw_streams(app, client, user_headers, admin_headers, monkeypatch):
|
||||||
|
"""管理员经 raw 接口取到图片字节;错配 feedback_id → 404 FEEDBACK.IMAGE_NOT_FOUND;非管理员 → 403。"""
|
||||||
|
# monkeypatch app.services.file_assets.service.file_asset_storage.get_bytes = lambda key: b"\x89PNG\r\n\x1a\nfake"
|
||||||
|
# 提交一条带图反馈后:GET .../<fb_id>/images/<image_id>/raw → 200,data 匹配,content_type 以 "image/png" 开头
|
||||||
|
# GET .../<fb_id + 99999>/images/<同一 image_id>/raw → 404,parse_api_error code == FEEDBACK.IMAGE_NOT_FOUND
|
||||||
|
# 同接口换 user_headers → 403
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 2: 运行确认失败**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pytest tests/api/test_general_feedback_api.py -v # Expected: 新用例 FAIL(无 images 键/404)
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: 实现 service 与路由**
|
||||||
|
|
||||||
|
`report_service.py`:import `GeneralFeedbackImage` 与 `from app.models import FileAsset`、`from app.services.file_assets.service import read_asset_bytes`。`list_general_feedbacks_report` 行构建后批量补 images:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def _attach_general_feedback_images(rows: list[dict], feedback_ids: list[int]) -> None:
|
||||||
|
"""批量回填每行 images 元数据(单查询,按 sort_order 排序),无图行置空列表。"""
|
||||||
|
```
|
||||||
|
|
||||||
|
实现:单条 query `GeneralFeedbackImage` join `FileAsset`,`feedback_id.in_(feedback_ids)`,`order_by(sort_order, id)`,按 feedback_id 分组后写入各行。`list_general_feedbacks_report` 末尾调用它。
|
||||||
|
|
||||||
|
新增:
|
||||||
|
|
||||||
|
```python
|
||||||
|
def get_general_feedback_image_payload(feedback_id: int, image_id: int) -> dict:
|
||||||
|
"""读取反馈图片字节(管理端代理输出,不走 MinIO 预签名,见 spec D6)。"""
|
||||||
|
# GeneralFeedbackImage.filter_by(id=image_id, feedback_id=feedback_id).first() → 无则 FEEDBACK.IMAGE_NOT_FOUND
|
||||||
|
# asset = db.session.get(FileAsset, img.asset_id);asset 为 None 或 deleted_at 非空 → 同上
|
||||||
|
# data = read_asset_bytes(asset);返回 {'data': data, 'mime_type': asset.mime_type or 'application/octet-stream', 'filename': asset.original_filename}
|
||||||
|
```
|
||||||
|
|
||||||
|
`reports.py` 追加(import `Response`、`urllib.parse.quote`、`report_service` 已有):
|
||||||
|
|
||||||
|
```python
|
||||||
|
@admin_bp.route('/reports/general-feedbacks/<int:feedback_id>/images/<int:image_id>/raw', methods=['GET'])
|
||||||
|
@require_admin
|
||||||
|
def general_feedback_image_raw(feedback_id: int, image_id: int):
|
||||||
|
"""代理输出意见反馈截图字节流(inline 展示用)。"""
|
||||||
|
payload = report_service.get_general_feedback_image_payload(feedback_id, image_id)
|
||||||
|
resp = Response(payload['data'], mimetype=payload['mime_type'])
|
||||||
|
resp.headers['Content-Disposition'] = f"inline; filename*=UTF-8''{quote(payload['filename'])}"
|
||||||
|
return resp
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: 运行确认通过**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m pytest tests/api/test_general_feedback_api.py -v # Expected: 全部 PASS
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add backend/app/services/admin/report_service.py backend/app/api/admin/reports.py backend/tests/api/test_general_feedback_api.py
|
||||||
|
git commit -m "feat(admin): 报表反馈行内附图元数据与图片代理接口"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 5: 反馈弹窗 Element Plus 化 + 粘贴/选图上传(前端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Rewrite: `frontend/src/shared/components/GeneralFeedbackDialog.vue`
|
||||||
|
- Modify: `frontend/src/features/workspace/components/WorkspaceModals.vue`(移除 `:auth-headers` 绑定与未再使用的 `getAuthHeaders` import)
|
||||||
|
- Modify: `frontend/src/features/chat/components/ChatViewOverlays.vue`(同上)
|
||||||
|
- Modify: `frontend/src/features/workspace/pages/FeedbackPage.vue`(同上,若有绑定)
|
||||||
|
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/feedback.json`(新增 `upload` 段)
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: `uploadFileAsset(file: File): Promise<FileAssetResponse>`(`@/shared/api/file-assets.api.ts`,返回含 `asset_no`);`requestJson<T>(url, init)`(`@/shared/api/client`,自动附鉴权头,失败抛 `BusinessError`);现有 props `modelValue: boolean`、`sourcePage?: string`(默认 'unknown')、`chatLogId?: number | null`,emits `update:modelValue` / `submitted` **保持不变**(仅删除 `authHeaders`)。
|
||||||
|
- Produces: 提交 payload 新增 `image_asset_nos: string[]`(仅 `status==='ready'` 的图,按添加顺序)。i18n 键 `feedback.upload.*`。
|
||||||
|
|
||||||
|
- [ ] **Step 1: 四语言 `feedback.json` 增加 `upload` 段**
|
||||||
|
|
||||||
|
在 `submit` 键后追加(`zh-CN` 为准,其余三语言如下):
|
||||||
|
|
||||||
|
```json
|
||||||
|
"upload": {
|
||||||
|
"addImage": "添加图片",
|
||||||
|
"pasteHint": "支持粘贴截图(Ctrl+V)或点击添加,最多 5 张",
|
||||||
|
"maxCount": "最多添加 {count} 张图片",
|
||||||
|
"maxSize": "单张图片不能超过 {size}MB",
|
||||||
|
"invalidType": "仅支持 png / jpg / jpeg / webp 格式图片",
|
||||||
|
"uploadFailed": "图片上传失败,请重试",
|
||||||
|
"remove": "移除图片"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- zh-TW:`添加圖片` / `支援貼上截圖(Ctrl+V)或點擊新增,最多 5 張` / `最多新增 {count} 張圖片` / `單張圖片不能超過 {size}MB` / `僅支援 png / jpg / jpeg / webp 格式圖片` / `圖片上傳失敗,請重試` / `移除圖片`
|
||||||
|
- en:`Add images` / `Paste a screenshot (Ctrl+V) or click to add, up to 5` / `Up to {count} images` / `Each image must be within {size}MB` / `Only png / jpg / jpeg / webp images are supported` / `Image upload failed, please retry` / `Remove image`
|
||||||
|
- th:`เพิ่มรูปภาพ` / `วางภาพหน้าจอ (Ctrl+V) หรือคลิกเพื่อเพิ่ม สูงสุด 5 รูป` / `เพิ่มได้สูงสุด {count} รูป` / `รูปภาพเดียวต้องไม่เกิน {size}MB` / `รองรับเฉพาะไฟล์ png / jpg / jpeg / webp` / `อัปโหลดรูปภาพไม่สำเร็จ กรุณาลองอีกครั้ง` / `นำรูปภาพออก`
|
||||||
|
|
||||||
|
- [ ] **Step 2: 重写 `GeneralFeedbackDialog.vue`**
|
||||||
|
|
||||||
|
文件头块注释更新(用途/依赖:element-plus、file-assets.api、client/依赖关系)。要点:
|
||||||
|
|
||||||
|
- import 样式仿 `frontend/src/features/admin/modules/agents/AgentsPage.vue:14-23`:按需 `import { ElButton, ElDialog, ElInput, ElMessage, ElOption, ElSegmented, ElSelect } from 'element-plus'` + `import 'element-plus/dist/index.css'`(组件级导入,Vite 自动去重)。
|
||||||
|
- Props 删除 `authHeaders`;`visible = computed({ get: () => props.modelValue, set: (v) => emit('update:modelValue', v) })`。
|
||||||
|
- 模板:`<ElDialog v-model="visible" :title="t('feedback.title')" width="640px" append-to-body :close-on-click-modal="false">`;内容外层 `<div @paste="onPaste">`;类型用 `<ElSegmented :options="typeOptions" v-model="selectedType" />`;模块用 `ElSelect` + `ElOption v-for`;内容用 `<ElInput v-model="content" type="textarea" :rows="5" :maxlength="2000" show-word-limit resize="none" :placeholder="..." />`;底部 `ElButton`(取消)与 `ElButton type="primary" :loading="submitting"`(提交)。字数统计与错误行保留在输入框下方。
|
||||||
|
- 图片条(输入框下方):已添加图片渲染 48×48 缩略图(`:src="img.previewUrl"`,右上角小 × = `removeImage`,uploading 状态加半透明遮罩);末尾「添加图片」格子(Plus 图标 + `t('feedback.upload.addImage')`,点击触发隐藏 `<input type="file" multiple accept="image/png,image/jpeg,image/webp">`);下方灰色提示 `t('feedback.upload.pasteHint')`。
|
||||||
|
- 组件常量与逻辑(签名钉死):
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const MAX_FEEDBACK_IMAGES = 5;
|
||||||
|
const MAX_FEEDBACK_IMAGE_SIZE_MB = 10;
|
||||||
|
const FEEDBACK_IMAGE_ACCEPT = ['image/png', 'image/jpeg', 'image/webp'];
|
||||||
|
|
||||||
|
interface PendingImage {
|
||||||
|
assetNo: string | null; // 上传成功后的 FA 编号
|
||||||
|
status: 'uploading' | 'ready';
|
||||||
|
previewUrl: string; // URL.createObjectURL(file)
|
||||||
|
filename: string;
|
||||||
|
}
|
||||||
|
const images = ref<PendingImage[]>([]);
|
||||||
|
const hasUploadingImage = computed(() => images.value.some((i) => i.status === 'uploading'));
|
||||||
|
const canSubmit = computed(() => content.value.trim().length > 0 && !submitting.value && !hasUploadingImage.value);
|
||||||
|
|
||||||
|
/** [AI 触发时机] 无 —— 纯 UI 交互:批量加入图片;超过上限整批拒绝并提示 maxCount(不截取前 N 张)。 */
|
||||||
|
async function addImages(files: File[]): Promise<void>
|
||||||
|
// 校验:先过滤类型不在 FEEDBACK_IMAGE_ACCEPT 的 → ElMessage.error(invalidType);
|
||||||
|
// 若 files.length + images.length > MAX_FEEDBACK_IMAGES → ElMessage.error(t('feedback.upload.maxCount', { count: MAX_FEEDBACK_IMAGES })) 且整批不入队;
|
||||||
|
// 单张 file.size > MAX_FEEDBACK_IMAGE_SIZE_MB * 1024 * 1024 → ElMessage.error(maxSize) 跳过该张;
|
||||||
|
// 逐张入队 status='uploading' → uploadFileAsset(file) 成功置 ready+assetNo;失败:移除该项 + ElMessage.error(uploadFailed)。
|
||||||
|
|
||||||
|
function removeImage(index: number): void // revoke previewUrl 后 splice
|
||||||
|
function onPaste(e: ClipboardEvent): void // e.clipboardData.items 中 kind==='file' 且 type 以 'image/' 开头的项 getAsFile();仅当取到文件才 preventDefault;调 addImages
|
||||||
|
function onFileChange(e: Event): void // input.files → addImages → input.value = ''
|
||||||
|
function cleanupImages(): void // 全部 revoke + 清空(resetForm 与弹窗关闭时调用,复用现有 watch(modelValue) 位置)
|
||||||
|
```
|
||||||
|
|
||||||
|
- 提交:`requestJson<void>('/api/user/feedback', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ feedback_type, feedback_module, content, source_page, ...(chatLogId != null ? { chat_log_id: chatLogId } : {}), image_asset_nos: images.value.filter(i => i.status === 'ready').map(i => i.assetNo as string) }) })`;捕获 `BusinessError` → `error.value = e.message`(沿用现有内联错误展示);成功路径不变(`emit('submitted'); closeDialog()`)。
|
||||||
|
- 其余行为保持:类型/模块仍存**翻译后的展示文案**;语言切换时 resetForm 的 watch 保留(cleanupImages 一并调用)。
|
||||||
|
|
||||||
|
- [ ] **Step 3: 更新三个挂载点**
|
||||||
|
|
||||||
|
在 `WorkspaceModals.vue`、`ChatViewOverlays.vue`、`FeedbackPage.vue` 中删除传给 `GeneralFeedbackDialog` 的 `:auth-headers="getAuthHeaders()"`(属性名以实际文件为准);若 `getAuthHeaders` 在该文件无其他使用,连同 import 一并删除。
|
||||||
|
|
||||||
|
- [ ] **Step 4: 构建验证**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend && npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
Expected: 构建通过,无 TS 报错;grep 确认 `GeneralFeedbackDialog.vue` 内无 `btn-`/`input-field`/`<textarea`/`<select`。
|
||||||
|
|
||||||
|
- [ ] **Step 5: 人工验证(dev server)**
|
||||||
|
|
||||||
|
`npm run dev` 后:粘贴一张截图 → 缩略图出现;粘贴 6 张 → maxCount 提示;删除、提交成功;workspace 与 chat 两个入口弹窗均可开、提交成功(chat 入口带 chat_log_id)。暗色主题下弹窗可读。
|
||||||
|
|
||||||
|
- [ ] **Step 6: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add frontend/src/shared/components/GeneralFeedbackDialog.vue frontend/src/features/workspace/components/WorkspaceModals.vue frontend/src/features/chat/components/ChatViewOverlays.vue frontend/src/features/workspace/pages/FeedbackPage.vue frontend/src/locales/
|
||||||
|
git commit -m "feat(feedback): 反馈弹窗整页替换 Element Plus 并支持粘贴与选图上传"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 6: 管理端报表附图缩略图与大图预览(前端)
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `frontend/src/features/admin/api/admin.api.ts`(类型)
|
||||||
|
- Modify: `frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts`
|
||||||
|
- Modify: `frontend/src/features/admin/modules/reports/ReportsPage.vue`
|
||||||
|
|
||||||
|
**Interfaces:**
|
||||||
|
- Consumes: Task 4 的行内 `images` 元数据与 raw 接口;现有 `requestBlob(url)`(`@/shared/api/client`,自动附鉴权头,返回 `{ blob, filename? }`)。
|
||||||
|
- Produces(在 `useReportsAdmin` 返回对象中新增,供 ReportsPage 解构):
|
||||||
|
- `feedbackImagePreview: Ref<{ feedbackId: number; images: FeedbackReportImage[]; index: number } | null>`
|
||||||
|
- `feedbackImageUrl(feedbackId: number, imageId: number): string | null`(objectURL 缓存,键 `${feedbackId}:${imageId}`,未加载过返回 null)
|
||||||
|
- `loadFeedbackImage(feedbackId: number, imageId: number): Promise<void>`(缓存键 `${feedbackId}:${imageId}` 已存在时直接 return;否则 `requestBlob('/api/admin/reports/general-feedbacks/${feedbackId}/images/${imageId}/raw')` → `URL.createObjectURL(blob)` 入缓存;失败静默置缓存值为 `''` 表示占位)
|
||||||
|
- `openFeedbackImagePreview(row: any, index: number): void` / `closeFeedbackImagePreview(): void` / `stepFeedbackImagePreview(delta: number): void`(index 在 images 内循环)
|
||||||
|
- 类型:`interface FeedbackReportImage { image_id: number; asset_no: string; original_filename: string; file_size: number; sort_order: number }`(放 admin.api.ts 并导出);报表行类型加可选 `images?: FeedbackReportImage[]`。
|
||||||
|
|
||||||
|
- [ ] **Step 1: composable 改造**
|
||||||
|
|
||||||
|
1. `visibleReportKeys` 的 `feedbackFixedOrder`(1068-1079 行)在 `'content'` 后插入 `'images'`。
|
||||||
|
2. 现有按列名返回宽度的 switch(useReportsAdmin.ts 顶部,`default: return 160;` 处)加 `case 'images': return 176;`。
|
||||||
|
3. `feedbackReportI18nMap` 四个语言包的 `generalColumns` 各加一条(en/zh-CN/zh-TW/th):`images: 'Images'` / `images: '附图'` / `images: '附圖'` / `images: 'รูปภาพ'`(CJK 沿用文件内已有的 `\uXXXX` 转义风格)。
|
||||||
|
4. 新增 Interfaces 段列出的状态与五个函数(含 objectURL 缓存 `Map<string, string>`,模块级或 composable 闭包内)。
|
||||||
|
|
||||||
|
- [ ] **Step 2: ReportsPage 单元格与 lightbox**
|
||||||
|
|
||||||
|
1. 意见反馈内容列旁新增分支(1417 行的 `<template v-if=...>` 链中,chat_log_id 分支之前):
|
||||||
|
|
||||||
|
```html
|
||||||
|
<template v-else-if="isMergedFeedbackTable && feedbackTab === 'general' && key === 'images'">
|
||||||
|
<div class="flex items-center gap-1" :style="getReportCellInnerStyle()">
|
||||||
|
<template v-if="(row.images || []).length">
|
||||||
|
<img
|
||||||
|
v-for="(img, i) in row.images"
|
||||||
|
:key="img.image_id"
|
||||||
|
:src="feedbackImageUrl(row.id, img.image_id) || ''"
|
||||||
|
:alt="img.original_filename"
|
||||||
|
loading="lazy"
|
||||||
|
class="h-10 w-10 cursor-pointer rounded border border-default object-cover"
|
||||||
|
@load="loadFeedbackImage(row.id, img.image_id)"
|
||||||
|
@error="loadFeedbackImage(row.id, img.image_id)"
|
||||||
|
@click.stop="openFeedbackImagePreview(row, i)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<span v-else class="text-muted">-</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
```
|
||||||
|
|
||||||
|
(`@load`/`@error` 触发懒加载:src 为空时浏览器立即 error → 发起 blob 加载,加载完成后缓存更新触发重渲;`<img>` 无法自带鉴权头,故必须走 blob,见 spec D6。)
|
||||||
|
|
||||||
|
2. 该单元格的 `:title` 绑定(1413 行)把 `key === 'images'` 加入置 undefined 的条件,避免 title 出现 `[object Object]`。
|
||||||
|
3. 表格之后(仿 1523-1543 行 chat-logs 详情 overlay 的自建模式)新增 lightbox:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<div v-if="feedbackImagePreview" class="fixed inset-0 z-50 flex items-center justify-center p-4">
|
||||||
|
<div class="absolute inset-0 bg-black/70" @click="closeFeedbackImagePreview"></div>
|
||||||
|
<div class="relative flex max-h-[90vh] max-w-[90vw] flex-col items-center gap-3">
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(-1)">‹</button>
|
||||||
|
<img v-if="currentPreviewUrl" :src="currentPreviewUrl" :alt="currentPreviewImage?.original_filename" class="max-h-[80vh] max-w-[80vw] rounded object-contain" />
|
||||||
|
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(1)">›</button>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 text-sm text-white/80">
|
||||||
|
<span>{{ feedbackImagePreview.index + 1 }} / {{ feedbackImagePreview.images.length }}</span>
|
||||||
|
<span>{{ currentPreviewImage?.original_filename }}</span>
|
||||||
|
<button type="button" class="btn-icon-ds" :title="t('admin.report.feedback.closePreview')" @click="closeFeedbackImagePreview">✕</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
```
|
||||||
|
|
||||||
|
`currentPreviewImage` / `currentPreviewUrl` 为 ReportsPage 内基于 `feedbackImagePreview` 与 `feedbackImageUrl` 的 computed;打开与翻页时对当前图调用 `loadFeedbackImage`。多图时(仅 1 张也显示,翻页按钮按 images.length 循环)。
|
||||||
|
|
||||||
|
4. `admin.json` 四语言 `report.feedback` 段加 `"closePreview"`:zh-CN `关闭预览` / zh-TW `關閉預覽` / en `Close preview` / th `ปิดตัวอย่าง`。
|
||||||
|
|
||||||
|
- [ ] **Step 3: 构建验证**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend && npm run build # Expected: 通过
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 4: 人工验证**
|
||||||
|
|
||||||
|
后端起 dev 服务(需 `flask db upgrade` 到新 head),提交 1-2 条带图反馈后,管理端「报表 → 用户反馈」:有图行显示缩略图,点击放大、左右翻页、关闭;无图行显示 `-`;Network 面板确认无图行零图片请求、缩略图 lazy(Review Focus 3/4)。
|
||||||
|
|
||||||
|
- [ ] **Step 5: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add frontend/src/features/admin/
|
||||||
|
git commit -m "feat(admin): 报表意见反馈页签展示附图缩略图与大图预览"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Task 7: 文档同步与收尾验证
|
||||||
|
|
||||||
|
**Files:**
|
||||||
|
- Modify: `docs/funclist.md`(意见反馈相关条目)
|
||||||
|
- Modify: `docs/superpowers/specs/2026-10-26-feedback-image-attachment-design.md`(状态行改为「已实现」)
|
||||||
|
|
||||||
|
- [ ] **Step 1: 更新 `funclist.md`**
|
||||||
|
|
||||||
|
在功能清单中「意见反馈」所在小节补一行(保持该文件既有格式):`意见反馈支持粘贴/上传截图附件(≤5 张),管理端报表可查看附图与大图预览`。若清单中无意见反馈条目,则在用户端与管理端各自最贴近的位置各补一条。
|
||||||
|
|
||||||
|
- [ ] **Step 2: 全量验证**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend && python -m pytest tests/api/test_general_feedback_api.py tests/services/test_feedback_notify.py -v # Expected: 全 PASS
|
||||||
|
cd ../frontend && npm run build # Expected: 通过
|
||||||
|
cd .. && flask db heads # (backend venv)Expected: 单 head
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Commit**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add docs/funclist.md docs/superpowers/specs/2026-10-26-feedback-image-attachment-design.md
|
||||||
|
git commit -m "docs(funclist): 补充意见反馈截图附件功能项"
|
||||||
|
```
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
# 意见反馈支持截图附件 — 设计文档
|
||||||
|
|
||||||
|
- 日期:2026-10-26
|
||||||
|
- 分支:`picture-feedback`(自 `dev` 切出,当前为空分支)
|
||||||
|
- 状态:已实现(2026-10-26,分支 picture-feedback)
|
||||||
|
- 需求来源:用户反馈处理时经常缺少截图,无法复现问题;现反馈弹窗只支持纯文本。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 意图与背景
|
||||||
|
|
||||||
|
意见反馈弹窗(`GeneralFeedbackDialog.vue`)目前只能提交文字(反馈类型/模块/内容/来源页),处理人拿到反馈后经常因为"没有截图、无法复现"反复找提交人确认。本次为反馈增加**截图附件**:用户在弹窗里可以**粘贴(Ctrl+V)**或**点击选图**添加截图,提交后图片随反馈入库;处理人在**管理端报表页**查看反馈时可以看到缩略图并点开大图。
|
||||||
|
|
||||||
|
处理人现有两个入口:企微群机器人通知(文字摘要)+ 后台报表完整记录。**已与需求方确认(方案 1)**:图片只在后台报表查看,企微通知保持纯文字。
|
||||||
|
|
||||||
|
## 2. 目标 / 非目标 / 反目标
|
||||||
|
|
||||||
|
**目标**
|
||||||
|
- 用户弹窗支持粘贴截图 + 点击选图,带缩略图预览与单张删除。
|
||||||
|
- 提交后图片与反馈记录关联,管理端报表「用户反馈」页签可见缩略图、可放大查看、可前后翻图。
|
||||||
|
- 有图时企微通知多一行「附图:N 张」(纯文字,不发图)。
|
||||||
|
- 反馈弹窗整页替换为 Element Plus 控件(需求方已拍板)。
|
||||||
|
|
||||||
|
**非目标(本期不做)**
|
||||||
|
- 企微群消息内嵌图片(企微机器人 markdown 不支持外链图,image 消息单张 ≤2MB,群里会刷屏)。
|
||||||
|
- 服务端图片压缩/旋转/加水印。
|
||||||
|
- 拖拽上传(粘贴 + 点选已覆盖需求)。
|
||||||
|
- gif/bmp 格式(平台文件资产白名单本就不含)。
|
||||||
|
- 提交后增删图片;反馈提交后即不可变。
|
||||||
|
- 关闭反馈时释放图片资产(图片随反馈长期保留)。
|
||||||
|
- 用户侧"我的反馈"回看页面(现网无此入口)。
|
||||||
|
- 管理端 ReportsPage 其余部分的 Element Plus 化(只加展示,不整页替换)。
|
||||||
|
|
||||||
|
**反目标(出现即算失败)**
|
||||||
|
- 破坏现有纯文本反馈的提交链路与 SSE 对话链路。
|
||||||
|
- 未引用图片滞留:孤儿图必须能被现有 72h 清理任务回收,不允许出现"永久滞留的临时资产"。
|
||||||
|
- 同一页面混用两套控件风格(仓库红线)。
|
||||||
|
|
||||||
|
## 3. 约束(来自 AGENTS.md / 现有设施)
|
||||||
|
|
||||||
|
1. **改表必须配套 Alembic 迁移**(当前单 head:`mh23e4f5a6b7`)。
|
||||||
|
2. **前端统一 Element Plus**:弹窗整页替换;管理端 ReportsPage 保持原样,只允许新增 `<img>` 缩略图与自建 overlay 预览(展示型,不新增表单控件)。
|
||||||
|
3. **HTTP 统一 `requestJson`(`@/shared/api/client`)**:弹窗现为裸 `fetch`,本次替换为 `requestJson`;失败以 `BusinessError` + `useMessage()` 展示。**后端接口响应契约保持现状**(`{status:'ok', id}`,唯一消费方就是本弹窗),不强行改 envelope,控制改动面。
|
||||||
|
4. **新增 error.code 同步四语言 `locales/*/errors.json`**。
|
||||||
|
5. **i18n 四语言**:新增文案补齐 zh-CN / zh-TW / en / th,禁止硬编码中文。
|
||||||
|
6. **不新增第三方依赖**:粘贴/上传/预览全部用现有依赖(原生 API + Element Plus + 现有 composables)。
|
||||||
|
7. **注释三层标准**(§5):文件层块注释 + 核心函数注释(含 AI 触发时机如有)+ `[STEP]` 分块。
|
||||||
|
8. **文档同步**:`docs/funclist.md` 与本设计文档随功能同一 PR 更新。
|
||||||
|
|
||||||
|
## 4. 已定决策
|
||||||
|
|
||||||
|
| # | 决策 | 来源 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| D1 | 图片只在管理端报表查看;企微通知纯文字,有图时加「附图:N 张」行 | 需求方(方案 1) |
|
||||||
|
| D2 | 反馈弹窗整页替换为 Element Plus | 需求方 |
|
||||||
|
| D3 | 选图/粘贴后**立即**上传(复用 `POST /api/files/assets` + `uploadFileAsset`),提交时 JSON 携带 `image_asset_nos[]`;取消弹窗的孤儿图交给现有 72h 清理,不新做回收 | 设计默认 |
|
||||||
|
| D4 | 限制:每条反馈最多 **5 张**,单张 **10MB**,格式 png/jpg/jpeg/webp;客户端校验 + **服务端扩展名二次校验**(平台资产白名单还含 pdf/doc 等文档类型,不能依赖) | 设计默认(可调) |
|
||||||
|
| D5 | 新子表 `general_feedback_images` 关联 feedback↔file_asset;`asset_id` 唯一约束(一张图只能挂一条反馈);提交时同事务调 `mark_asset_referenced` | 设计默认(照搬 `ShippingOrderIntake.asset_id` 模式) |
|
||||||
|
| D6 | 图片统一由**后端代理输出**:新增管理端 raw 接口流式返回图片字节,前端带鉴权头 fetch 取 blob 后 `URL.createObjectURL` 展示。**不走 MinIO 预签名 URL**——已核实:`presigned_get_url` 按 `MINIO_ENDPOINT` 签名(storage.py:32,123),`MINIO_PUBLIC_BASE_URL`(settings.py:674)全库无一处使用,生产 `MINIO_ENDPOINT=host.docker.internal:9000` 浏览器不可解析;且 SigV4 签名覆盖 Host,事后改写域名即失效 | 评审修订 |
|
||||||
|
| D7 | 大图预览:ReportsPage 内按该页现有自建 overlay 风格做轻量 lightbox(深色遮罩 + 大图 + 前后翻页);不复用 `FilePreviewModal`(其绑死 chat agent 取流) | 设计默认 |
|
||||||
|
| D8 | 提交接口 `POST /api/user/feedback` 响应契约不变,只扩展请求字段与校验 | 设计默认 |
|
||||||
|
| D9 | 仅允许挂载**全新未引用**资产:`reference_count == 0` 且 `lifecycle_status == 'temporary'`。防止把已投入其他业务(如货代接单)的资产挂到反馈上,污染其引用计数/生命周期 | 评审修订 |
|
||||||
|
| D10 | 缩略图以 `loading="lazy"` 按需加载原图,不做服务端缩略图生成;无图行零图片请求。列表默认 200 行,有图反馈占比低,可接受 | 评审确认 |
|
||||||
|
|
||||||
|
## 5. 方案详述
|
||||||
|
|
||||||
|
### 5.1 数据模型与迁移
|
||||||
|
|
||||||
|
新表 `general_feedback_images`:
|
||||||
|
|
||||||
|
| 列 | 类型 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| id | Integer PK | |
|
||||||
|
| feedback_id | FK `general_feedbacks.id`,NOT NULL,indexed | 级联删除随反馈 |
|
||||||
|
| asset_id | FK `file_assets.id`,NOT NULL,**unique** | 一图只挂一条反馈 |
|
||||||
|
| sort_order | Integer,NOT NULL,default 0 | 按添加顺序 |
|
||||||
|
| created_at | DateTime,default utcnow | |
|
||||||
|
|
||||||
|
模型 `GeneralFeedbackImage` 放在 `backend/app/models/chat.py`(`GeneralFeedback` 旁),并在 `GeneralFeedback` 上加 `images` 有序 relationship。Alembic 迁移基于单 head `mh23e4f5a6b7`。
|
||||||
|
|
||||||
|
### 5.2 上传链路(用户弹窗)
|
||||||
|
|
||||||
|
1. 交互:内容输入框下方新增图片条——缩略图(右上角 × 删除)+「添加图片」格子;提示文案"支持粘贴截图(Ctrl+V)或点击添加,最多 5 张"。
|
||||||
|
2. 粘贴:监听弹窗根节点 `paste` 事件,`clipboardData.items` 中 `type startsWith 'image/'` 的项转 `File`;仅当存在图片项时拦截默认行为。
|
||||||
|
3. 选图:隐藏 `<input type="file" multiple accept="image/png,image/jpeg,image/webp">` 由格子触发。
|
||||||
|
4. 客户端校验:格式(扩展名/ mime)、单张 ≤10MB、总数 ≤5(含上传中与已上传);超限给出 i18n 提示。
|
||||||
|
5. 校验通过立即 `uploadFileAsset(file)`(`frontend/src/shared/api/file-assets.api.ts`),格子显示上传中态;失败可重试或移除。
|
||||||
|
6. 弹窗内维护 `uploadedAssets: [{assetNo, filename, previewUrl?, ...}]`。**取消/关闭弹窗不回收资产**:未提交的图是 `temporary` 状态,72h 后被 `SCH-FILE-ASSET-CLEANUP` 每小时任务自动清理(见 `services/file_assets/cleanup.py`),本期不主动调 `release_asset_reference`。
|
||||||
|
7. 缩略图预览优先用 `URL.createObjectURL`,弹窗关闭时 revoke。
|
||||||
|
|
||||||
|
### 5.3 提交接口变更(后端)
|
||||||
|
|
||||||
|
`POST /api/user/feedback`(`backend/app/api/user/handlers.py:122-177` `submit_general_feedback`):
|
||||||
|
|
||||||
|
- 请求体新增可选 `image_asset_nos: string[]`(≤5 个,去重)。
|
||||||
|
- 校验(任一失败整单拒绝,400):每个 asset_no 存在、`owner_user_id == 当前用户`、`upload_status` 为已上传、`deleted_at IS NULL`、扩展名 ∈ {png, jpg, jpeg, webp}(服务端二次校验,见 D4)、`reference_count == 0` 且 `lifecycle_status == 'temporary'`(未被任何业务引用,见 D9;`asset_id` 唯一约束兜底并发双挂)。
|
||||||
|
- 同一事务:创建 `GeneralFeedback` → 批量创建 `GeneralFeedbackImage`(sort_order 按传入顺序)→ 对每个资产调 `mark_asset_referenced`(`services/file_assets/service.py:430`,reference_count+1、lifecycle='referenced'、清 expires_at)→ commit。
|
||||||
|
- 失败路径:校验失败不落任何数据;commit 异常整体回滚。
|
||||||
|
- 响应契约不变:`{status:'ok', id}`。
|
||||||
|
- 错误码走 `AppError` 子类,新增 `FEEDBACK.IMAGE_INVALID` 之类错误码并同步四语言 `errors.json`。
|
||||||
|
|
||||||
|
### 5.4 企微通知调整
|
||||||
|
|
||||||
|
`backend/app/services/feedback_notify.py` `build_feedback_markdown`:仅当 `feedback.images` 非空时,在「反馈内容」前插入一行 `>附图:N 张`(N 为图片数)。不发送图片本体,其余不变。
|
||||||
|
|
||||||
|
### 5.5 管理端列表与图片查看
|
||||||
|
|
||||||
|
**后端**(`backend/app/api/admin/reports.py` + `services/admin/report_service.py`):
|
||||||
|
|
||||||
|
- `list_general_feedbacks_report`(report_service.py:560-590)每行新增 `images: [{image_id, asset_no, original_filename, file_size, sort_order}]`(仅元数据,不含 URL)。
|
||||||
|
- 新接口 `GET /api/admin/reports/general-feedbacks/<feedback_id>/images/<image_id>/raw`:鉴权沿用该 blueprint 现有管理员校验;校验 image 属于该 feedback;`read_asset_bytes` 读字节后流式输出,`Content-Type` 取资产 mime,`Content-Disposition: inline`。前端以带鉴权头的 fetch 取 blob 再 `URL.createObjectURL` 展示(见 D6,不使用预签名 URL,`<img>` 无需自带鉴权头)。
|
||||||
|
|
||||||
|
**前端**(`frontend/src/features/admin/modules/reports/`):
|
||||||
|
|
||||||
|
- `useReportsAdmin.ts` `feedbackFixedOrder`(1070-1083)在 `content` 后插入 `images` 虚拟列;API 类型(`admin.api.ts:856` 附近)同步。
|
||||||
|
- `ReportsPage.vue`:`images` 列渲染缩略图(`<img loading="lazy">`,高约 40px,最多 5 张横向排列),无图显示 `-`,blob 加载失败显示占位。
|
||||||
|
- 点击缩略图打开本页内 lightbox overlay(参照 chat-logs 详情 overlay 的自建模式,ReportsPage.vue:1524-1543):深色遮罩 + 居中大图 + 左右翻页(在该反馈 images 内循环)+ 关闭;打开与翻页时按需 fetch blob,关闭/切换时 revoke 旧 objectURL。
|
||||||
|
- 不改动该页其余控件风格。
|
||||||
|
|
||||||
|
### 5.6 反馈弹窗 Element Plus 化
|
||||||
|
|
||||||
|
`frontend/src/shared/components/GeneralFeedbackDialog.vue` 整页重写:
|
||||||
|
|
||||||
|
- 控件:`el-dialog` + `el-radio-group`/`el-segmented`(反馈类型三选一)+ `el-select`(反馈模块)+ `el-input type="textarea"`(maxlength 2000, show-word-limit)+ `el-button`(取消/提交,提交 loading 态)。图片条可用 `el-upload` 的 list-type="picture-card" 思路或自绘缩略图条(允许:上传区不是表单校验控件;实现者按 EP 惯例选择,但**禁止**再引入 `btn-*`/`input-field` 等旧类)。
|
||||||
|
- 现有行为保持:类型/模块取值仍是**翻译后的展示文案**(后端按 ≤32 字符字符串存储,本次不改该契约);`source-page`、`chat_log_id`(chat 来源时)透传;成功/失败提示文案沿用 `feedback.*` i18n。
|
||||||
|
- 提交改走 `requestJson`(已核实其自动附带鉴权头),移除 `auth-headers` prop,同步更新挂载点:`features/workspace/components/WorkspaceModals.vue`、`features/chat/components/ChatViewOverlays.vue`、`features/workspace/pages/FeedbackPage.vue`。
|
||||||
|
- Element Plus 引入方式参照 `features/admin/modules/agents/AgentsPage.vue`(手动按需 import + `element-plus/dist/index.css`;注意弹窗挂在 workspace/chat 场景下的样式与暗色主题表现)。
|
||||||
|
- 上传/粘贴中禁用提交按钮,防止图片未传完就提交。
|
||||||
|
|
||||||
|
### 5.7 i18n
|
||||||
|
|
||||||
|
- `frontend/src/locales/{zh-CN,zh-TW,en,th}/feedback.json`:新增 `upload.*`(addImage、pasteHint、maxCount、maxSize、invalidType、uploadFailed、remove 等)。
|
||||||
|
- `frontend/src/locales/{...}/admin.json`:`admin.report.feedback.images`(附图列头)与预览相关文案。
|
||||||
|
- `frontend/src/locales/{...}/errors.json`:新增图片校验错误码。
|
||||||
|
|
||||||
|
### 5.8 测试
|
||||||
|
|
||||||
|
- 后端 pytest(新增,无既有反馈测试可依):
|
||||||
|
- 提交带 `image_asset_nos`:资产被引用(reference_count+1、lifecycle='referenced'、expires_at 清空),图片行 sort_order 正确;
|
||||||
|
- 拒绝场景:他人资产、不存在的 asset_no、超过 5 张、重复 asset_no;
|
||||||
|
- 管理端 raw 图片接口:管理员可取且 Content-Type 正确、image 与 feedback 不匹配 404、非管理员被拒;
|
||||||
|
- 拒绝非图片扩展名资产(如 pdf);
|
||||||
|
- 拒绝已被其他业务引用的资产(reference_count > 0);
|
||||||
|
- 报表行内含 `images` 元数据数组。
|
||||||
|
- 既有链路回归:纯文本提交不受影响。
|
||||||
|
- 前端:弹窗无既有 spec,本期不强制新增(可选)。
|
||||||
|
|
||||||
|
## 6. 现有代码坐标(调研结论)
|
||||||
|
|
||||||
|
| 事物 | 位置 |
|
||||||
|
| --- | --- |
|
||||||
|
| 反馈弹窗组件 | `frontend/src/shared/components/GeneralFeedbackDialog.vue`(裸 fetch 提交 98-105 行) |
|
||||||
|
| 弹窗挂载点 | `features/workspace/components/WorkspaceModals.vue:9,122-128`;`features/chat/components/ChatViewOverlays.vue:8,53-54`;状态 `useChatPageDialogs.ts:81`、`useWorkspaceNavigation.ts:63,92,198`;占位路由 `features/workspace/pages/FeedbackPage.vue` |
|
||||||
|
| 提交接口 | `backend/app/api/user/handlers.py:122-177`(校验 feedback_type/module ≤32、content ≤2000、chat_log_id 归属) |
|
||||||
|
| 反馈模型 | `backend/app/models/chat.py:117-140` `GeneralFeedback`(无任何附件字段) |
|
||||||
|
| 企微通知 | `backend/app/services/feedback_notify.py`(markdown 组装 :93,发送 :138,best-effort) |
|
||||||
|
| 管理端路由/服务 | `backend/app/api/admin/reports.py:90-132`;`backend/app/services/admin/report_service.py:560-590` |
|
||||||
|
| 管理端页面 | `frontend/src/features/admin/modules/reports/ReportsPage.vue`(内容 popover :1417-1441;chat-logs 自建 overlay :1524-1543);`composables/useReportsAdmin.ts`(列序 :1070-1083);API `features/admin/api/admin.api.ts:856,888-912` |
|
||||||
|
| 文件资产模型 | `backend/app/models/file_asset.py:22-70`(`owner_user_id`、`lifecycle_status` temporary/referenced/expired、`reference_count`、`expires_at`) |
|
||||||
|
| 文件资产服务 | `backend/app/services/file_assets/service.py`(白名单 :55-58 含 png/jpg/jpeg/webp;序列化 :102-116;**owner-only** :119-136;30MB 限制 :155-157;`mark_asset_referenced` :430;`release_asset_reference` :450);存储 `storage.py`(预签名下载) |
|
||||||
|
| 上传接口(复用) | `POST /api/files/assets`(`backend/app/api/files/assets.py:33-49`,multipart);前端 `frontend/src/shared/api/file-assets.api.ts:24-31` `uploadFileAsset` |
|
||||||
|
| 预签名 URL 风险(已核实) | `storage.py:32` MinIO 客户端以 `MINIO_ENDPOINT` 构建、`:123` `presigned_get_url` 按其签名;`MINIO_PUBLIC_BASE_URL`(settings.py:674)全库未被使用;生产 `MINIO_ENDPOINT=host.docker.internal:9000` 浏览器不可解析 → 反馈图片不走预签名(D6) |
|
||||||
|
| 孤儿清理 | `backend/app/services/file_assets/cleanup.py`(72h TTL,每小时 `SCH-FILE-ASSET-CLEANUP`) |
|
||||||
|
| 关联模式参照 | `backend/app/models/shipping.py:250` `ShippingOrderIntake.asset_id` FK→file_assets |
|
||||||
|
| Element Plus 引入范例 | `App.vue:11-15`(ElConfigProvider);`features/admin/modules/agents/AgentsPage.vue:21-23`(手动 import + css) |
|
||||||
|
| i18n 注册 | `frontend/src/locales/index.ts:45-48`(namespace `feedback`);四语言 `locales/*/feedback.json`、`admin.json`、`errors.json` |
|
||||||
|
| Alembic | 单 head `mh23e4f5a6b7`(385 个 revision) |
|
||||||
|
| 不复用项 | `shared/components/FilePreviewModal.vue`(取流绑死 chat agent,需 agentId) |
|
||||||
|
|
||||||
|
## 7. 留给实现者的开放点(builder's call)
|
||||||
|
|
||||||
|
1. Element Plus 样式引入位置(组件级 vs 全局)与暗色主题验证。
|
||||||
|
2. raw 接口流式响应细节(Content-Disposition 的 UTF-8 文件名编码、缓存头)按后端既有流式惯例实现。
|
||||||
|
3. 图片条实现选 `el-upload` picture-card 还是自绘缩略条(前提:不违反红线 2)。
|
||||||
|
4. 粘贴事件监听目标与输入法/占位符的边界行为。
|
||||||
|
5. 错误码具体命名(遵循 `errors.json` 既有风格)。
|
||||||
|
|
||||||
|
## 8. 验收标准
|
||||||
|
|
||||||
|
1. 弹窗内可粘贴截图与点击选图;实时缩略图、可删除;超 5 张 / 超 10MB / 格式不符有明确提示(四语言)。
|
||||||
|
2. 提交成功后,图片与反馈关联入库;资产 `lifecycle='referenced'`,不会被 72h 清理回收。
|
||||||
|
3. 管理端「用户反馈」页签可见附图缩略图,点开可大图查看并前后翻页;旧的无图反馈展示不受影响;缩略图懒加载,无图行不发起图片请求。
|
||||||
|
4. 有图反馈的企微通知多一行「附图:N 张」;无图反馈通知与现状完全一致。
|
||||||
|
5. 取消弹窗未提交的图片 72h 后被现有清理任务回收。
|
||||||
|
6. `flask db upgrade` 可从单 head 平滑迁移;`npm run build` 通过;后端 pytest 全绿;纯文本反馈回归无影响。
|
||||||
|
7. `docs/funclist.md` 已同步更新。
|
||||||
+1
-1
@@ -24,7 +24,7 @@
|
|||||||
|
|
||||||
## 设备验收预警(2026-10)
|
## 设备验收预警(2026-10)
|
||||||
|
|
||||||
- 已实现的同步只读 E10:`OA_E10_SQLSERVER_*`,验收单 `ecology10.dbo.ft_gdzcysdv2`,流程 `wfc_requestbase` / `wfc_currentnode` / `wfc_operate`,人员 `eteams.dbo.employee`。不回退 E8。本地快照按 `request_id` 唯一。每天 06:00 先同步再生成待发送,每周五 18:00 只发送。
|
- 已实现的同步只读 E10:`OA_E10_SQLSERVER_*`,验收单 `ecology10.dbo.ft_gdzcysdv2`,流程 `wfc_requestbase` / `wfc_currentnode` / `wfc_operate`,人员 `eteams.dbo.employee`。不回退 E8。本地快照按 `request_id` 唯一。每天 06:30 先同步再生成待发送,每周五 18:30 只发送(错开合同付款 06:00 / 18:00)。
|
||||||
- E8 补抓已接上。`OA_SQLSERVER_*` 读 `ecology`。与 E10 分来源保存。暂停 `currentstatus = 0` 按撤销停表。没有作废、强制结束。字段见 [features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。
|
- E8 补抓已接上。`OA_SQLSERVER_*` 读 `ecology`。与 E10 分来源保存。暂停 `currentstatus = 0` 按撤销停表。没有作废、强制结束。字段见 [features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。
|
||||||
|
|
||||||
## 货代发货通知 STP + 例外工作台(2026-07-29)
|
## 货代发货通知 STP + 例外工作台(2026-07-29)
|
||||||
|
|||||||
@@ -200,7 +200,7 @@ section.admin-table-section 一张圆角卡片,页面上只此一层
|
|||||||
| 用户管理 | 列表、筛选、三个业务弹窗、删除和改角色确认已按 §3、§4 对齐。筛选宽度和两列表单写在页面里。 |
|
| 用户管理 | 列表、筛选、三个业务弹窗、删除和改角色确认已按 §3、§4 对齐。筛选宽度和两列表单写在页面里。 |
|
||||||
| 知识库分组 | 列表骨架、行内链接按钮、删除确认、创建分组、Dify 设置和健康检查已对齐。 |
|
| 知识库分组 | 列表骨架、行内链接按钮、删除确认、创建分组、Dify 设置和健康检查已对齐。 |
|
||||||
| 应用配置 | 列表、状态标签、测试弹窗、授权弹窗、删除确认和 680px 创建/编辑表单内部已对齐。保存仍走原来的 `save` 事件。 |
|
| 应用配置 | 列表、状态标签、测试弹窗、授权弹窗、删除确认和 680px 创建/编辑表单内部已对齐。保存仍走原来的 `save` 事件。 |
|
||||||
| 部门管理 | 列表已用 `AdminListPage`。搜索、表头排序、行内链接、480px 表单、员工名单和删除确认已按 §3、§4 对齐。列表仍是本地过滤和排序,没有分页。 |
|
| 部门管理 | 已改为左树右成员面板的组织树页(非 AdminListPage 列表骨架,页面头注释有说明)。树行内链接按钮、成员 ElTable/ElPagination/ElTag、680px 表单(含上级部门/同级排序/隐藏标记)和 ElMessageBox 删除确认已按 §4 对齐;成员分页走服务端。 |
|
||||||
| 公告管理 | 列表已用 `AdminListPage`。发布/编辑是 680px 对话框,详情是描述列表,删除确认已对齐。 |
|
| 公告管理 | 列表已用 `AdminListPage`。发布/编辑是 680px 对话框,详情是描述列表,删除确认已对齐。 |
|
||||||
| 关联服务 | 列表已用 `AdminListPage`。启用用 `ElSwitch`,表单 480px,删除确认已对齐。 |
|
| 关联服务 | 列表已用 `AdminListPage`。启用用 `ElSwitch`,表单 480px,删除确认已对齐。 |
|
||||||
| 知识库分组 | 外层不再套第二张卡片,列表骨架改为 `AdminListPage`。 |
|
| 知识库分组 | 外层不再套第二张卡片,列表骨架改为 `AdminListPage`。 |
|
||||||
|
|||||||
@@ -584,10 +584,24 @@ export const updateAdminUserPermissions = (userId: number, agentIds: number[]) =
|
|||||||
body: JSON.stringify({ agent_ids: agentIds }),
|
body: JSON.stringify({ agent_ids: agentIds }),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Departments
|
// Departments(树形结构:/tree 返回 children 嵌套,成员支持含下级)
|
||||||
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
|
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
|
||||||
export const listAdminDepartmentMembers = (id: number) =>
|
export const listAdminDepartmentTree = () => requestJson<any[]>('/api/admin/departments/tree', auth());
|
||||||
requestJson(`/api/admin/departments/${id}/members`, auth());
|
export interface AdminDepartmentMembersQuery {
|
||||||
|
includeDescendants?: boolean;
|
||||||
|
keyword?: string;
|
||||||
|
page?: number;
|
||||||
|
pageSize?: number;
|
||||||
|
}
|
||||||
|
export const listAdminDepartmentMembers = (id: number, query: AdminDepartmentMembersQuery = {}) => {
|
||||||
|
const params = new URLSearchParams();
|
||||||
|
if (query.includeDescendants) params.set('include_descendants', '1');
|
||||||
|
if (query.keyword?.trim()) params.set('keyword', query.keyword.trim());
|
||||||
|
if (query.page && query.page > 1) params.set('page', String(query.page));
|
||||||
|
if (query.pageSize && query.pageSize !== 20) params.set('page_size', String(query.pageSize));
|
||||||
|
const qs = params.toString();
|
||||||
|
return requestJson(`/api/admin/departments/${id}/members${qs ? `?${qs}` : ''}`, auth());
|
||||||
|
};
|
||||||
export const createAdminDepartment = (payload: Record<string, unknown>) =>
|
export const createAdminDepartment = (payload: Record<string, unknown>) =>
|
||||||
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
|
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
|
||||||
@@ -912,6 +926,30 @@ export const closeAdminGeneralFeedback = (feedbackId: number) =>
|
|||||||
`/api/admin/reports/general-feedbacks/${feedbackId}/close`,
|
`/api/admin/reports/general-feedbacks/${feedbackId}/close`,
|
||||||
{ method: 'POST', ...auth() },
|
{ method: 'POST', ...auth() },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 意见反馈附图元数据(管理端报表行内嵌)。
|
||||||
|
* 图片二进制不走预签名 URL,统一经 `/images/<image_id>/raw` 代理接口(requestBlob 附鉴权头)拉取。
|
||||||
|
*/
|
||||||
|
export interface FeedbackReportImage {
|
||||||
|
image_id: number;
|
||||||
|
asset_no: string;
|
||||||
|
original_filename: string;
|
||||||
|
file_size: number;
|
||||||
|
sort_order: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 意见反馈报表行(general_feedbacks)。
|
||||||
|
* 说明:通用报表接口历史上一律以 any 行返回,无显式行类型;此处固化意见反馈行的关键字段供
|
||||||
|
* 前端(useReportsAdmin 附图预览等)按类型消费;`images` 为可选字段以兼容旧数据与无图行。
|
||||||
|
*/
|
||||||
|
export interface AdminGeneralFeedbackReportRow {
|
||||||
|
id: number;
|
||||||
|
status?: string;
|
||||||
|
[key: string]: unknown;
|
||||||
|
images?: FeedbackReportImage[];
|
||||||
|
}
|
||||||
export const batchDeleteAdminChatLogs = (ids: number[]) =>
|
export const batchDeleteAdminChatLogs = (ids: number[]) =>
|
||||||
requestJson<{ deleted_count: number }>('/api/admin/database/chat_logs/batch-delete', {
|
requestJson<{ deleted_count: number }>('/api/admin/database/chat_logs/batch-delete', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
@@ -1,219 +1,492 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/departments/DepartmentsPage.vue
|
* features/admin/modules/departments/DepartmentsPage.vue
|
||||||
* 用途:部门管理列表。一张卡片里放标题、添加按钮、搜索、表格。
|
* 用途:部门管理独立页面——左树(公司虚拟分组 + 部门层级)右成员面板(OA 组织结构口径)。
|
||||||
* 依赖:AdminListPage、useDepartmentsAdmin、element-plus、部门表单和员工名单弹窗。
|
* 依赖:useDepartmentsAdmin、DepartmentFormModal、element-plus、@element-plus/icons-vue。
|
||||||
* 逻辑:路由 /admin/departments。骨架用 AdminListPage。筛选、列和两个弹窗留在本页。
|
* 逻辑:路由 /admin/departments。左侧点击部门节点后,右侧按分页 + 关键词展示该部门成员
|
||||||
* 名称、编码、公司用表头排序,排的是当前过滤结果。删除用 Element 确认框。
|
* (含下级口径可切换);删除确认走 ElMessageBox。控件按 ELEMENT_MIGRATION.md 全量 Element 化,
|
||||||
* 表格用 Element stripe 斑马纹。员工数、编辑、删除用 Element 链接按钮,悬停文案走 i18n title。
|
* 树本身是自定义层级结构,不是 ElTable/ElTree 列表页,故不走 AdminListPage 骨架。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted, ref } from 'vue';
|
import { computed, onMounted } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { Delete, Edit, Plus, User } from '@element-plus/icons-vue';
|
import { ElButton, ElCheckbox, ElConfigProvider, ElEmpty, ElIcon, ElInput, ElLoading, ElPagination, ElTable, ElTableColumn, ElTag } from 'element-plus';
|
||||||
import {
|
import {
|
||||||
ElButton,
|
ArrowDown,
|
||||||
ElInput,
|
ArrowRight,
|
||||||
ElLoading,
|
Delete,
|
||||||
ElTable,
|
Edit,
|
||||||
ElTableColumn,
|
Expand,
|
||||||
} from 'element-plus';
|
Fold,
|
||||||
|
FolderAdd,
|
||||||
|
Hide,
|
||||||
|
OfficeBuilding,
|
||||||
|
Plus,
|
||||||
|
Search,
|
||||||
|
} from '@element-plus/icons-vue';
|
||||||
|
import DepartmentFormModal from './components/DepartmentFormModal.vue';
|
||||||
|
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
|
||||||
|
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||||
|
import type { AdminDepartmentTreeNode } from '@/features/admin/types/admin.types';
|
||||||
import 'element-plus/dist/index.css';
|
import 'element-plus/dist/index.css';
|
||||||
import 'element-plus/theme-chalk/dark/css-vars.css';
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
import '@/features/admin/styles/element-trial.css';
|
import '@/features/admin/styles/element-trial.css';
|
||||||
import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
|
||||||
import type { AdminDepartmentMembersResponse, AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
|
||||||
import DepartmentFormModal from './components/DepartmentFormModal.vue';
|
|
||||||
import DepartmentMembersModal from './components/DepartmentMembersModal.vue';
|
|
||||||
import { useDepartmentsAdmin, type DeptSortKey } from './composables/useDepartmentsAdmin';
|
|
||||||
import { listAdminDepartmentMembers } from '@/features/admin/api/admin.api';
|
|
||||||
import { useMessage } from '@/shared/composables/useMessage';
|
|
||||||
|
|
||||||
const vLoading = ElLoading.directive;
|
const vLoading = ElLoading.directive;
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t, te } = useI18n();
|
||||||
const msg = useMessage();
|
const { elementLocale } = useElementProvider();
|
||||||
const showMembersModal = ref(false);
|
|
||||||
const departmentMembers = ref<AdminDepartmentMembersResponse | null>(null);
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
filteredDepartments,
|
displayRows,
|
||||||
|
parentOptions,
|
||||||
form,
|
form,
|
||||||
searchQuery,
|
searchQuery,
|
||||||
sortKey,
|
|
||||||
sortDir,
|
|
||||||
isLoading,
|
isLoading,
|
||||||
isListLoading,
|
|
||||||
isSaving,
|
isSaving,
|
||||||
showFormModal,
|
showFormModal,
|
||||||
loadAll,
|
loadAll,
|
||||||
applySort,
|
toggleNode,
|
||||||
|
toggleCompany,
|
||||||
|
expandAll,
|
||||||
|
collapseAll,
|
||||||
openCreateModal,
|
openCreateModal,
|
||||||
openEditModal,
|
openEditModal,
|
||||||
closeFormModal,
|
closeFormModal,
|
||||||
saveDepartment,
|
saveDepartment,
|
||||||
deleteDepartment,
|
deleteDepartment,
|
||||||
|
selectedDeptId,
|
||||||
|
selectedDept,
|
||||||
|
selectedDeptPath,
|
||||||
|
memberData,
|
||||||
|
memberLoading,
|
||||||
|
memberKeyword,
|
||||||
|
memberIncludeDescendants,
|
||||||
|
memberPage,
|
||||||
|
memberPageSize,
|
||||||
|
selectDept,
|
||||||
|
setMemberKeyword,
|
||||||
|
setMemberIncludeDescendants,
|
||||||
|
setMemberPage,
|
||||||
|
setMemberPageSize,
|
||||||
} = useDepartmentsAdmin();
|
} = useDepartmentsAdmin();
|
||||||
|
|
||||||
const defaultSort = computed(() => ({
|
/** 成员面板总页数(由 total / page_size 推导)。 */
|
||||||
prop: sortKey.value || 'name',
|
const memberTotalPages = computed(() => {
|
||||||
order: sortDir.value === 'desc' ? 'descending' as const : 'ascending' as const,
|
const data = memberData.value;
|
||||||
}));
|
if (!data || data.page_size <= 0) return 1;
|
||||||
|
return Math.max(1, Math.ceil(data.total / data.page_size));
|
||||||
|
});
|
||||||
|
|
||||||
const emptyText = computed(() => (
|
/** 左树空状态文案:搜索无结果或尚无部门。 */
|
||||||
|
const treeEmptyText = computed(() => (
|
||||||
searchQuery.value.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts')
|
searchQuery.value.trim() ? t('admin.dept.noSearchResults') : t('admin.dept.noDepts')
|
||||||
));
|
));
|
||||||
|
|
||||||
/**
|
/** 成员状态 → 本地化标签;未知状态回退显示原值。 */
|
||||||
* 把 Element 表头排序交给本地列表。
|
const statusLabel = (status?: string): string => {
|
||||||
* 核心逻辑:只接受名称、编码、公司;第三次点击 order 为空时清空排序。
|
if (!status) return '-';
|
||||||
* @param payload.prop - 列字段
|
const key = `admin.dept.members.status.${status}`;
|
||||||
* @param payload.order - ascending、descending 或空
|
return te(key) ? t(key) : status;
|
||||||
*/
|
};
|
||||||
function onSortChange(payload: { prop: string | null; order: string | null }): void {
|
|
||||||
const field = payload.prop;
|
|
||||||
const sortable = field === 'name' || field === 'code' || field === 'company';
|
|
||||||
if (sortable && payload.order) {
|
|
||||||
applySort(field as DeptSortKey, payload.order === 'descending' ? 'desc' : 'asc');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
applySort('', '');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/** 成员状态 → ElTag 类型:启用 success,待审核 warning,其余 info。 */
|
||||||
* 打开编辑弹窗。表格插槽行类型较宽,这里收成部门行。
|
const statusTagType = (status?: string): 'success' | 'warning' | 'info' => {
|
||||||
* @param row - 当前表格行
|
if (status === 'active') return 'success';
|
||||||
*/
|
if (status === 'pending') return 'warning';
|
||||||
function editDepartment(row: AdminDepartmentRow): void {
|
return 'info';
|
||||||
openEditModal(row);
|
};
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/** 公司虚拟分组行 key 去前缀,得到分组 key(用于展开状态)。 */
|
||||||
* 加载并展示指定部门的员工名单。
|
const companyGroupKey = (rowKey: string): string => rowKey.slice('company:'.length);
|
||||||
* 核心逻辑:请求成功才打开弹窗;失败只提示,不打开空名单。
|
|
||||||
* @param departmentId - 部门主键
|
|
||||||
*/
|
|
||||||
async function openDepartmentMembers(departmentId: number): Promise<void> {
|
|
||||||
try {
|
|
||||||
departmentMembers.value = await listAdminDepartmentMembers(departmentId) as AdminDepartmentMembersResponse;
|
|
||||||
showMembersModal.value = true;
|
|
||||||
} catch (error) {
|
|
||||||
msg.error((error as Error).message || t('admin.msg.requestFailed'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
|
// 【版本标记】用于核对浏览器加载的是否为本版代码;确认后可移除
|
||||||
|
console.info('[departments] UI build v8 (2026-10-30): 树列贴合内容/成员表580定宽居中/默认展开第一层/两栏独立滚动');
|
||||||
void loadAll();
|
void loadAll();
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<AdminListPage :loading="isLoading">
|
<ElConfigProvider :locale="elementLocale">
|
||||||
<template #title>
|
<!-- 高度/布局写内联样式:外层内容列不再出现整页滚动条,滚动只发生在左右两栏各自内部 -->
|
||||||
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
|
<section
|
||||||
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
|
class="admin-table-section admin-dept-page"
|
||||||
</template>
|
style="height: 100%; min-height: 0; display: flex; flex-direction: column; overflow: hidden;"
|
||||||
<template #actions>
|
>
|
||||||
<ElButton type="primary" :icon="Plus" @click="openCreateModal">
|
<header class="admin-table-header admin-table-header--stacked">
|
||||||
|
<div>
|
||||||
|
<h2 class="section-title">{{ t('admin.dept.title') }}</h2>
|
||||||
|
<p class="section-desc mt-1">{{ t('admin.dept.subtitle') }}</p>
|
||||||
|
</div>
|
||||||
|
<ElButton type="primary" :icon="Plus" @click="openCreateModal()">
|
||||||
{{ t('admin.dept.add') }}
|
{{ t('admin.dept.add') }}
|
||||||
</ElButton>
|
</ElButton>
|
||||||
</template>
|
</header>
|
||||||
<template #filters>
|
|
||||||
|
<!-- 筛选条:左树搜索 + 展开/收起,一条分隔线与内容区分开 -->
|
||||||
|
<div class="admin-dept-filter">
|
||||||
<ElInput
|
<ElInput
|
||||||
v-model="searchQuery"
|
v-model="searchQuery"
|
||||||
|
class="admin-dept-filter__search"
|
||||||
|
:prefix-icon="Search"
|
||||||
clearable
|
clearable
|
||||||
class="dept-filter-search"
|
|
||||||
:placeholder="t('admin.dept.searchPlaceholder')"
|
:placeholder="t('admin.dept.searchPlaceholder')"
|
||||||
/>
|
/>
|
||||||
</template>
|
<ElButton text :icon="Expand" :title="t('admin.dept.expandAll')" @click="expandAll" />
|
||||||
|
<ElButton text :icon="Fold" :title="t('admin.dept.collapseAll')" @click="collapseAll" />
|
||||||
|
</div>
|
||||||
|
|
||||||
<ElTable
|
<div v-loading="isLoading" class="admin-dept-body" style="flex: 1; min-height: 0; display: flex; align-items: stretch; overflow-x: auto;">
|
||||||
v-loading="isListLoading"
|
<!-- 左侧:组织树(公司虚拟分组 + 层级缩进);定宽写在 style 上,避免 HMR 样式层滞后导致宽度不生效 -->
|
||||||
class="hx-admin-table"
|
<div class="admin-dept-tree" style="width: max-content; min-width: 260px; max-width: 45%; flex-shrink: 0;">
|
||||||
:data="filteredDepartments"
|
<ElEmpty v-if="displayRows.length === 0" :description="treeEmptyText" :image-size="80" />
|
||||||
row-key="id"
|
<template v-for="row in displayRows" :key="row.key">
|
||||||
stripe
|
<!-- 公司虚拟分组行(不入库,前端按 company 字段归堆) -->
|
||||||
:default-sort="defaultSort"
|
<div
|
||||||
:empty-text="emptyText"
|
v-if="row.kind === 'company'"
|
||||||
@sort-change="onSortChange"
|
class="admin-dept-tree__row admin-dept-tree__row--company"
|
||||||
>
|
@click="toggleCompany(companyGroupKey(row.key))"
|
||||||
<ElTableColumn prop="name" :label="t('admin.dept.headers.name')" sortable="custom" min-width="200">
|
|
||||||
<template #default="{ row }">
|
|
||||||
<div :title="row.name">{{ row.name }}</div>
|
|
||||||
<p v-if="row.description" class="hx-element-hint dept-desc" :title="row.description">
|
|
||||||
{{ row.description }}
|
|
||||||
</p>
|
|
||||||
</template>
|
|
||||||
</ElTableColumn>
|
|
||||||
<ElTableColumn prop="code" :label="t('admin.dept.headers.code')" sortable="custom" min-width="140">
|
|
||||||
<template #default="{ row }">{{ row.code || '-' }}</template>
|
|
||||||
</ElTableColumn>
|
|
||||||
<ElTableColumn prop="company" :label="t('admin.dept.headers.company')" sortable="custom" min-width="180">
|
|
||||||
<template #default="{ row }">{{ row.company || '-' }}</template>
|
|
||||||
</ElTableColumn>
|
|
||||||
<ElTableColumn :label="t('admin.dept.headers.members')" width="120" align="center">
|
|
||||||
<template #default="{ row }">
|
|
||||||
<ElButton
|
|
||||||
link
|
|
||||||
type="primary"
|
|
||||||
:icon="User"
|
|
||||||
:title="t('admin.dept.actions.viewMembers')"
|
|
||||||
@click="openDepartmentMembers((row as AdminDepartmentRow).id)"
|
|
||||||
>
|
>
|
||||||
{{ row.member_count || 0 }}
|
<ElIcon class="admin-dept-tree__chevron">
|
||||||
</ElButton>
|
<component :is="row.expanded ? ArrowDown : ArrowRight" />
|
||||||
</template>
|
</ElIcon>
|
||||||
</ElTableColumn>
|
<ElIcon class="admin-dept-tree__company-icon"><OfficeBuilding /></ElIcon>
|
||||||
<ElTableColumn :label="t('admin.dept.headers.actions')" width="120" align="right">
|
<span class="admin-dept-tree__name" :title="row.company">{{ row.company }}</span>
|
||||||
<template #default="{ row }">
|
|
||||||
<div class="dept-row-actions">
|
|
||||||
<ElButton
|
<ElButton
|
||||||
link
|
link
|
||||||
type="primary"
|
type="primary"
|
||||||
:icon="Edit"
|
:icon="FolderAdd"
|
||||||
:title="t('admin.dept.actions.edit')"
|
:title="t('admin.dept.addChild')"
|
||||||
@click="editDepartment(row as AdminDepartmentRow)"
|
@click.stop="openCreateModal(null, row.company)"
|
||||||
/>
|
|
||||||
<ElButton
|
|
||||||
link
|
|
||||||
type="danger"
|
|
||||||
:icon="Delete"
|
|
||||||
:title="t('admin.dept.actions.delete')"
|
|
||||||
@click="deleteDepartment((row as AdminDepartmentRow).id)"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 部门行(层级缩进;点击选中 → 右侧出成员面板) -->
|
||||||
|
<div
|
||||||
|
v-else
|
||||||
|
class="admin-dept-tree__row"
|
||||||
|
:class="{ 'is-selected': selectedDeptId === row.node!.id }"
|
||||||
|
:style="{ paddingLeft: `${(row.depth - 1) * 16 + 4}px` }"
|
||||||
|
@click="selectDept(row.node!)"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
v-if="row.hasChildren"
|
||||||
|
type="button"
|
||||||
|
class="admin-dept-tree__toggle"
|
||||||
|
:title="row.expanded ? t('admin.dept.collapse') : t('admin.dept.expand')"
|
||||||
|
@click.stop="toggleNode(row.node!.id)"
|
||||||
|
>
|
||||||
|
<ElIcon>
|
||||||
|
<component :is="row.expanded ? ArrowDown : ArrowRight" />
|
||||||
|
</ElIcon>
|
||||||
|
</button>
|
||||||
|
<span v-else class="admin-dept-tree__toggle" />
|
||||||
|
<span class="admin-dept-tree__name" :title="row.node!.name">{{ row.node!.name }}</span>
|
||||||
|
<ElTag
|
||||||
|
v-if="row.node!.is_hidden"
|
||||||
|
type="warning"
|
||||||
|
effect="light"
|
||||||
|
size="small"
|
||||||
|
:icon="Hide"
|
||||||
|
:title="t('admin.dept.fields.hiddenHint')"
|
||||||
|
>
|
||||||
|
{{ t('admin.dept.tags.hidden') }}
|
||||||
|
</ElTag>
|
||||||
|
<span class="admin-dept-tree__spacer" />
|
||||||
|
<span class="admin-dept-tree__actions" @click.stop>
|
||||||
|
<ElButton
|
||||||
|
link
|
||||||
|
type="primary"
|
||||||
|
:icon="FolderAdd"
|
||||||
|
:title="t('admin.dept.addChild')"
|
||||||
|
@click="openCreateModal(row.node as AdminDepartmentTreeNode)"
|
||||||
|
/>
|
||||||
|
<ElButton
|
||||||
|
link
|
||||||
|
type="primary"
|
||||||
|
:icon="Edit"
|
||||||
|
:title="t('admin.dept.actions.edit')"
|
||||||
|
@click="openEditModal(row.node!)"
|
||||||
|
/>
|
||||||
|
<ElButton
|
||||||
|
link
|
||||||
|
type="danger"
|
||||||
|
:icon="Delete"
|
||||||
|
:title="t('admin.dept.actions.delete')"
|
||||||
|
@click="deleteDepartment(row.node!.id)"
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
</ElTableColumn>
|
</div>
|
||||||
</ElTable>
|
|
||||||
</AdminListPage>
|
<!-- 右侧:选中部门的成员面板(OA 口径) -->
|
||||||
|
<div class="admin-dept-members" style="flex: 1; min-width: 280px; min-height: 0; display: flex; flex-direction: column;">
|
||||||
|
<template v-if="!selectedDept">
|
||||||
|
<ElEmpty class="admin-dept-members__empty" :description="t('admin.dept.members.hint')" :image-size="80" />
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<header class="admin-dept-members__header">
|
||||||
|
<div class="admin-dept-members__title">
|
||||||
|
<h3>{{ selectedDept.name }}</h3>
|
||||||
|
<p :title="selectedDeptPath.join(' / ')">{{ selectedDeptPath.join(' / ') }}</p>
|
||||||
|
</div>
|
||||||
|
<ElCheckbox
|
||||||
|
:model-value="memberIncludeDescendants"
|
||||||
|
@change="setMemberIncludeDescendants($event as boolean)"
|
||||||
|
>
|
||||||
|
{{ t('admin.dept.members.includeDescendants') }}
|
||||||
|
</ElCheckbox>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="admin-dept-members__toolbar">
|
||||||
|
<ElInput
|
||||||
|
:model-value="memberKeyword"
|
||||||
|
class="admin-dept-members__search"
|
||||||
|
:prefix-icon="Search"
|
||||||
|
clearable
|
||||||
|
:placeholder="t('admin.dept.members.searchPlaceholder')"
|
||||||
|
@input="setMemberKeyword(String($event))"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-loading="memberLoading" class="admin-dept-members__tablewrap" style="flex: 1 1 0; min-height: 0; width: 600px; max-width: 100%; margin-inline: auto;">
|
||||||
|
<ElTable
|
||||||
|
:data="memberData?.members ?? []"
|
||||||
|
row-key="id"
|
||||||
|
stripe
|
||||||
|
height="100%"
|
||||||
|
:empty-text="t('admin.dept.members.empty')"
|
||||||
|
>
|
||||||
|
<ElTableColumn :label="t('admin.dept.members.columns.name')" width="170">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div class="admin-dept-member__name">{{ row.real_name || row.username }}</div>
|
||||||
|
<div class="admin-dept-member__sub">{{ row.username }}</div>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.dept.members.columns.contact')" width="150" show-overflow-tooltip>
|
||||||
|
<template #default="{ row }">{{ row.phone_number || row.email || '-' }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn prop="employee_id" :label="t('admin.dept.members.columns.employeeId')" width="90" show-overflow-tooltip />
|
||||||
|
<ElTableColumn prop="department" :label="t('admin.dept.members.columns.department')" width="110" show-overflow-tooltip />
|
||||||
|
<ElTableColumn :label="t('admin.dept.members.columns.status')" width="80">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<ElTag :type="statusTagType(row.status)" effect="light" size="small">
|
||||||
|
{{ statusLabel(row.status) }}
|
||||||
|
</ElTag>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
</ElTable>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer v-if="memberData" class="admin-dept-members__footer" style="width: 600px; max-width: 100%; margin-inline: auto; display: flex; align-items: center; justify-content: flex-end; flex-wrap: wrap; row-gap: 8px; gap: 12px; padding: 12px 0; border-top: 1px solid var(--el-border-color-lighter);">
|
||||||
|
<ElPagination
|
||||||
|
background
|
||||||
|
layout="total, sizes, prev, pager, next"
|
||||||
|
:total="memberData.total"
|
||||||
|
:current-page="memberPage"
|
||||||
|
:page-size="memberPageSize"
|
||||||
|
:page-sizes="[20, 50, 100]"
|
||||||
|
@current-change="setMemberPage"
|
||||||
|
@size-change="setMemberPageSize"
|
||||||
|
/>
|
||||||
|
<span class="admin-dept-members__pages">{{ memberPage }} / {{ memberTotalPages }}</span>
|
||||||
|
</footer>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<DepartmentFormModal
|
<DepartmentFormModal
|
||||||
:visible="showFormModal"
|
:visible="showFormModal"
|
||||||
:form="form"
|
:form="form"
|
||||||
|
:parent-options="parentOptions"
|
||||||
:is-saving="isSaving"
|
:is-saving="isSaving"
|
||||||
@close="closeFormModal"
|
@close="closeFormModal"
|
||||||
@save="saveDepartment"
|
@save="saveDepartment"
|
||||||
/>
|
/>
|
||||||
<DepartmentMembersModal
|
</ElConfigProvider>
|
||||||
:visible="showMembersModal"
|
|
||||||
:data="departmentMembers"
|
|
||||||
@close="showMembersModal = false"
|
|
||||||
/>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
:deep(.dept-filter-search) {
|
/* 页内布局(非 Element 控件内部),间距对齐迁移规范:筛选条、面板分隔、分页右侧 */
|
||||||
|
/* AdminLayout 内容列高度确定(h-dvh 壳内 flex-1 min-h-0),本页卡片填满后左右两栏各自滚动 */
|
||||||
|
.admin-dept-page {
|
||||||
|
height: 100%;
|
||||||
|
min-height: 24rem;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.admin-dept-filter {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 12px 32px;
|
||||||
|
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||||
|
}
|
||||||
|
.admin-dept-filter__search {
|
||||||
width: 16rem;
|
width: 16rem;
|
||||||
}
|
}
|
||||||
|
.admin-dept-body {
|
||||||
.dept-desc {
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
display: flex;
|
||||||
|
align-items: stretch;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
.admin-dept-tree {
|
||||||
|
width: max-content;
|
||||||
|
min-width: 260px;
|
||||||
|
max-width: 45%;
|
||||||
|
flex-shrink: 0;
|
||||||
|
padding: 12px 8px 12px 24px;
|
||||||
|
border-right: 1px solid var(--el-border-color-lighter);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
.admin-dept-tree__row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 6px 4px;
|
||||||
|
border-radius: var(--el-border-radius-base);
|
||||||
|
cursor: pointer;
|
||||||
|
user-select: none;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.admin-dept-tree__row:hover {
|
||||||
|
background: var(--el-fill-color-light);
|
||||||
|
}
|
||||||
|
.admin-dept-tree__row--company {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.admin-dept-tree__row.is-selected {
|
||||||
|
background: var(--el-color-primary-light-9);
|
||||||
|
}
|
||||||
|
.admin-dept-tree__row.is-selected .admin-dept-tree__name {
|
||||||
|
color: var(--el-color-primary);
|
||||||
|
}
|
||||||
|
.admin-dept-tree__chevron,
|
||||||
|
.admin-dept-tree__toggle {
|
||||||
|
flex-shrink: 0;
|
||||||
|
width: 20px;
|
||||||
|
display: inline-flex;
|
||||||
|
justify-content: center;
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.admin-dept-tree__company-icon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
color: var(--el-color-primary);
|
||||||
|
}
|
||||||
|
.admin-dept-tree__name {
|
||||||
|
font-size: var(--el-font-size-base);
|
||||||
|
color: var(--el-text-color-primary);
|
||||||
|
white-space: nowrap;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
text-overflow: ellipsis;
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
.admin-dept-tree__spacer {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
.admin-dept-tree__actions {
|
||||||
|
display: none;
|
||||||
|
align-items: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.admin-dept-tree__row:hover .admin-dept-tree__actions {
|
||||||
|
display: inline-flex;
|
||||||
|
}
|
||||||
|
.admin-dept-members {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 280px;
|
||||||
|
min-height: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.admin-dept-members__empty {
|
||||||
|
flex: 1;
|
||||||
|
margin: auto;
|
||||||
|
}
|
||||||
|
.admin-dept-members__header {
|
||||||
|
/* width 由 .admin-dept-members 统一定宽 */
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
padding: 16px 24px 8px;
|
||||||
|
}
|
||||||
|
.admin-dept-members__title {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.admin-dept-members__title h3 {
|
||||||
|
font-size: var(--el-font-size-large);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--el-text-color-primary);
|
||||||
|
margin: 0;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
.admin-dept-members__title p {
|
||||||
|
font-size: var(--el-font-size-small);
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
margin: 2px 0 0;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
.admin-dept-members__toolbar {
|
||||||
|
padding: 8px 24px 12px;
|
||||||
|
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||||
|
}
|
||||||
|
.admin-dept-members__search {
|
||||||
|
width: 16rem;
|
||||||
|
}
|
||||||
|
.admin-dept-members__tablewrap {
|
||||||
|
/* 宽度须与上方五列 width 之和(170+150+90+110+80=600)保持一致;居中使剩余空白均匀分两侧 */
|
||||||
|
width: 600px;
|
||||||
|
max-width: 100%;
|
||||||
|
margin-inline: auto;
|
||||||
|
}
|
||||||
|
.admin-dept-members__footer {
|
||||||
|
/* 与表格同宽并同样居中,分页对齐表格右缘 */
|
||||||
|
width: 600px;
|
||||||
|
max-width: 100%;
|
||||||
|
margin-inline: auto;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: flex-end;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
row-gap: 8px;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 12px 0;
|
||||||
|
border-top: 1px solid var(--el-border-color-lighter);
|
||||||
|
}
|
||||||
|
.admin-dept-members__pages {
|
||||||
|
font-size: var(--el-font-size-small);
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
.admin-dept-member__name {
|
||||||
.dept-row-actions {
|
color: var(--el-text-color-primary);
|
||||||
display: inline-flex;
|
}
|
||||||
justify-content: flex-end;
|
.admin-dept-member__sub {
|
||||||
gap: 4px;
|
font-size: var(--el-font-size-extra-small);
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
@media (max-width: 1023px) {
|
||||||
|
.admin-dept-body {
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
.admin-dept-tree {
|
||||||
|
max-height: 40vh;
|
||||||
|
}
|
||||||
|
.admin-dept-members {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
+91
-13
@@ -1,17 +1,20 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/departments/components/DepartmentFormModal.vue
|
* features/admin/modules/departments/components/DepartmentFormModal.vue
|
||||||
* 用途:部门创建和编辑对话框。四个字段,单列。
|
* 用途:部门创建/编辑对话框(上级部门选择、同级排序、隐藏标记)。
|
||||||
* 依赖:element-plus 对话框和表单、DepartmentFormState。
|
* 依赖:element-plus 对话框和表单、DepartmentFormState、DeptParentOption。
|
||||||
* 逻辑:DepartmentsPage 打开本组件。提交时 emit save,由 useDepartmentsAdmin 调接口。样式跟页面已引入的 Element 皮肤走。
|
* 逻辑:DepartmentsPage 打开本组件。上级选项由父级传入(编辑时已排除自身及子孙,防成环);
|
||||||
|
* 公司未填时由后端继承上级部门;提交时 emit save,由 useDepartmentsAdmin 调接口。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput } from 'element-plus';
|
import { ElButton, ElCol, ElDialog, ElForm, ElFormItem, ElInput, ElInputNumber, ElOption, ElRow, ElSelect, ElSwitch } from 'element-plus';
|
||||||
import type { DepartmentFormState } from '@/features/admin/types/department.types';
|
import type { DepartmentFormState } from '@/features/admin/types/department.types';
|
||||||
|
import type { DeptParentOption } from '../composables/useDepartmentsAdmin';
|
||||||
|
|
||||||
defineProps<{
|
const props = defineProps<{
|
||||||
visible: boolean;
|
visible: boolean;
|
||||||
form: DepartmentFormState;
|
form: DepartmentFormState;
|
||||||
|
parentOptions: DeptParentOption[];
|
||||||
isSaving: boolean;
|
isSaving: boolean;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
@@ -22,6 +25,14 @@ const emit = defineEmits<{
|
|||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 上级部门下拉回写:ElSelect 不接受 null 类型,空值在此统一为 null(顶级部门)。
|
||||||
|
* @param value - 下拉选中的值
|
||||||
|
*/
|
||||||
|
function onParentChange(value: unknown): void {
|
||||||
|
props.form.parentId = (value ?? null) as number | null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 对话框关闭时通知页面收起并重置表单。
|
* 对话框关闭时通知页面收起并重置表单。
|
||||||
* @param open - Element 对话框的打开状态
|
* @param open - Element 对话框的打开状态
|
||||||
@@ -35,7 +46,7 @@ function onVisibleChange(open: boolean): void {
|
|||||||
<ElDialog
|
<ElDialog
|
||||||
:model-value="visible"
|
:model-value="visible"
|
||||||
:title="form.id ? t('admin.dept.edit') : t('admin.dept.add')"
|
:title="form.id ? t('admin.dept.edit') : t('admin.dept.add')"
|
||||||
width="480px"
|
width="680px"
|
||||||
align-center
|
align-center
|
||||||
append-to-body
|
append-to-body
|
||||||
:close-on-click-modal="false"
|
:close-on-click-modal="false"
|
||||||
@@ -44,15 +55,54 @@ function onVisibleChange(open: boolean): void {
|
|||||||
@update:model-value="onVisibleChange"
|
@update:model-value="onVisibleChange"
|
||||||
>
|
>
|
||||||
<ElForm label-position="top" :model="form" @submit.prevent="emit('save')">
|
<ElForm label-position="top" :model="form" @submit.prevent="emit('save')">
|
||||||
|
<ElFormItem :label="t('admin.dept.fields.parent')">
|
||||||
|
<!-- 运行时以 null 表示顶级部门(有对应选项),modelValue 的类型限制此处用 as any 放行 -->
|
||||||
|
<ElSelect :model-value="(form.parentId ?? null) as any" filterable @update:model-value="onParentChange">
|
||||||
|
<ElOption
|
||||||
|
v-for="option in parentOptions"
|
||||||
|
:key="String(option.id)"
|
||||||
|
:label="option.label"
|
||||||
|
:value="option.id as number"
|
||||||
|
:disabled="option.disabled"
|
||||||
|
/>
|
||||||
|
</ElSelect>
|
||||||
|
</ElFormItem>
|
||||||
<ElFormItem :label="t('admin.dept.fields.name')" required>
|
<ElFormItem :label="t('admin.dept.fields.name')" required>
|
||||||
<ElInput v-model="form.name" :placeholder="t('admin.dept.fields.namePlaceholder')" />
|
<ElInput v-model="form.name" :placeholder="t('admin.dept.fields.namePlaceholder')" />
|
||||||
</ElFormItem>
|
</ElFormItem>
|
||||||
<ElFormItem :label="t('admin.dept.fields.code')">
|
<ElRow>
|
||||||
<ElInput v-model="form.code" :placeholder="t('admin.dept.fields.codePlaceholder')" />
|
<ElCol :span="12" class="admin-dept-form__col">
|
||||||
</ElFormItem>
|
<ElFormItem :label="t('admin.dept.fields.code')">
|
||||||
<ElFormItem :label="t('admin.dept.fields.company')">
|
<ElInput v-model="form.code" :placeholder="t('admin.dept.fields.codePlaceholder')" />
|
||||||
<ElInput v-model="form.company" :placeholder="t('admin.dept.fields.companyPlaceholder')" />
|
</ElFormItem>
|
||||||
</ElFormItem>
|
</ElCol>
|
||||||
|
<ElCol :span="12" class="admin-dept-form__col">
|
||||||
|
<ElFormItem :label="t('admin.dept.fields.company')">
|
||||||
|
<ElInput v-model="form.company" :placeholder="t('admin.dept.fields.companyPlaceholder')" />
|
||||||
|
</ElFormItem>
|
||||||
|
</ElCol>
|
||||||
|
</ElRow>
|
||||||
|
<ElRow>
|
||||||
|
<ElCol :span="12" class="admin-dept-form__col">
|
||||||
|
<ElFormItem :label="t('admin.dept.fields.sort')">
|
||||||
|
<ElInputNumber
|
||||||
|
:model-value="form.sortOrder ?? 0"
|
||||||
|
:min="0"
|
||||||
|
class="admin-dept-form__number"
|
||||||
|
@update:model-value="form.sortOrder = $event ?? 0"
|
||||||
|
/>
|
||||||
|
</ElFormItem>
|
||||||
|
</ElCol>
|
||||||
|
<ElCol :span="12" class="admin-dept-form__col">
|
||||||
|
<ElFormItem :label="t('admin.dept.fields.visibility')">
|
||||||
|
<div class="admin-dept-form__switch">
|
||||||
|
<ElSwitch v-model="form.isHidden" />
|
||||||
|
<span class="admin-dept-form__switch-label">{{ t('admin.dept.fields.hidden') }}</span>
|
||||||
|
</div>
|
||||||
|
<p class="admin-dept-form__hint">{{ t('admin.dept.fields.hiddenHint') }}</p>
|
||||||
|
</ElFormItem>
|
||||||
|
</ElCol>
|
||||||
|
</ElRow>
|
||||||
<ElFormItem :label="t('admin.dept.fields.description')">
|
<ElFormItem :label="t('admin.dept.fields.description')">
|
||||||
<ElInput
|
<ElInput
|
||||||
v-model="form.description"
|
v-model="form.description"
|
||||||
@@ -70,3 +120,31 @@ function onVisibleChange(open: boolean): void {
|
|||||||
</template>
|
</template>
|
||||||
</ElDialog>
|
</ElDialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.admin-dept-form__col {
|
||||||
|
padding-right: 16px;
|
||||||
|
}
|
||||||
|
.admin-dept-form__col:last-child {
|
||||||
|
padding-right: 0;
|
||||||
|
}
|
||||||
|
.admin-dept-form__number {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
.admin-dept-form__switch {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding-top: 4px;
|
||||||
|
}
|
||||||
|
.admin-dept-form__switch-label {
|
||||||
|
font-size: var(--el-font-size-base);
|
||||||
|
color: var(--el-text-color-regular);
|
||||||
|
}
|
||||||
|
.admin-dept-form__hint {
|
||||||
|
font-size: var(--el-font-size-extra-small);
|
||||||
|
color: var(--el-text-color-secondary);
|
||||||
|
margin: 4px 0 0;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
/**
|
|
||||||
* features/admin/modules/departments/components/DepartmentMembersModal.vue
|
|
||||||
* 用途:只读展示某个部门的员工数量和名单。
|
|
||||||
* 依赖:element-plus 对话框和表格、部门成员响应类型。
|
|
||||||
* 逻辑:DepartmentsPage 拉到名单后传入。本组件不请求接口,只展示和关闭。
|
|
||||||
*/
|
|
||||||
<script setup lang="ts">
|
|
||||||
import { useI18n } from 'vue-i18n';
|
|
||||||
import { ElButton, ElDialog, ElTable, ElTableColumn } from 'element-plus';
|
|
||||||
import type { AdminDepartmentMembersResponse } from '@/features/admin/types/admin.types';
|
|
||||||
|
|
||||||
defineProps<{
|
|
||||||
visible: boolean;
|
|
||||||
data: AdminDepartmentMembersResponse | null;
|
|
||||||
}>();
|
|
||||||
|
|
||||||
const emit = defineEmits<{ close: [] }>();
|
|
||||||
const { t } = useI18n();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 对话框关闭时通知页面收起。
|
|
||||||
* @param open - Element 对话框的打开状态
|
|
||||||
*/
|
|
||||||
function onVisibleChange(open: boolean): void {
|
|
||||||
if (!open) emit('close');
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
|
||||||
<ElDialog
|
|
||||||
:model-value="visible && !!data"
|
|
||||||
:title="data ? t('admin.dept.members.title', { name: data.department.name }) : ''"
|
|
||||||
width="680px"
|
|
||||||
align-center
|
|
||||||
append-to-body
|
|
||||||
:close-on-click-modal="false"
|
|
||||||
@update:model-value="onVisibleChange"
|
|
||||||
>
|
|
||||||
<template v-if="data">
|
|
||||||
<p class="section-desc">{{ t('admin.dept.members.count', { count: data.count }) }}</p>
|
|
||||||
<ElTable
|
|
||||||
class="dept-members-table"
|
|
||||||
:data="data.members"
|
|
||||||
row-key="id"
|
|
||||||
max-height="60vh"
|
|
||||||
:empty-text="t('admin.dept.members.empty')"
|
|
||||||
>
|
|
||||||
<ElTableColumn :label="t('admin.user.fields.realName')" min-width="140">
|
|
||||||
<template #default="{ row }">{{ row.real_name || row.username }}</template>
|
|
||||||
</ElTableColumn>
|
|
||||||
<ElTableColumn :label="t('admin.user.fields.employeeId')" min-width="120">
|
|
||||||
<template #default="{ row }">{{ row.employee_id || '-' }}</template>
|
|
||||||
</ElTableColumn>
|
|
||||||
<ElTableColumn :label="t('admin.user.fields.email')" min-width="180">
|
|
||||||
<template #default="{ row }">{{ row.email || '-' }}</template>
|
|
||||||
</ElTableColumn>
|
|
||||||
<ElTableColumn :label="t('admin.user.headers.status')" min-width="100">
|
|
||||||
<template #default="{ row }">{{ row.status || '-' }}</template>
|
|
||||||
</ElTableColumn>
|
|
||||||
</ElTable>
|
|
||||||
</template>
|
|
||||||
<template #footer>
|
|
||||||
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
|
|
||||||
</template>
|
|
||||||
</ElDialog>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.dept-members-table {
|
|
||||||
margin-top: 16px;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
+353
-77
@@ -1,8 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
|
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
|
||||||
* 用途:部门管理列表、搜索过滤、列排序、创建/编辑弹窗、删除。
|
* 用途:部门树加载、公司虚拟分组、展开/收起、搜索过滤、创建/编辑/删除。
|
||||||
* 依赖:admin.api、department.types、useMessage、useTableSort、element-plus 的确认框。
|
* 依赖:admin.api、department.types、useMessage、element-plus 的确认框。
|
||||||
* 逻辑:DepartmentsPage 调用本 composable。表头排序由页面把 Element 的 sort-change 交给 applySort,仍在本地对过滤后的列表排序。删除用 ElMessageBox,不再使用 DeleteConfirmDialog。
|
* 逻辑:DepartmentsPage 调用本 composable;数据来自 /admin/departments/tree(children 已按同级排序号排好);
|
||||||
|
* 公司层不入库,按顶级部门的 company 字段在前端虚拟分组;删除用 ElMessageBox,不再使用 DeleteConfirmDialog。
|
||||||
*/
|
*/
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
@@ -10,84 +11,310 @@ import { ElMessageBox } from 'element-plus';
|
|||||||
import {
|
import {
|
||||||
createAdminDepartment,
|
createAdminDepartment,
|
||||||
deleteAdminDepartment,
|
deleteAdminDepartment,
|
||||||
listAdminDepartments,
|
listAdminDepartmentMembers,
|
||||||
|
listAdminDepartmentTree,
|
||||||
updateAdminDepartment,
|
updateAdminDepartment,
|
||||||
} from '@/features/admin/api/admin.api';
|
} from '@/features/admin/api/admin.api';
|
||||||
import { useMessage } from '@/shared/composables/useMessage';
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
import { useTableSort } from '@/shared/composables/useTableSort';
|
import type {
|
||||||
import type { SortDir } from '@/shared/utils/table-sort';
|
AdminDepartmentMembersResponse,
|
||||||
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
|
AdminDepartmentTreeNode,
|
||||||
|
} from '@/features/admin/types/admin.types';
|
||||||
import {
|
import {
|
||||||
createEmptyDepartmentForm,
|
createEmptyDepartmentForm,
|
||||||
departmentRowToForm,
|
departmentRowToForm,
|
||||||
type DepartmentFormState,
|
type DepartmentFormState,
|
||||||
} from '@/features/admin/types/department.types';
|
} from '@/features/admin/types/department.types';
|
||||||
|
|
||||||
/** 部门表可排序列 */
|
/** 表单弹窗「上级部门」下拉选项(编辑时排除自身及子孙,防成环) */
|
||||||
export type DeptSortKey = 'name' | 'code' | 'company';
|
export interface DeptParentOption {
|
||||||
|
id: number | null;
|
||||||
|
label: string;
|
||||||
|
disabled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 树表展开后的一行:company 为公司虚拟分组行,dept 为部门行 */
|
||||||
|
export interface DeptTreeDisplayRow {
|
||||||
|
kind: 'company' | 'dept';
|
||||||
|
key: string;
|
||||||
|
/** 缩进层级:公司组为 0,顶级部门为 1,逐层 +1 */
|
||||||
|
depth: number;
|
||||||
|
company?: string;
|
||||||
|
/** dept 行对应的部门节点 */
|
||||||
|
node?: AdminDepartmentTreeNode;
|
||||||
|
expanded: boolean;
|
||||||
|
hasChildren: boolean;
|
||||||
|
/** 含下级递归汇总的成员数 */
|
||||||
|
totalMembers: number;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 部门管理页的列表、表单和删除状态。
|
|
||||||
* 核心逻辑:拉全量部门后在本地过滤和排序,保存与删除成功后再拉一次列表。
|
|
||||||
* @returns 页面绑定的状态和打开弹窗、排序、保存、删除方法
|
|
||||||
*/
|
|
||||||
export function useDepartmentsAdmin() {
|
export function useDepartmentsAdmin() {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const msg = useMessage();
|
const msg = useMessage();
|
||||||
|
|
||||||
const departments = ref<AdminDepartmentRow[]>([]);
|
const tree = ref<AdminDepartmentTreeNode[]>([]);
|
||||||
const form = ref<DepartmentFormState>(createEmptyDepartmentForm());
|
const form = ref<DepartmentFormState>(createEmptyDepartmentForm());
|
||||||
const searchQuery = ref('');
|
const searchQuery = ref('');
|
||||||
const { sortKey, sortDir, sortItems } = useTableSort<DeptSortKey>({
|
|
||||||
initialKey: 'name',
|
|
||||||
initialDir: 'asc',
|
|
||||||
});
|
|
||||||
const isLoading = ref(true);
|
const isLoading = ref(true);
|
||||||
const isListLoading = ref(false);
|
|
||||||
const isSaving = ref(false);
|
const isSaving = ref(false);
|
||||||
const showFormModal = ref(false);
|
const showFormModal = ref(false);
|
||||||
|
|
||||||
/**
|
/** 展开状态:部门节点 id 集合 / 公司分组 key 集合 */
|
||||||
* 先按关键词过滤,再按当前排序列排序。
|
const expandedIds = ref<Set<number>>(new Set());
|
||||||
* 核心逻辑:模糊匹配四字段 → useTableSort.sortItems。
|
const expandedCompanies = ref<Set<string>>(new Set());
|
||||||
*/
|
|
||||||
const filteredDepartments = computed(() => {
|
|
||||||
const q = searchQuery.value.trim().toLowerCase();
|
|
||||||
const filtered = q
|
|
||||||
? departments.value.filter((d) => {
|
|
||||||
const haystack = [d.name, d.code, d.company, d.description]
|
|
||||||
.filter(Boolean)
|
|
||||||
.join(' ')
|
|
||||||
.toLowerCase();
|
|
||||||
return haystack.includes(q);
|
|
||||||
})
|
|
||||||
: departments.value;
|
|
||||||
|
|
||||||
return sortItems(
|
|
||||||
filtered,
|
|
||||||
(row, key) => row[key],
|
|
||||||
(a, b) => a.id - b.id,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 拉取部门列表并写入 departments。
|
* 拉取部门树并写入 tree。
|
||||||
* @returns Promise<void>
|
* @returns Promise<void>
|
||||||
*/
|
*/
|
||||||
|
/** 是否已做过首屏默认展开(只做一次,之后尊重用户的展开/收起操作) */
|
||||||
|
let expandSeeded = false;
|
||||||
|
|
||||||
const loadDepartments = async (): Promise<void> => {
|
const loadDepartments = async (): Promise<void> => {
|
||||||
isListLoading.value = true;
|
|
||||||
try {
|
try {
|
||||||
departments.value = await listAdminDepartments();
|
tree.value = (await listAdminDepartmentTree()) as AdminDepartmentTreeNode[];
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Failed to load departments', e);
|
console.error('Failed to load department tree', e);
|
||||||
departments.value = [];
|
tree.value = [];
|
||||||
} finally {
|
}
|
||||||
isListLoading.value = false;
|
// 首屏默认展开公司组与第一层部门:树内容填满栏高(对齐 OA 展开到第一级的习惯)
|
||||||
|
if (!expandSeeded && tree.value.length) {
|
||||||
|
expandSeeded = true;
|
||||||
|
expandedCompanies.value = new Set(tree.value.map((r) => r.company?.trim() || ''));
|
||||||
|
expandedIds.value = new Set(tree.value.map((r) => r.id));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 页面初始化:加载部门列表并结束 loading。
|
* 按关键词过滤树:命中节点及其祖先保留;搜索态下全部自动展开。
|
||||||
|
* 核心逻辑:递归 filterTree → 命中自身或子孙的节点保留。
|
||||||
|
*/
|
||||||
|
const displayRows = computed<DeptTreeDisplayRow[]>(() => {
|
||||||
|
const q = searchQuery.value.trim().toLowerCase();
|
||||||
|
|
||||||
|
const filterTree = (nodes: AdminDepartmentTreeNode[]): AdminDepartmentTreeNode[] => {
|
||||||
|
const out: AdminDepartmentTreeNode[] = [];
|
||||||
|
for (const n of nodes) {
|
||||||
|
const children = filterTree(n.children || []);
|
||||||
|
const haystack = [n.name, n.code, n.company, n.description]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(' ')
|
||||||
|
.toLowerCase();
|
||||||
|
if (!q || haystack.includes(q) || children.length) {
|
||||||
|
out.push({ ...n, children });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
const activeTree = q ? filterTree(tree.value) : tree.value;
|
||||||
|
const rows: DeptTreeDisplayRow[] = [];
|
||||||
|
|
||||||
|
/** 递归铺开部门行;搜索态全展开,常态按 expandedIds */
|
||||||
|
const appendDeptRows = (nodes: AdminDepartmentTreeNode[], depth: number): void => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
const children = n.children || [];
|
||||||
|
const expanded = q ? true : expandedIds.value.has(n.id);
|
||||||
|
rows.push({
|
||||||
|
kind: 'dept',
|
||||||
|
key: `dept:${n.id}`,
|
||||||
|
depth,
|
||||||
|
node: n,
|
||||||
|
expanded,
|
||||||
|
hasChildren: children.length > 0,
|
||||||
|
totalMembers: n.total_member_count || 0,
|
||||||
|
company: n.company,
|
||||||
|
});
|
||||||
|
if (expanded && children.length) appendDeptRows(children, depth + 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 树顶公司虚拟分组:顶级部门按 company 文本归堆(未填公司归入「未分配公司」)
|
||||||
|
const groups = new Map<string, AdminDepartmentTreeNode[]>();
|
||||||
|
for (const root of activeTree) {
|
||||||
|
const key = root.company?.trim() || '';
|
||||||
|
if (!groups.has(key)) groups.set(key, []);
|
||||||
|
groups.get(key)!.push(root);
|
||||||
|
}
|
||||||
|
const groupKeys = [...groups.keys()].sort((a, b) => a.localeCompare(b, 'zh-Hans-CN'));
|
||||||
|
for (const key of groupKeys) {
|
||||||
|
const roots = groups.get(key)!;
|
||||||
|
const companyOpen = q ? true : expandedCompanies.value.has(key);
|
||||||
|
rows.push({
|
||||||
|
kind: 'company',
|
||||||
|
key: `company:${key}`,
|
||||||
|
depth: 0,
|
||||||
|
company: key || t('admin.dept.noCompany'),
|
||||||
|
expanded: companyOpen,
|
||||||
|
hasChildren: true,
|
||||||
|
totalMembers: roots.reduce((sum, r) => sum + (r.total_member_count || 0), 0),
|
||||||
|
});
|
||||||
|
if (companyOpen) appendDeptRows(roots, 1);
|
||||||
|
}
|
||||||
|
return rows;
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 在树中按 id 查找节点。 */
|
||||||
|
const findNode = (
|
||||||
|
nodes: AdminDepartmentTreeNode[],
|
||||||
|
id: number,
|
||||||
|
): AdminDepartmentTreeNode | null => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
if (n.id === id) return n;
|
||||||
|
const hit = findNode(n.children || [], id);
|
||||||
|
if (hit) return hit;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 在树中查找 id 的祖先路径(含自身,不含公司虚拟层)。 */
|
||||||
|
const findPath = (nodes: AdminDepartmentTreeNode[], id: number, trail: AdminDepartmentTreeNode[] = []): AdminDepartmentTreeNode[] | null => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
const next = [...trail, n];
|
||||||
|
if (n.id === id) return next;
|
||||||
|
const hit = findPath(n.children || [], id, next);
|
||||||
|
if (hit) return hit;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------- 右侧成员面板(OA 组织结构口径:点部门出成员列表) ----------
|
||||||
|
const selectedDeptId = ref<number | null>(null);
|
||||||
|
const memberData = ref<AdminDepartmentMembersResponse | null>(null);
|
||||||
|
const memberLoading = ref(false);
|
||||||
|
const memberKeyword = ref('');
|
||||||
|
const memberIncludeDescendants = ref(true);
|
||||||
|
const memberPage = ref(1);
|
||||||
|
const memberPageSize = ref(20);
|
||||||
|
// 竞态保护:仅采纳最后一次请求的结果(切部门/翻页/搜索连击时旧响应作废)
|
||||||
|
let memberRequestSeq = 0;
|
||||||
|
let memberKeywordTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
const MEMBER_KEYWORD_DEBOUNCE_MS = 300;
|
||||||
|
|
||||||
|
const selectedDept = computed<AdminDepartmentTreeNode | null>(() =>
|
||||||
|
selectedDeptId.value ? findNode(tree.value, selectedDeptId.value) : null,
|
||||||
|
);
|
||||||
|
|
||||||
|
/** 选中部门的祖先路径(面包屑:公司分组名 → … → 本部门)。 */
|
||||||
|
const selectedDeptPath = computed<string[]>(() => {
|
||||||
|
if (!selectedDeptId.value) return [];
|
||||||
|
const path = findPath(tree.value, selectedDeptId.value) || [];
|
||||||
|
const rootCompany = path[0]?.company?.trim() || t('admin.dept.noCompany');
|
||||||
|
return [rootCompany, ...path.map((n) => n.name)];
|
||||||
|
});
|
||||||
|
|
||||||
|
/** 拉取当前选中部门的分页成员名单。 */
|
||||||
|
const fetchMembers = async (): Promise<void> => {
|
||||||
|
if (!selectedDeptId.value) {
|
||||||
|
memberData.value = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const seq = ++memberRequestSeq;
|
||||||
|
memberLoading.value = true;
|
||||||
|
try {
|
||||||
|
const data = (await listAdminDepartmentMembers(selectedDeptId.value, {
|
||||||
|
includeDescendants: memberIncludeDescendants.value,
|
||||||
|
keyword: memberKeyword.value,
|
||||||
|
page: memberPage.value,
|
||||||
|
pageSize: memberPageSize.value,
|
||||||
|
})) as AdminDepartmentMembersResponse;
|
||||||
|
if (seq === memberRequestSeq) memberData.value = data;
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to load department members', e);
|
||||||
|
if (seq === memberRequestSeq) {
|
||||||
|
memberData.value = null;
|
||||||
|
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (seq === memberRequestSeq) memberLoading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 选中树节点:右侧面板加载该部门成员。
|
||||||
|
* @param node - 被点击的部门节点
|
||||||
|
*/
|
||||||
|
const selectDept = (node: AdminDepartmentTreeNode): void => {
|
||||||
|
if (selectedDeptId.value === node.id) return;
|
||||||
|
selectedDeptId.value = node.id;
|
||||||
|
memberKeyword.value = '';
|
||||||
|
memberPage.value = 1;
|
||||||
|
void fetchMembers();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 成员关键词输入(300ms 防抖后回到第 1 页重新查询)。 */
|
||||||
|
const setMemberKeyword = (value: string): void => {
|
||||||
|
memberKeyword.value = value;
|
||||||
|
if (memberKeywordTimer) clearTimeout(memberKeywordTimer);
|
||||||
|
memberKeywordTimer = setTimeout(() => {
|
||||||
|
memberKeywordTimer = null;
|
||||||
|
memberPage.value = 1;
|
||||||
|
void fetchMembers();
|
||||||
|
}, MEMBER_KEYWORD_DEBOUNCE_MS);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 切换「含下级部门」口径:回到第 1 页重新查询。 */
|
||||||
|
const setMemberIncludeDescendants = (value: boolean): void => {
|
||||||
|
memberIncludeDescendants.value = value;
|
||||||
|
memberPage.value = 1;
|
||||||
|
void fetchMembers();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 翻页 / 调整每页条数。 */
|
||||||
|
const setMemberPage = (page: number): void => {
|
||||||
|
memberPage.value = Math.max(page, 1);
|
||||||
|
void fetchMembers();
|
||||||
|
};
|
||||||
|
const setMemberPageSize = (size: number): void => {
|
||||||
|
memberPageSize.value = size;
|
||||||
|
memberPage.value = 1;
|
||||||
|
void fetchMembers();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 选中部门被删除或树刷新后,校正成员面板状态。 */
|
||||||
|
const syncMemberPanelAfterTreeReload = (deletedId?: number): void => {
|
||||||
|
if (deletedId != null && deletedId === selectedDeptId.value) {
|
||||||
|
selectedDeptId.value = null;
|
||||||
|
memberData.value = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (selectedDeptId.value) void fetchMembers();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 表单弹窗「上级部门」选项:编辑时排除自身及子孙,避免把子树挂到自己下面 */
|
||||||
|
const parentOptions = computed<DeptParentOption[]>(() => {
|
||||||
|
const options: DeptParentOption[] = [
|
||||||
|
{ id: null, label: t('admin.dept.fields.parentRoot'), disabled: false },
|
||||||
|
];
|
||||||
|
const exclude = new Set<number>();
|
||||||
|
if (form.value.id) {
|
||||||
|
const stack: number[] = [form.value.id];
|
||||||
|
const target = findNode(tree.value, form.value.id);
|
||||||
|
const collect = (nodes: AdminDepartmentTreeNode[]): void => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
stack.push(n.id);
|
||||||
|
collect(n.children || []);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if (target) collect(target.children || []);
|
||||||
|
while (stack.length) exclude.add(stack.pop()!);
|
||||||
|
}
|
||||||
|
const walk = (nodes: AdminDepartmentTreeNode[], depth: number): void => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
options.push({
|
||||||
|
id: n.id,
|
||||||
|
label: `${' '.repeat(depth)}${n.name}`,
|
||||||
|
disabled: exclude.has(n.id),
|
||||||
|
});
|
||||||
|
walk(n.children || [], depth + 1);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(tree.value, 0);
|
||||||
|
return options;
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 页面初始化:加载部门树并结束 loading。
|
||||||
* @returns Promise<void>
|
* @returns Promise<void>
|
||||||
*/
|
*/
|
||||||
const loadAll = async (): Promise<void> => {
|
const loadAll = async (): Promise<void> => {
|
||||||
@@ -96,32 +323,59 @@ export function useDepartmentsAdmin() {
|
|||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/** 切换部门节点展开/收起。 */
|
||||||
* 把 Element 表头排序写回本地排序状态。
|
const toggleNode = (id: number): void => {
|
||||||
* 核心逻辑:第三次点击清空排序时回到接口原顺序;有效列只排当前过滤结果,不请求接口。
|
const next = new Set(expandedIds.value);
|
||||||
* @param key - 名称、编码、公司;空字符串表示取消排序
|
if (next.has(id)) next.delete(id);
|
||||||
* @param dir - asc、desc,或空
|
else next.add(id);
|
||||||
*/
|
expandedIds.value = next;
|
||||||
const applySort = (key: DeptSortKey | '', dir: SortDir | ''): void => {
|
|
||||||
if (key === '' || dir === '') {
|
|
||||||
sortKey.value = undefined;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sortKey.value = key;
|
|
||||||
sortDir.value = dir;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 打开「添加部门」弹窗并重置表单。 */
|
/** 切换公司虚拟分组展开/收起。 */
|
||||||
const openCreateModal = (): void => {
|
const toggleCompany = (key: string): void => {
|
||||||
|
const next = new Set(expandedCompanies.value);
|
||||||
|
if (next.has(key)) next.delete(key);
|
||||||
|
else next.add(key);
|
||||||
|
expandedCompanies.value = next;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 全部展开(含所有公司组与部门节点)。 */
|
||||||
|
const expandAll = (): void => {
|
||||||
|
const ids = new Set<number>();
|
||||||
|
const walk = (nodes: AdminDepartmentTreeNode[]): void => {
|
||||||
|
for (const n of nodes) {
|
||||||
|
ids.add(n.id);
|
||||||
|
walk(n.children || []);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(tree.value);
|
||||||
|
expandedIds.value = ids;
|
||||||
|
expandedCompanies.value = new Set(tree.value.map((r) => r.company?.trim() || ''));
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 全部收起(仅保留公司组层)。 */
|
||||||
|
const collapseAll = (): void => {
|
||||||
|
expandedIds.value = new Set();
|
||||||
|
expandedCompanies.value = new Set();
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开「添加部门」弹窗。
|
||||||
|
* @param parent - 上级部门节点(添加子部门时传入);空 = 顶级
|
||||||
|
* @param company - 预填公司(公司虚拟分组行的「添加子部门」传入)
|
||||||
|
*/
|
||||||
|
const openCreateModal = (parent?: AdminDepartmentTreeNode | null, company?: string): void => {
|
||||||
form.value = createEmptyDepartmentForm();
|
form.value = createEmptyDepartmentForm();
|
||||||
|
form.value.parentId = parent ? parent.id : null;
|
||||||
|
form.value.company = company ?? parent?.company ?? '';
|
||||||
showFormModal.value = true;
|
showFormModal.value = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 打开「编辑部门」弹窗并回填选中行数据。
|
* 打开「编辑部门」弹窗并回填选中行数据。
|
||||||
* @param dept - 待编辑的部门行
|
* @param dept - 待编辑的部门树节点
|
||||||
*/
|
*/
|
||||||
const openEditModal = (dept: AdminDepartmentRow): void => {
|
const openEditModal = (dept: AdminDepartmentTreeNode): void => {
|
||||||
form.value = departmentRowToForm(dept);
|
form.value = departmentRowToForm(dept);
|
||||||
showFormModal.value = true;
|
showFormModal.value = true;
|
||||||
};
|
};
|
||||||
@@ -134,7 +388,8 @@ export function useDepartmentsAdmin() {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 保存部门:有 id 则更新,否则新建。
|
* 保存部门:有 id 则更新,否则新建。
|
||||||
* 核心逻辑:校验名称 → 调 create/update API → 刷新列表并关闭弹窗。
|
* 核心逻辑:校验名称 → 组装含 parent_id/sort_order/is_hidden 的载荷 → 调 API → 刷新树并关闭弹窗。
|
||||||
|
* 后端负责同级查重、防成环等校验,失败抛 BusinessError(errors.json 四语言文案)。
|
||||||
* @returns Promise<void>
|
* @returns Promise<void>
|
||||||
*/
|
*/
|
||||||
const saveDepartment = async (): Promise<void> => {
|
const saveDepartment = async (): Promise<void> => {
|
||||||
@@ -149,6 +404,9 @@ export function useDepartmentsAdmin() {
|
|||||||
code: form.value.code?.trim() || '',
|
code: form.value.code?.trim() || '',
|
||||||
company: form.value.company?.trim() || '',
|
company: form.value.company?.trim() || '',
|
||||||
description: form.value.description?.trim() || '',
|
description: form.value.description?.trim() || '',
|
||||||
|
parent_id: form.value.parentId ?? null,
|
||||||
|
sort_order: form.value.sortOrder ?? 0,
|
||||||
|
is_hidden: !!form.value.isHidden,
|
||||||
};
|
};
|
||||||
if (form.value.id) {
|
if (form.value.id) {
|
||||||
await updateAdminDepartment(form.value.id, payload);
|
await updateAdminDepartment(form.value.id, payload);
|
||||||
@@ -157,6 +415,7 @@ export function useDepartmentsAdmin() {
|
|||||||
}
|
}
|
||||||
closeFormModal();
|
closeFormModal();
|
||||||
await loadDepartments();
|
await loadDepartments();
|
||||||
|
syncMemberPanelAfterTreeReload();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
msg.error((e as Error).message || t('admin.msg.failed'));
|
msg.error((e as Error).message || t('admin.msg.failed'));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -165,8 +424,8 @@ export function useDepartmentsAdmin() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 删除指定部门。先用 Element 确认框询问,取消则不请求。
|
* 删除指定部门:ElMessageBox 确认后调接口。
|
||||||
* 核心逻辑:MessageBox 在取消时 reject,这里吞掉;确定后再调删除接口并刷新列表。
|
* 有下级部门或名下仍有员工时后端返回 409(HAS_CHILDREN / HAS_MEMBERS),此处展示其文案。
|
||||||
* @param id - 部门主键
|
* @param id - 部门主键
|
||||||
*/
|
*/
|
||||||
const deleteDepartment = async (id: number): Promise<void> => {
|
const deleteDepartment = async (id: number): Promise<void> => {
|
||||||
@@ -182,6 +441,7 @@ export function useDepartmentsAdmin() {
|
|||||||
try {
|
try {
|
||||||
await deleteAdminDepartment(id);
|
await deleteAdminDepartment(id);
|
||||||
await loadDepartments();
|
await loadDepartments();
|
||||||
|
syncMemberPanelAfterTreeReload(id);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
msg.error((e as Error).message || t('admin.msg.requestFailed'));
|
||||||
@@ -189,22 +449,38 @@ export function useDepartmentsAdmin() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
departments,
|
tree,
|
||||||
filteredDepartments,
|
displayRows,
|
||||||
|
parentOptions,
|
||||||
form,
|
form,
|
||||||
searchQuery,
|
searchQuery,
|
||||||
sortKey,
|
|
||||||
sortDir,
|
|
||||||
isLoading,
|
isLoading,
|
||||||
isListLoading,
|
|
||||||
isSaving,
|
isSaving,
|
||||||
showFormModal,
|
showFormModal,
|
||||||
loadAll,
|
loadAll,
|
||||||
applySort,
|
toggleNode,
|
||||||
|
toggleCompany,
|
||||||
|
expandAll,
|
||||||
|
collapseAll,
|
||||||
openCreateModal,
|
openCreateModal,
|
||||||
openEditModal,
|
openEditModal,
|
||||||
closeFormModal,
|
closeFormModal,
|
||||||
saveDepartment,
|
saveDepartment,
|
||||||
deleteDepartment,
|
deleteDepartment,
|
||||||
|
// 成员面板(OA 口径:左树右成员列表)
|
||||||
|
selectedDeptId,
|
||||||
|
selectedDept,
|
||||||
|
selectedDeptPath,
|
||||||
|
memberData,
|
||||||
|
memberLoading,
|
||||||
|
memberKeyword,
|
||||||
|
memberIncludeDescendants,
|
||||||
|
memberPage,
|
||||||
|
memberPageSize,
|
||||||
|
selectDept,
|
||||||
|
setMemberKeyword,
|
||||||
|
setMemberIncludeDescendants,
|
||||||
|
setMemberPage,
|
||||||
|
setMemberPageSize,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+22
-7
@@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* features/admin/modules/permissions/components/RoleMembersConfirmDialog.vue
|
* features/admin/modules/permissions/components/RoleMembersConfirmDialog.vue
|
||||||
* 用途:选人确定后展示将改入/移出的人及来源角色,确认才写库。
|
* 用途:选人确定后展示将加入/移出本角色的人,以及仍保留的其他角色。确认才写库。
|
||||||
* 依赖:permissionRole.types、vue-i18n、element-plus 对话框。
|
* 依赖:permissionRole.types、vue-i18n、element-plus 对话框。
|
||||||
* 逻辑:PermissionsPage 在 UserPickerDialog 之后打开;取消不改变成员。样式跟权限页已引入的 Element 皮肤走。
|
* 逻辑:PermissionsPage 在 UserPickerDialog 之后打开;取消不改变成员。样式跟权限页已引入的 Element 皮肤走。
|
||||||
*/
|
*/
|
||||||
@@ -24,22 +24,36 @@ const emit = defineEmits<{
|
|||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 把人员和来源角色拼成一行。
|
* 把人员和仍保留的角色拼成一行。
|
||||||
* @param person - 预览里的成员
|
* @param person - 预览里的成员
|
||||||
* @returns 姓名 · 原角色
|
* @returns 姓名,或姓名 · 仍保留的角色
|
||||||
*/
|
*/
|
||||||
function personLine(person: PermissionRolePerson): string {
|
function personLine(person: PermissionRolePerson): string {
|
||||||
const name = person.real_name || person.username;
|
const name = person.real_name || person.username;
|
||||||
const from = person.role_name || person.role;
|
const kept = (person.retained_role_names || []).filter(Boolean).join('、');
|
||||||
return `${name} · ${from}`;
|
return kept ? `${name} · ${kept}` : name;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 是否有需要写库的增减。
|
* 是否有需要写库的增减。
|
||||||
* @returns 有改入或移出时为 true
|
* @returns 有加入或移出时为 true
|
||||||
*/
|
*/
|
||||||
const hasChanges = computed(() => Boolean(props.preview && (props.preview.added.length || props.preview.removed.length)));
|
const hasChanges = computed(() => Boolean(props.preview && (props.preview.added.length || props.preview.removed.length)));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移出后是否有人会回到默认权限组。
|
||||||
|
*/
|
||||||
|
const returnsToDefault = computed(() =>
|
||||||
|
Boolean(props.preview?.removed.some((person) => person.returns_to_default)),
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移出后是否还有人保留其他业务角色。
|
||||||
|
*/
|
||||||
|
const keepsOtherRoles = computed(() =>
|
||||||
|
Boolean(props.preview?.removed.some((person) => (person.retained_role_names || []).length > 0)),
|
||||||
|
);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 点关闭或按 Esc 时通知页面放弃本次调整。
|
* 点关闭或按 Esc 时通知页面放弃本次调整。
|
||||||
* @param open - Element 对话框的打开状态
|
* @param open - Element 对话框的打开状态
|
||||||
@@ -90,7 +104,8 @@ function onVisibleChange(open: boolean): void {
|
|||||||
<ul class="perm-member-list">
|
<ul class="perm-member-list">
|
||||||
<li v-for="person in preview.removed" :key="person.id">{{ personLine(person) }}</li>
|
<li v-for="person in preview.removed" :key="person.id">{{ personLine(person) }}</li>
|
||||||
</ul>
|
</ul>
|
||||||
<p class="hx-element-hint">{{ t('admin.permRoles.confirm.backToDefault') }}</p>
|
<p v-if="returnsToDefault" class="hx-element-hint">{{ t('admin.permRoles.confirm.backToDefault') }}</p>
|
||||||
|
<p v-if="keepsOtherRoles" class="hx-element-hint">{{ t('admin.permRoles.confirm.keepOthers') }}</p>
|
||||||
</div>
|
</div>
|
||||||
<p v-if="!preview.added.length && !preview.removed.length" class="hx-element-hint">
|
<p v-if="!preview.added.length && !preview.removed.length" class="hx-element-hint">
|
||||||
{{ t('admin.permRoles.confirm.noChanges') }}
|
{{ t('admin.permRoles.confirm.noChanges') }}
|
||||||
|
|||||||
@@ -499,7 +499,7 @@ export function usePermissionsAdmin() {
|
|||||||
}
|
}
|
||||||
pickerRole.value = role;
|
pickerRole.value = role;
|
||||||
pickerSelectedIds.value = pickerUsers.value
|
pickerSelectedIds.value = pickerUsers.value
|
||||||
.filter((person) => person.role === role.code)
|
.filter((person) => (person.role_codes?.length ? person.role_codes : [person.role]).includes(role.code))
|
||||||
.map((person) => person.id);
|
.map((person) => person.id);
|
||||||
showPicker.value = true;
|
showPicker.value = true;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
* 依赖:useReportsAdmin、AdminListPage、AdminListTabs、element-plus、@element-plus/icons-vue。
|
* 依赖:useReportsAdmin、AdminListPage、AdminListTabs、element-plus、@element-plus/icons-vue。
|
||||||
* 逻辑:路由 /admin/reports/:table?。看板块用 ElCard;有表格的页签用 AdminListPage。
|
* 逻辑:路由 /admin/reports/:table?。看板块用 ElCard;有表格的页签用 AdminListPage。
|
||||||
* 反馈页签用 AdminListTabs。筛选和分页沿用 composable 里的原状态。删除聊天日志用 Element 确认框。
|
* 反馈页签用 AdminListTabs。筛选和分页沿用 composable 里的原状态。删除聊天日志用 Element 确认框。
|
||||||
|
* 意见反馈附图列为懒加载缩略图(composable 内 blob objectURL 缓存),页面附 lightbox 大图预览。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, onMounted } from 'vue';
|
import { computed, onMounted } from 'vue';
|
||||||
@@ -49,6 +50,7 @@ import AdminListPage from '@/features/admin/components/AdminListPage.vue';
|
|||||||
import AdminListTabs from '@/features/admin/components/AdminListTabs.vue';
|
import AdminListTabs from '@/features/admin/components/AdminListTabs.vue';
|
||||||
import type { ApplicationReportItem, ApplicationSortKey, ApplicationUsageFilter } from '@/features/admin/types/report.types';
|
import type { ApplicationReportItem, ApplicationSortKey, ApplicationUsageFilter } from '@/features/admin/types/report.types';
|
||||||
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
import { formatLocalDateTime } from '@/shared/utils/dateTime';
|
||||||
|
import type { FeedbackReportImage } from '../../api/admin.api';
|
||||||
import { useReportsAdmin } from './composables/useReportsAdmin';
|
import { useReportsAdmin } from './composables/useReportsAdmin';
|
||||||
|
|
||||||
const vLoading = ElLoading.directive;
|
const vLoading = ElLoading.directive;
|
||||||
@@ -181,6 +183,12 @@ const {
|
|||||||
generalFeedbackTotal,
|
generalFeedbackTotal,
|
||||||
feedbackSummary,
|
feedbackSummary,
|
||||||
closeFeedback,
|
closeFeedback,
|
||||||
|
feedbackImagePreview,
|
||||||
|
feedbackImageUrl,
|
||||||
|
loadFeedbackImage,
|
||||||
|
openFeedbackImagePreview,
|
||||||
|
closeFeedbackImagePreview,
|
||||||
|
stepFeedbackImagePreview,
|
||||||
feedbackTypeOptions,
|
feedbackTypeOptions,
|
||||||
feedbackModuleOptions,
|
feedbackModuleOptions,
|
||||||
feedbackSourceOptions,
|
feedbackSourceOptions,
|
||||||
@@ -231,6 +239,26 @@ const {
|
|||||||
batchDeleteChatLogs,
|
batchDeleteChatLogs,
|
||||||
} = useReportsAdmin();
|
} = useReportsAdmin();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前大图预览指向的附图元数据(下标越界时钳制,防翻页竞态渲染 undefined)。
|
||||||
|
*/
|
||||||
|
const currentPreviewImage = computed(() => {
|
||||||
|
const preview = feedbackImagePreview.value;
|
||||||
|
if (!preview || preview.images.length === 0) return null;
|
||||||
|
const safeIndex = Math.min(Math.max(0, preview.index), preview.images.length - 1);
|
||||||
|
return preview.images[safeIndex] || null;
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前大图的 blob objectURL(未加载完成返回空串,lightbox 由 v-if 隐藏 <img>)。
|
||||||
|
*/
|
||||||
|
const currentPreviewUrl = computed(() => {
|
||||||
|
const preview = feedbackImagePreview.value;
|
||||||
|
const image = currentPreviewImage.value;
|
||||||
|
if (!preview || !image) return '';
|
||||||
|
return feedbackImageUrl(preview.feedbackId, image.image_id) || '';
|
||||||
|
});
|
||||||
|
|
||||||
/** 应用运营可点击排序的列 */
|
/** 应用运营可点击排序的列 */
|
||||||
const applicationSortableKeys: ApplicationSortKey[] = [
|
const applicationSortableKeys: ApplicationSortKey[] = [
|
||||||
'name',
|
'name',
|
||||||
@@ -672,6 +700,16 @@ function isGeneralFeedbackContent(columnKey: string): boolean {
|
|||||||
return isMergedFeedbackTable.value && feedbackTab.value === 'general' && columnKey === 'content';
|
return isMergedFeedbackTable.value && feedbackTab.value === 'general' && columnKey === 'content';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 意见反馈行的附图元数据。
|
||||||
|
* @param row - 当前行
|
||||||
|
* @returns 附图元数据数组;无图或字段缺失时为空数组
|
||||||
|
*/
|
||||||
|
function rowFeedbackImages(row: ReportTableRow): FeedbackReportImage[] {
|
||||||
|
const images = (row as { images?: FeedbackReportImage[] }).images;
|
||||||
|
return Array.isArray(images) ? images : [];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 意见反馈操作列。
|
* 意见反馈操作列。
|
||||||
* @param columnKey - 列字段
|
* @param columnKey - 列字段
|
||||||
@@ -1779,6 +1817,25 @@ onMounted(() => {
|
|||||||
</span>
|
</span>
|
||||||
</template>
|
</template>
|
||||||
</ElPopover>
|
</ElPopover>
|
||||||
|
<!-- 意见反馈附图列:懒加载缩略图(<img> 无法带鉴权头,blob URL 由 composable 缓存),点击放大;无图显示 - -->
|
||||||
|
<template v-else-if="isMergedFeedbackTable && columnKey === 'images'">
|
||||||
|
<div class="flex items-center gap-1">
|
||||||
|
<template v-if="rowFeedbackImages(row as ReportTableRow).length">
|
||||||
|
<img
|
||||||
|
v-for="(img, i) in rowFeedbackImages(row as ReportTableRow)"
|
||||||
|
:key="img.image_id"
|
||||||
|
:src="feedbackImageUrl(Number((row as ReportTableRow).id), img.image_id) || ''"
|
||||||
|
:alt="img.original_filename"
|
||||||
|
loading="lazy"
|
||||||
|
class="h-10 w-10 cursor-pointer rounded border border-default object-cover"
|
||||||
|
@load="loadFeedbackImage(Number((row as ReportTableRow).id), img.image_id)"
|
||||||
|
@error="loadFeedbackImage(Number((row as ReportTableRow).id), img.image_id)"
|
||||||
|
@click.stop="openFeedbackImagePreview(row as ReportTableRow, Number(i))"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
<span v-else class="report-muted">-</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
<template v-else-if="isMergedFeedbackTable && columnKey === 'chat_log_id'">
|
<template v-else-if="isMergedFeedbackTable && columnKey === 'chat_log_id'">
|
||||||
<ElButton
|
<ElButton
|
||||||
v-if="getFeedbackChatLogCell(row as ReportTableRow).type === 'link'"
|
v-if="getFeedbackChatLogCell(row as ReportTableRow).type === 'link'"
|
||||||
@@ -1895,6 +1952,35 @@ onMounted(() => {
|
|||||||
<ElButton @click="closeChatLogDetail">{{ t('admin.report.chatLog.close') }}</ElButton>
|
<ElButton @click="closeChatLogDetail">{{ t('admin.report.chatLog.close') }}</ElButton>
|
||||||
</template>
|
</template>
|
||||||
</ElDialog>
|
</ElDialog>
|
||||||
|
<!-- 意见反馈附图大图预览:深色遮罩 + 前后翻页(blob URL 由 composable 缓存) -->
|
||||||
|
<div
|
||||||
|
v-if="feedbackImagePreview"
|
||||||
|
class="fixed inset-0 z-50 flex items-center justify-center p-4"
|
||||||
|
>
|
||||||
|
<div class="absolute inset-0 bg-black/70" @click="closeFeedbackImagePreview"></div>
|
||||||
|
<div class="relative flex max-h-[90vh] max-w-[90vw] flex-col items-center gap-3">
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(-1)">‹</button>
|
||||||
|
<img
|
||||||
|
v-if="currentPreviewUrl"
|
||||||
|
:src="currentPreviewUrl"
|
||||||
|
:alt="currentPreviewImage?.original_filename"
|
||||||
|
class="max-h-[80vh] max-w-[80vw] rounded object-contain"
|
||||||
|
/>
|
||||||
|
<button type="button" class="btn-icon-ds text-white" @click.stop="stepFeedbackImagePreview(1)">›</button>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3 text-sm text-white/80">
|
||||||
|
<span>{{ feedbackImagePreview.index + 1 }} / {{ feedbackImagePreview.images.length }}</span>
|
||||||
|
<span>{{ currentPreviewImage?.original_filename }}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn-icon-ds"
|
||||||
|
:title="t('admin.report.feedback.closePreview')"
|
||||||
|
@click="closeFeedbackImagePreview"
|
||||||
|
>✕</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -5,9 +5,10 @@
|
|||||||
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,页码状态交给页面的 ElPagination;
|
* 逻辑:ReportsPage 调用本 composable;使用分析按用户服务端分页、按应用前端分页,页码状态交给页面的 ElPagination;
|
||||||
* 低使用应用优先消费后端 low_agents(含零使用启用应用),与应用运营口径对齐;
|
* 低使用应用优先消费后端 low_agents(含零使用启用应用),与应用运营口径对齐;
|
||||||
* 统计范围统一为开始/结束日期(默认近 30 天),经 start_date/end_date 传给后端,聊天日志走 created_from/created_to;
|
* 统计范围统一为开始/结束日期(默认近 30 天),经 start_date/end_date 传给后端,聊天日志走 created_from/created_to;
|
||||||
* 趋势 by_day 前端按日期升序兜底;问题分析优先问题表前端分页;非表页切换时清空通用表状态防幽灵分页。
|
* 趋势 by_day 前端按日期升序兜底;问题分析优先问题表前端分页;非表页切换时清空通用表状态防幽灵分页;
|
||||||
|
* 意见反馈附图经 requestBlob 代理接口懒加载 objectURL(缓存键 feedbackId:imageId),支持行内缩略图与大图循环预览。
|
||||||
*/
|
*/
|
||||||
import { computed, ref, watch } from 'vue';
|
import { computed, reactive, ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
import { ElMessageBox } from 'element-plus';
|
import { ElMessageBox } from 'element-plus';
|
||||||
@@ -25,6 +26,7 @@ import {
|
|||||||
getAdminUsageReport,
|
getAdminUsageReport,
|
||||||
listAdminAgents,
|
listAdminAgents,
|
||||||
} from '@/features/admin/api/admin.api';
|
} from '@/features/admin/api/admin.api';
|
||||||
|
import { requestBlob } from '@/shared/api/client';
|
||||||
import { loadReportLayoutPref, saveReportLayoutPref } from '@/shared/composables/useReportLayoutStorage';
|
import { loadReportLayoutPref, saveReportLayoutPref } from '@/shared/composables/useReportLayoutStorage';
|
||||||
import { buildOffsetPageButtons } from '@/shared/composables/useOffsetPagination';
|
import { buildOffsetPageButtons } from '@/shared/composables/useOffsetPagination';
|
||||||
import { useMessage } from '@/shared/composables/useMessage';
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
@@ -44,6 +46,7 @@ import type {
|
|||||||
UsageReport,
|
UsageReport,
|
||||||
} from '@/features/admin/types/report.types';
|
} from '@/features/admin/types/report.types';
|
||||||
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
|
import type { AdminReportTableId } from '@/features/admin/types/admin.types';
|
||||||
|
import type { FeedbackReportImage } from '@/features/admin/api/admin.api';
|
||||||
|
|
||||||
/** 聊天日志报表固定展示列(顺序与产品约定一致;id 仅用于批量删除) */
|
/** 聊天日志报表固定展示列(顺序与产品约定一致;id 仅用于批量删除) */
|
||||||
const CHAT_LOGS_REPORT_KEYS = [
|
const CHAT_LOGS_REPORT_KEYS = [
|
||||||
@@ -65,7 +68,8 @@ const CHAT_LOG_RISK_STATUS_OPTIONS = ['attention', 'review', 'responded'] as con
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 报表列默认宽度:聊天日志前三列与 Token 收窄,提问/回答留宽,风险列居中紧凑;
|
* 报表列默认宽度:聊天日志前三列与 Token 收窄,提问/回答留宽,风险列居中紧凑;
|
||||||
* 意见反馈操作列保留按钮所需空间,防止中文文案按单字断行拉高整行。
|
* 意见反馈操作列保留按钮所需空间,防止中文文案按单字断行拉高整行;
|
||||||
|
* 意见反馈附图列按 3-4 张 40px 缩略图横排估宽。
|
||||||
* @param key - 列字段名
|
* @param key - 列字段名
|
||||||
* @returns 像素宽度
|
* @returns 像素宽度
|
||||||
*/
|
*/
|
||||||
@@ -98,6 +102,8 @@ const defaultChatLogsColumnWidth = (key: string): number => {
|
|||||||
return 240;
|
return 240;
|
||||||
case 'actions':
|
case 'actions':
|
||||||
return 112;
|
return 112;
|
||||||
|
case 'images':
|
||||||
|
return 176;
|
||||||
default:
|
default:
|
||||||
return 160;
|
return 160;
|
||||||
}
|
}
|
||||||
@@ -381,6 +387,87 @@ export function useReportsAdmin() {
|
|||||||
chatLogDetailRow.value = null;
|
chatLogDetailRow.value = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ===== 意见反馈附图:blob 懒加载缓存 + 大图循环预览 =====
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 附图 objectURL 缓存(reactive Map,模板读取其键值建立响应依赖)。
|
||||||
|
* 键:`${feedbackId}:${imageId}`;值:blob objectURL,''=加载失败/加载中占位(<img> 空 src,不重试)。
|
||||||
|
* 回收语义:缓存随页面会话存续、objectURL 刻意不 revoke——缩略图与大图共享同一 URL,
|
||||||
|
* 提前回收会让已渲染的 <img> 变裂图;页面刷新时由浏览器统一回收。
|
||||||
|
*/
|
||||||
|
const feedbackImageObjectUrls = reactive(new Map<string, string>());
|
||||||
|
|
||||||
|
/** 当前大图预览状态(null=未打开):feedbackId 拼接 raw 接口,images/index 支持在单条反馈内循环翻页 */
|
||||||
|
const feedbackImagePreview = ref<{ feedbackId: number; images: FeedbackReportImage[]; index: number } | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取附图 objectURL(【AI 触发时机】模板 :src 绑定按此取值,无需手动刷新)。
|
||||||
|
* @param feedbackId - 反馈行 id(禁止传 undefined/0)
|
||||||
|
* @param imageId - 附图 id(禁止传 undefined/0)
|
||||||
|
* @returns blob objectURL;未加载过返回 null;加载失败返回 ''(<img> 显示空占位)
|
||||||
|
*/
|
||||||
|
const feedbackImageUrl = (feedbackId: number, imageId: number): string | null => {
|
||||||
|
const url = feedbackImageObjectUrls.get(`${feedbackId}:${imageId}`);
|
||||||
|
return url === undefined ? null : url;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 懒加载单张附图为 blob objectURL(【AI 触发时机】缩略图 @load/@error 或打开/翻页大图时调用)。
|
||||||
|
* 核心逻辑:<img> 无法自带鉴权头,必须经 requestBlob 代理接口取流再 createObjectURL。
|
||||||
|
* [STEP 1] 缓存已有键(含 objectURL 与 ''占位)直接返回,避免 @load/@error 反复触发重复请求;
|
||||||
|
* [STEP 2] 同步写入 ''占位实现并发去重,随后异步请求;成功覆盖为 objectURL(响应式触发单元格重渲),
|
||||||
|
* 失败静默保持 ''占位——空 src 不会再触发 error 事件,天然防止无限重试。
|
||||||
|
* @param feedbackId - 反馈行 id(禁止传 undefined/0)
|
||||||
|
* @param imageId - 附图 id(禁止传 undefined/0)
|
||||||
|
*/
|
||||||
|
const loadFeedbackImage = async (feedbackId: number, imageId: number): Promise<void> => {
|
||||||
|
if (!Number.isFinite(feedbackId) || !Number.isFinite(imageId) || feedbackId <= 0 || imageId <= 0) return;
|
||||||
|
const key = `${feedbackId}:${imageId}`;
|
||||||
|
if (feedbackImageObjectUrls.has(key)) return;
|
||||||
|
feedbackImageObjectUrls.set(key, '');
|
||||||
|
try {
|
||||||
|
const { blob } = await requestBlob(
|
||||||
|
`/api/admin/reports/general-feedbacks/${feedbackId}/images/${imageId}/raw`,
|
||||||
|
);
|
||||||
|
feedbackImageObjectUrls.set(key, URL.createObjectURL(blob));
|
||||||
|
} catch {
|
||||||
|
// 拉取失败保持 ''占位:单元格显示空缩略图即可,不打断报表浏览
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打开附图大图预览(【AI 触发时机】点击行内缩略图时调用)。
|
||||||
|
* @param row - 意见反馈行(须含 id 与 images 元数据;无图行直接忽略)
|
||||||
|
* @param index - 预览起始附图下标(越界时钳制到最后一张)
|
||||||
|
*/
|
||||||
|
const openFeedbackImagePreview = (row: any, index: number): void => {
|
||||||
|
const feedbackId = Number(row?.id);
|
||||||
|
const images = Array.isArray(row?.images) ? row.images : [];
|
||||||
|
if (!Number.isFinite(feedbackId) || feedbackId <= 0 || images.length === 0) return;
|
||||||
|
const safeIndex = Math.min(Math.max(0, Number(index) || 0), images.length - 1);
|
||||||
|
feedbackImagePreview.value = { feedbackId, images, index: safeIndex };
|
||||||
|
void loadFeedbackImage(feedbackId, images[safeIndex].image_id);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 关闭附图大图预览(objectURL 缓存保留,行内缩略图复用同一 URL) */
|
||||||
|
const closeFeedbackImagePreview = (): void => {
|
||||||
|
feedbackImagePreview.value = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 大图预览翻页(【AI 触发时机】lightbox 左右箭头按钮调用)。
|
||||||
|
* 核心逻辑:index 仅在当前反馈的 images 内 +1/-1 取模循环,不跨反馈串联。
|
||||||
|
* @param delta - 翻页步长(1=下一张,-1=上一张;其他值按取模处理)
|
||||||
|
*/
|
||||||
|
const stepFeedbackImagePreview = (delta: number): void => {
|
||||||
|
const preview = feedbackImagePreview.value;
|
||||||
|
if (!preview || preview.images.length === 0) return;
|
||||||
|
const len = preview.images.length;
|
||||||
|
preview.index = (((preview.index + delta) % len) + len) % len;
|
||||||
|
const next = preview.images[preview.index];
|
||||||
|
if (next) void loadFeedbackImage(preview.feedbackId, next.image_id);
|
||||||
|
};
|
||||||
|
|
||||||
/** 风险状态 → 本地化标签 */
|
/** 风险状态 → 本地化标签 */
|
||||||
const getChatLogRiskStatusLabel = (status: string): string => {
|
const getChatLogRiskStatusLabel = (status: string): string => {
|
||||||
const key = `admin.report.chatLog.risk.${status}`;
|
const key = `admin.report.chatLog.risk.${status}`;
|
||||||
@@ -1048,6 +1135,7 @@ const visibleReportKeys = computed(() => {
|
|||||||
'feedback_module',
|
'feedback_module',
|
||||||
'feedback_type',
|
'feedback_type',
|
||||||
'content',
|
'content',
|
||||||
|
'images',
|
||||||
'username',
|
'username',
|
||||||
'real_name',
|
'real_name',
|
||||||
'department',
|
'department',
|
||||||
@@ -1122,6 +1210,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
|
|||||||
/** 意见反馈 Tab 专用列名(覆盖通用列名,主要在关联跳转列) */
|
/** 意见反馈 Tab 专用列名(覆盖通用列名,主要在关联跳转列) */
|
||||||
generalColumns: {
|
generalColumns: {
|
||||||
chat_log_id: 'Linked Chat',
|
chat_log_id: 'Linked Chat',
|
||||||
|
images: 'Images',
|
||||||
},
|
},
|
||||||
/** 回答评价 Tab 列名:更易读、贴合评价语境 */
|
/** 回答评价 Tab 列名:更易读、贴合评价语境 */
|
||||||
ratingColumns: {
|
ratingColumns: {
|
||||||
@@ -1158,6 +1247,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
|
|||||||
},
|
},
|
||||||
generalColumns: {
|
generalColumns: {
|
||||||
chat_log_id: '\u5173\u8054\u804a\u5929',
|
chat_log_id: '\u5173\u8054\u804a\u5929',
|
||||||
|
images: '\u9644\u56fe',
|
||||||
},
|
},
|
||||||
ratingColumns: {
|
ratingColumns: {
|
||||||
chat_log_id: '\u5173\u8054\u804a\u5929',
|
chat_log_id: '\u5173\u8054\u804a\u5929',
|
||||||
@@ -1193,6 +1283,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
|
|||||||
},
|
},
|
||||||
generalColumns: {
|
generalColumns: {
|
||||||
chat_log_id: '\u95dc\u806f\u804a\u5929',
|
chat_log_id: '\u95dc\u806f\u804a\u5929',
|
||||||
|
images: '\u9644\u5716',
|
||||||
},
|
},
|
||||||
ratingColumns: {
|
ratingColumns: {
|
||||||
chat_log_id: '\u95dc\u806f\u804a\u5929',
|
chat_log_id: '\u95dc\u806f\u804a\u5929',
|
||||||
@@ -1228,6 +1319,7 @@ const feedbackReportI18nMap: Record<string, FeedbackReportI18nPack> = {
|
|||||||
},
|
},
|
||||||
generalColumns: {
|
generalColumns: {
|
||||||
chat_log_id: '\u0e41\u0e0a\u0e17\u0e17\u0e35\u0e48\u0e40\u0e0a\u0e37\u0e48\u0e2d\u0e21\u0e42\u0e22\u0e07',
|
chat_log_id: '\u0e41\u0e0a\u0e17\u0e17\u0e35\u0e48\u0e40\u0e0a\u0e37\u0e48\u0e2d\u0e21\u0e42\u0e22\u0e07',
|
||||||
|
images: '\u0e23\u0e39\u0e1b\u0e20\u0e32\u0e1e',
|
||||||
},
|
},
|
||||||
ratingColumns: {
|
ratingColumns: {
|
||||||
chat_log_id: '\u0e41\u0e0a\u0e17\u0e17\u0e35\u0e48\u0e40\u0e0a\u0e37\u0e48\u0e2d\u0e21\u0e42\u0e22\u0e07',
|
chat_log_id: '\u0e41\u0e0a\u0e17\u0e17\u0e35\u0e48\u0e40\u0e0a\u0e37\u0e48\u0e2d\u0e21\u0e42\u0e22\u0e07',
|
||||||
@@ -1351,6 +1443,11 @@ const getReportCellValue = (row: any, key: string) => {
|
|||||||
return getTranslatedFeedbackValue('pages', value);
|
return getTranslatedFeedbackValue('pages', value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (key === 'images') {
|
||||||
|
// 附图列为对象数组:单元格由专用分支渲染缩略图;此处返回张数,供表头排序与 Excel 导出,避免出现 [object Object]
|
||||||
|
return Array.isArray(value) ? value.length : 0;
|
||||||
|
}
|
||||||
|
|
||||||
// format datetime fields in report table
|
// format datetime fields in report table
|
||||||
if (typeof value === 'string' && (key.endsWith('_at') || key === 'created_at' || key === 'updated_at')) {
|
if (typeof value === 'string' && (key.endsWith('_at') || key === 'created_at' || key === 'updated_at')) {
|
||||||
return formatReportDateTime(value);
|
return formatReportDateTime(value);
|
||||||
@@ -1868,6 +1965,12 @@ watch([reportPageSize, issueQuestionTotal], () => {
|
|||||||
feedbackSummary,
|
feedbackSummary,
|
||||||
expandedFeedbackId,
|
expandedFeedbackId,
|
||||||
closeFeedback,
|
closeFeedback,
|
||||||
|
feedbackImagePreview,
|
||||||
|
feedbackImageUrl,
|
||||||
|
loadFeedbackImage,
|
||||||
|
openFeedbackImagePreview,
|
||||||
|
closeFeedbackImagePreview,
|
||||||
|
stepFeedbackImagePreview,
|
||||||
feedbackTypeOptions,
|
feedbackTypeOptions,
|
||||||
feedbackModuleOptions,
|
feedbackModuleOptions,
|
||||||
feedbackSourceOptions,
|
feedbackSourceOptions,
|
||||||
|
|||||||
@@ -2,7 +2,8 @@
|
|||||||
* features/admin/modules/users/components/UserFormModal.vue
|
* features/admin/modules/users/components/UserFormModal.vue
|
||||||
* 用途:创建/编辑用户弹窗。权限组启用后只选角色,不再按人勾应用或功能权限。
|
* 用途:创建/编辑用户弹窗。权限组启用后只选角色,不再按人勾应用或功能权限。
|
||||||
* 依赖:element-plus、admin.types、user.types、permissionRole.types、roleLabel.LEGACY_ROLE_OPTIONS。
|
* 依赖:element-plus、admin.types、user.types、permissionRole.types、roleLabel.LEGACY_ROLE_OPTIONS。
|
||||||
* 逻辑:UsersPage 传入角色列表;未种子权限组时保留历史 Agent / 功能权限勾选,角色下拉用旧枚举。
|
* 逻辑:UsersPage 传入角色列表。已配置权限组时角色可多选,权限取并集;选平台管理员会清掉其他角色。
|
||||||
|
* 未种子权限组时保留历史 Agent / 功能权限勾选,角色下拉用旧枚举。
|
||||||
* 本弹窗属于用户管理 Element Plus 试点。
|
* 本弹窗属于用户管理 Element Plus 试点。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
@@ -59,6 +60,21 @@ function onVisibleChange(open: boolean): void {
|
|||||||
if (!open) emit('close');
|
if (!open) emit('close');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 已配置权限组时的多选。选中平台管理员则只留该角色;清空时回到默认角色。
|
||||||
|
* @param codes - 当前勾选的角色 code
|
||||||
|
*/
|
||||||
|
function onRoleCodesChange(codes: string[] | string): void {
|
||||||
|
const admin = props.roles.find((role) => role.is_platform_admin);
|
||||||
|
let next = Array.isArray(codes) ? [...codes] : [codes];
|
||||||
|
if (admin && next.includes(admin.code)) next = [admin.code];
|
||||||
|
if (!next.length) {
|
||||||
|
const fallback = props.roles.find((role) => role.is_default)?.code || 'user';
|
||||||
|
next = [fallback];
|
||||||
|
}
|
||||||
|
props.form.role_codes = next;
|
||||||
|
props.form.role = next[0] || props.form.role;
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* 部门选择。清空时写回空字符串,表示不指定部门。
|
* 部门选择。清空时写回空字符串,表示不指定部门。
|
||||||
* @param value - 选中的部门名;清空为 undefined
|
* @param value - 选中的部门名;清空为 undefined
|
||||||
@@ -116,11 +132,21 @@ function onDepartmentChange(value: string | undefined): void {
|
|||||||
</ElCheckboxGroup>
|
</ElCheckboxGroup>
|
||||||
<p v-if="agents.length === 0" class="hx-element-hint">{{ t('admin.user.fields.noAgents') }}</p>
|
<p v-if="agents.length === 0" class="hx-element-hint">{{ t('admin.user.fields.noAgents') }}</p>
|
||||||
</ElFormItem>
|
</ElFormItem>
|
||||||
<ElFormItem class="users-form-span" :label="t('admin.user.fields.role')" required>
|
<ElFormItem v-if="rolesConfigured" class="users-form-span" :label="t('admin.user.fields.role')" required>
|
||||||
|
<ElSelect
|
||||||
|
:model-value="form.role_codes"
|
||||||
|
class="w-full"
|
||||||
|
multiple
|
||||||
|
@update:model-value="onRoleCodesChange"
|
||||||
|
>
|
||||||
|
<ElOption v-for="option in roleOptions" :key="option.value" :label="option.label" :value="option.value" />
|
||||||
|
</ElSelect>
|
||||||
|
<p class="hx-element-hint">{{ t('admin.permRoles.userFormHint') }}</p>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem v-else class="users-form-span" :label="t('admin.user.fields.role')" required>
|
||||||
<ElSelect v-model="form.role" class="w-full">
|
<ElSelect v-model="form.role" class="w-full">
|
||||||
<ElOption v-for="option in roleOptions" :key="option.value" :label="option.label" :value="option.value" />
|
<ElOption v-for="option in roleOptions" :key="option.value" :label="option.label" :value="option.value" />
|
||||||
</ElSelect>
|
</ElSelect>
|
||||||
<p v-if="rolesConfigured" class="hx-element-hint">{{ t('admin.permRoles.userFormHint') }}</p>
|
|
||||||
</ElFormItem>
|
</ElFormItem>
|
||||||
<ElFormItem v-if="!rolesConfigured" class="users-form-span" :label="t('admin.user.fields.featurePermissions')">
|
<ElFormItem v-if="!rolesConfigured" class="users-form-span" :label="t('admin.user.fields.featurePermissions')">
|
||||||
<div class="flex flex-col gap-3">
|
<div class="flex flex-col gap-3">
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ export function useUsersAdmin() {
|
|||||||
const showUserModal = ref(false);
|
const showUserModal = ref(false);
|
||||||
const editingUser = ref<UserFormState>(createEmptyUserForm());
|
const editingUser = ref<UserFormState>(createEmptyUserForm());
|
||||||
const originalUserRole = ref('user');
|
const originalUserRole = ref('user');
|
||||||
|
const originalRoleCodes = ref<string[]>(['user']);
|
||||||
|
|
||||||
const showBatchEditModal = ref(false);
|
const showBatchEditModal = ref(false);
|
||||||
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
|
const batchEditForm = ref<BatchEditForm>({ department: '', role: '', status: '' });
|
||||||
@@ -228,19 +229,27 @@ export function useUsersAdmin() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const openCreateUserModal = (): void => {
|
const openCreateUserModal = (): void => {
|
||||||
editingUser.value = { ...createEmptyUserForm(), role: defaultRoleCode.value };
|
editingUser.value = {
|
||||||
|
...createEmptyUserForm(),
|
||||||
|
role: defaultRoleCode.value,
|
||||||
|
role_codes: [defaultRoleCode.value],
|
||||||
|
};
|
||||||
originalUserRole.value = defaultRoleCode.value;
|
originalUserRole.value = defaultRoleCode.value;
|
||||||
|
originalRoleCodes.value = [defaultRoleCode.value];
|
||||||
showUserModal.value = true;
|
showUserModal.value = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
const openEditUserModal = (user: AdminUserRow): void => {
|
const openEditUserModal = (user: AdminUserRow): void => {
|
||||||
|
const roleCodes = user.role_codes?.length ? [...user.role_codes] : [user.role];
|
||||||
originalUserRole.value = user.role;
|
originalUserRole.value = user.role;
|
||||||
|
originalRoleCodes.value = roleCodes;
|
||||||
editingUser.value = {
|
editingUser.value = {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
department: user.department || '',
|
department: user.department || '',
|
||||||
role: user.role,
|
role: roleCodes[0] || user.role,
|
||||||
|
role_codes: roleCodes,
|
||||||
password: '',
|
password: '',
|
||||||
real_name: user.real_name || '',
|
real_name: user.real_name || '',
|
||||||
employee_id: user.employee_id || '',
|
employee_id: user.employee_id || '',
|
||||||
@@ -301,15 +310,18 @@ export function useUsersAdmin() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const nextRole = editingUser.value.role;
|
const selectedCodes = rolesConfigured.value
|
||||||
const roleChanged = isCreate
|
? [...(editingUser.value.role_codes || [])].sort()
|
||||||
? nextRole !== defaultRoleCode.value
|
: [editingUser.value.role];
|
||||||
: nextRole !== originalUserRole.value;
|
const previousCodes = rolesConfigured.value
|
||||||
const touchesAdmin = isAdminRoleCode(nextRole) || isAdminRoleCode(originalUserRole.value);
|
? [...originalRoleCodes.value].sort()
|
||||||
|
: [originalUserRole.value];
|
||||||
|
const roleChanged = selectedCodes.join('|') !== previousCodes.join('|');
|
||||||
|
const touchesAdmin = [...selectedCodes, ...previousCodes].some((code) => isAdminRoleCode(code));
|
||||||
if (roleChanged) {
|
if (roleChanged) {
|
||||||
const message = touchesAdmin
|
const message = touchesAdmin
|
||||||
? t('admin.permRoles.userAdminConfirm')
|
? t('admin.permRoles.userAdminConfirm')
|
||||||
: t('admin.permRoles.userRoleConfirm', { role: nextRole });
|
: t('admin.permRoles.userRoleConfirm', { role: selectedCodes.join('、') });
|
||||||
await confirmRoleThen(message, persistUser);
|
await confirmRoleThen(message, persistUser);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -326,7 +338,8 @@ export function useUsersAdmin() {
|
|||||||
await updateAdminUser(editingUser.value.id, {
|
await updateAdminUser(editingUser.value.id, {
|
||||||
email: editingUser.value.email,
|
email: editingUser.value.email,
|
||||||
department: editingUser.value.department,
|
department: editingUser.value.department,
|
||||||
role: editingUser.value.role,
|
role: editingUser.value.role_codes[0] || editingUser.value.role,
|
||||||
|
roles: rolesConfigured.value ? editingUser.value.role_codes : undefined,
|
||||||
password: editingUser.value.password || undefined,
|
password: editingUser.value.password || undefined,
|
||||||
real_name: editingUser.value.real_name,
|
real_name: editingUser.value.real_name,
|
||||||
employee_id: editingUser.value.employee_id,
|
employee_id: editingUser.value.employee_id,
|
||||||
@@ -339,7 +352,8 @@ export function useUsersAdmin() {
|
|||||||
username: editingUser.value.username,
|
username: editingUser.value.username,
|
||||||
email: editingUser.value.email,
|
email: editingUser.value.email,
|
||||||
department: editingUser.value.department,
|
department: editingUser.value.department,
|
||||||
role: editingUser.value.role,
|
role: editingUser.value.role_codes[0] || editingUser.value.role,
|
||||||
|
roles: rolesConfigured.value ? editingUser.value.role_codes : undefined,
|
||||||
password: editingUser.value.password,
|
password: editingUser.value.password,
|
||||||
real_name: editingUser.value.real_name,
|
real_name: editingUser.value.real_name,
|
||||||
employee_id: editingUser.value.employee_id,
|
employee_id: editingUser.value.employee_id,
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ export interface AdminUserRow {
|
|||||||
department?: string;
|
department?: string;
|
||||||
role: string;
|
role: string;
|
||||||
role_name?: string;
|
role_name?: string;
|
||||||
|
role_codes?: string[];
|
||||||
is_platform_admin?: boolean;
|
is_platform_admin?: boolean;
|
||||||
status: string;
|
status: string;
|
||||||
real_name?: string;
|
real_name?: string;
|
||||||
@@ -75,21 +76,40 @@ export interface AdminDepartmentRow {
|
|||||||
code?: string;
|
code?: string;
|
||||||
company?: string;
|
company?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
|
/** 上级部门主键;null/缺省表示顶级部门 */
|
||||||
|
parent_id?: number | null;
|
||||||
|
/** 同级排序号(升序),对应 ERP hrao09 */
|
||||||
|
sort_order?: number;
|
||||||
|
/** 是否在组织树中隐藏(对应 ERP hrao08;管理端仍可见并打标) */
|
||||||
|
is_hidden?: boolean;
|
||||||
member_count?: number;
|
member_count?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 部门树节点:/admin/departments/tree 返回结构,children 已按同级排序号排好 */
|
||||||
|
export interface AdminDepartmentTreeNode extends AdminDepartmentRow {
|
||||||
|
/** 含全部下级部门的成员总数(递归汇总) */
|
||||||
|
total_member_count?: number;
|
||||||
|
children: AdminDepartmentTreeNode[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface AdminDepartmentMember {
|
export interface AdminDepartmentMember {
|
||||||
id: number;
|
id: number;
|
||||||
username: string;
|
username: string;
|
||||||
real_name?: string;
|
real_name?: string;
|
||||||
employee_id?: string;
|
employee_id?: string;
|
||||||
email?: string;
|
email?: string;
|
||||||
|
phone_number?: string;
|
||||||
|
/** 成员所属部门名(含下级视图下用于区分来源部门) */
|
||||||
|
department?: string;
|
||||||
status?: string;
|
status?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 部门成员分页响应(OA 组织面板口径:右侧成员列表) */
|
||||||
export interface AdminDepartmentMembersResponse {
|
export interface AdminDepartmentMembersResponse {
|
||||||
department: AdminDepartmentRow;
|
department: AdminDepartmentRow;
|
||||||
count: number;
|
total: number;
|
||||||
|
page: number;
|
||||||
|
page_size: number;
|
||||||
members: AdminDepartmentMember[];
|
members: AdminDepartmentMember[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,12 @@ export interface DepartmentFormState {
|
|||||||
code?: string;
|
code?: string;
|
||||||
company?: string;
|
company?: string;
|
||||||
description?: string;
|
description?: string;
|
||||||
|
/** 上级部门主键;null 表示顶级部门 */
|
||||||
|
parentId?: number | null;
|
||||||
|
/** 同级排序号(升序) */
|
||||||
|
sortOrder?: number;
|
||||||
|
/** 是否在组织树中隐藏 */
|
||||||
|
isHidden?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -23,6 +29,9 @@ export const createEmptyDepartmentForm = (): DepartmentFormState => ({
|
|||||||
code: '',
|
code: '',
|
||||||
company: '',
|
company: '',
|
||||||
description: '',
|
description: '',
|
||||||
|
parentId: null,
|
||||||
|
sortOrder: 0,
|
||||||
|
isHidden: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -36,4 +45,7 @@ export const departmentRowToForm = (dept: AdminDepartmentRow): DepartmentFormSta
|
|||||||
code: dept.code || '',
|
code: dept.code || '',
|
||||||
company: dept.company || '',
|
company: dept.company || '',
|
||||||
description: dept.description || '',
|
description: dept.description || '',
|
||||||
|
parentId: dept.parent_id ?? null,
|
||||||
|
sortOrder: dept.sort_order ?? 0,
|
||||||
|
isHidden: !!dept.is_hidden,
|
||||||
});
|
});
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
* features/admin/types/permissionRole.types.ts
|
* features/admin/types/permissionRole.types.ts
|
||||||
* 用途:可配置权限组列表、目录、成员预览的前端类型。
|
* 用途:可配置权限组列表、目录、成员预览的前端类型。
|
||||||
* 依赖:shared/types/userPicker.types。
|
* 依赖:shared/types/userPicker.types。
|
||||||
* 逻辑:PermissionsPage / UserFormModal / admin.api 共用;成员预览供确认框展示来源角色。
|
* 逻辑:PermissionsPage / UserFormModal / admin.api 共用;成员预览标明追加后仍保留的角色。
|
||||||
*/
|
*/
|
||||||
import type { UserPickerPerson } from '@/shared/types/userPicker.types';
|
import type { UserPickerPerson } from '@/shared/types/userPicker.types';
|
||||||
|
|
||||||
@@ -46,6 +46,9 @@ export interface PermissionRoleCatalog {
|
|||||||
export interface PermissionRolePerson extends UserPickerPerson {
|
export interface PermissionRolePerson extends UserPickerPerson {
|
||||||
role: string;
|
role: string;
|
||||||
role_name: string;
|
role_name: string;
|
||||||
|
role_codes?: string[];
|
||||||
|
retained_role_names?: string[];
|
||||||
|
returns_to_default?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PermissionRoleMembersPreview {
|
export interface PermissionRoleMembersPreview {
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ export interface UserFormState {
|
|||||||
email: string;
|
email: string;
|
||||||
department: string;
|
department: string;
|
||||||
role: string;
|
role: string;
|
||||||
|
role_codes: string[];
|
||||||
password: string;
|
password: string;
|
||||||
real_name: string;
|
real_name: string;
|
||||||
employee_id: string;
|
employee_id: string;
|
||||||
@@ -50,6 +51,7 @@ export const createEmptyUserForm = (): UserFormState => ({
|
|||||||
email: '',
|
email: '',
|
||||||
department: '',
|
department: '',
|
||||||
role: 'user',
|
role: 'user',
|
||||||
|
role_codes: ['user'],
|
||||||
password: '',
|
password: '',
|
||||||
real_name: '',
|
real_name: '',
|
||||||
employee_id: '',
|
employee_id: '',
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { requestJson } from '@/shared/api/client';
|
|||||||
import type {
|
import type {
|
||||||
AssetHistorySearchResult,
|
AssetHistorySearchResult,
|
||||||
AssetImageResolveResult,
|
AssetImageResolveResult,
|
||||||
|
ChatCapabilityListEntry,
|
||||||
ChatCrossAgentHistoryItem,
|
ChatCrossAgentHistoryItem,
|
||||||
ChatMessage,
|
ChatMessage,
|
||||||
ChatQueryPreviewPage,
|
ChatQueryPreviewPage,
|
||||||
@@ -63,6 +64,16 @@ export const listChatMessages = async (conversationId: string, agentId: number)
|
|||||||
: messages;
|
: messages;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前应用的知识库内容清单(常用问题「能力清单条目」标准答案)。
|
||||||
|
* 用途:AI 回复命中知识库未命中兜底语句时,【知识库内容清单】按钮点击后调用。
|
||||||
|
* 核心逻辑:后端按 agent_id 过滤全局常用问题条目;未配置时抛 code=CHAT.CAPABILITY_LIST_NOT_FOUND。
|
||||||
|
* @param agentId - 当前聊天应用 ID(chatStore.currentAgentId),禁止传 0 或空值。
|
||||||
|
* @returns 含标准答案 answer 的清单条目。
|
||||||
|
*/
|
||||||
|
export const getAgentCapabilityList = (agentId: number) =>
|
||||||
|
requestJson<ChatCapabilityListEntry>(`/api/chat/capability-list?agent_id=${agentId}`, auth());
|
||||||
|
|
||||||
export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
|
export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
|
||||||
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
|
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ import { useRoute } from 'vue-router';
|
|||||||
|
|
||||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||||
|
|
||||||
|
import { Maximize2 } from 'lucide-vue-next';
|
||||||
|
|
||||||
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
import ChatShell from '@/shared/layouts/ChatShell.vue';
|
||||||
|
|
||||||
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
|
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
|
||||||
|
|||||||
@@ -52,7 +52,6 @@ async function handleQueryPreviewAssetImage(assetId: string, assetName: string)
|
|||||||
/>
|
/>
|
||||||
<GeneralFeedbackDialog
|
<GeneralFeedbackDialog
|
||||||
v-model="page.showGeneralFeedbackDialog"
|
v-model="page.showGeneralFeedbackDialog"
|
||||||
:auth-headers="getAuthHeaders()"
|
|
||||||
source-page="chat"
|
source-page="chat"
|
||||||
:chat-log-id="page.currentGeneralFeedbackChatLogId"
|
:chat-log-id="page.currentGeneralFeedbackChatLogId"
|
||||||
@submitted="onFeedbackSubmitted"
|
@submitted="onFeedbackSubmitted"
|
||||||
|
|||||||
@@ -7,12 +7,19 @@
|
|||||||
* 助手 Markdown 排版在本组件内收口:全局 base 只恢复标题字重,列表序号/圆点、
|
* 助手 Markdown 排版在本组件内收口:全局 base 只恢复标题字重,列表序号/圆点、
|
||||||
* 层级缩进与标题字号层级由 scoped 样式统一补齐,避免回答渲染成无结构平铺文本。
|
* 层级缩进与标题字号层级由 scoped 样式统一补齐,避免回答渲染成无结构平铺文本。
|
||||||
* 兼容:同时承接采购合同审查、库存映射、订单提取和 Mermaid 展示。
|
* 兼容:同时承接采购合同审查、库存映射、订单提取和 Mermaid 展示。
|
||||||
|
* 知识库未命中兜底回复按原始 content 检测触发标记,在正文下方渲染【知识库内容清单】按钮,
|
||||||
|
* 点击后弹窗展示常用问题「能力清单条目」标准答案。
|
||||||
*/
|
*/
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, nextTick, onMounted, ref, watch } from 'vue';
|
import { computed, nextTick, onMounted, ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
import { BookOpen, Check, Copy, Download, Edit2, Eye, LayoutGrid, MessageSquareText, RotateCw, X } from 'lucide-vue-next';
|
||||||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||||||
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
|
import { useChatStore } from '../../stores/chat.store';
|
||||||
|
import { getAgentCapabilityList } from '../../api/chat.api';
|
||||||
|
import { hasCapabilityListTrigger } from '../../utils/capabilityList';
|
||||||
|
import type { ChatCapabilityListEntry } from '../../types/chat.types';
|
||||||
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
|
||||||
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
|
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
|
||||||
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
|
import MaintenanceDeviceResultCard from './MaintenanceDeviceResultCard.vue';
|
||||||
@@ -216,6 +223,45 @@ watch(renderedMarkdown, () => { void renderMermaidCharts(); });
|
|||||||
const inlineDownloadFiles = computed(() => (
|
const inlineDownloadFiles = computed(() => (
|
||||||
message.role === 'assistant' ? handlers.getInlineDownloadFiles(message.content).files : []
|
message.role === 'assistant' ? handlers.getInlineDownloadFiles(message.content).files : []
|
||||||
));
|
));
|
||||||
|
|
||||||
|
// [知识库内容清单]:触发检测基于原始 content(标记剥离只发生在展示文本层),历史会话同样生效。
|
||||||
|
const chatStore = useChatStore();
|
||||||
|
const { error: showCapabilityError } = useMessage();
|
||||||
|
const capabilityListButtonVisible = computed(() => (
|
||||||
|
message.role === 'assistant' && hasCapabilityListTrigger(message.content)
|
||||||
|
));
|
||||||
|
const capabilityListLoading = ref(false);
|
||||||
|
const capabilityListEntry = ref<ChatCapabilityListEntry | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 拉取并打开知识库内容清单弹窗。
|
||||||
|
* AI 触发时机:知识库未命中兜底回复正文下方的【知识库内容清单】按钮被点击时调用。
|
||||||
|
* 核心逻辑:按当前会话应用(chatStore.currentAgentId)请求常用问题「能力清单条目」标准答案,
|
||||||
|
* 成功后以弹窗展示;失败时优先复用 requestJson 抛出 BusinessError 的错误码本地化文案。
|
||||||
|
* 参数约束:agentId 一律取自路由级 chat store,组件不接收外部传入的应用 ID,禁止跨应用查询。
|
||||||
|
*/
|
||||||
|
async function openCapabilityListDialog(): Promise<void> {
|
||||||
|
if (capabilityListLoading.value) return;
|
||||||
|
const agentId = Number(chatStore.currentAgentId || 0);
|
||||||
|
if (!agentId) {
|
||||||
|
showCapabilityError(t('chat.capabilityList.notFound'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
capabilityListLoading.value = true;
|
||||||
|
try {
|
||||||
|
capabilityListEntry.value = await getAgentCapabilityList(agentId);
|
||||||
|
} catch (error) {
|
||||||
|
showCapabilityError(error instanceof Error ? error.message : t('chat.capabilityList.notFound'));
|
||||||
|
} finally {
|
||||||
|
capabilityListLoading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 关闭知识库内容清单弹窗并清空条目,避免下次打开闪现旧内容。 */
|
||||||
|
function closeCapabilityListDialog(): void {
|
||||||
|
capabilityListEntry.value = null;
|
||||||
|
}
|
||||||
|
|
||||||
const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() => ({
|
const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() => ({
|
||||||
getPayload: shippingHandlers.getParseReviewPayload,
|
getPayload: shippingHandlers.getParseReviewPayload,
|
||||||
updateHeader: shippingHandlers.updateHeader,
|
updateHeader: shippingHandlers.updateHeader,
|
||||||
@@ -865,6 +911,18 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div v-if="capabilityListButtonVisible" class="mt-4">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-60"
|
||||||
|
:disabled="capabilityListLoading"
|
||||||
|
@click="openCapabilityListDialog"
|
||||||
|
>
|
||||||
|
<BookOpen class="h-3.5 w-3.5" />
|
||||||
|
{{ $t('chat.capabilityList.button') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -1135,6 +1193,31 @@ function handleInlineDownload(file: InlineDownloadFile): void {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</Teleport>
|
</Teleport>
|
||||||
|
<Teleport to="body">
|
||||||
|
<div
|
||||||
|
v-if="capabilityListEntry"
|
||||||
|
class="dialog-overlay z-[130] items-center"
|
||||||
|
@click.self="closeCapabilityListDialog"
|
||||||
|
>
|
||||||
|
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,760px)] flex-col">
|
||||||
|
<div class="dialog-header">
|
||||||
|
<div>
|
||||||
|
<h3 class="section-title">{{ $t('chat.capabilityList.dialogTitle') }}</h3>
|
||||||
|
<p class="section-desc mt-1">{{ capabilityListEntry.title }}</p>
|
||||||
|
</div>
|
||||||
|
<button type="button" class="btn-icon-ds" :aria-label="$t('common.close')" @click="closeCapabilityListDialog">
|
||||||
|
<X class="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="dialog-body min-h-0 flex-1 overflow-auto border-t-0 pt-4">
|
||||||
|
<div
|
||||||
|
class="markdown-body chat-markdown min-w-0 break-words text-sm leading-relaxed"
|
||||||
|
v-html="handlers.renderMarkdown(capabilityListEntry.answer)"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<style scoped>
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
parseFileCheckExcelRunId,
|
parseFileCheckExcelRunId,
|
||||||
rewriteFileCheckExcelLinksForDisplay,
|
rewriteFileCheckExcelLinksForDisplay,
|
||||||
} from '../utils/fileCheckExcelDownload';
|
} from '../utils/fileCheckExcelDownload';
|
||||||
|
import { stripCapabilityListMarker } from '../utils/capabilityList';
|
||||||
|
|
||||||
marked.setOptions({ gfm: true, breaks: true });
|
marked.setOptions({ gfm: true, breaks: true });
|
||||||
|
|
||||||
@@ -472,7 +473,9 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。
|
* 将聊天正文转换为展示 HTML,并在渲染前剥离内嵌文件 JSON 块。
|
||||||
* 核心逻辑:先抽取 FILE_START/FILE_END 文件,再走既有 Markdown 清洗与 marked 渲染,保证聊天气泡只展示可读文本。
|
* 核心逻辑:先抽取 FILE_START/FILE_END 文件,再剥离知识库未命中兜底回复的 [知识库能力清单]
|
||||||
|
* 触发标记(按钮由 ChatMessageBubble 按原始 content 渲染),最后走既有 Markdown 清洗与
|
||||||
|
* marked 渲染,保证聊天气泡只展示可读文本。
|
||||||
* @param text - 原始聊天文本。
|
* @param text - 原始聊天文本。
|
||||||
* @returns 供 v-html 使用的安全展示字符串。
|
* @returns 供 v-html 使用的安全展示字符串。
|
||||||
*/
|
*/
|
||||||
@@ -480,7 +483,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
|
|||||||
if (!text) return '';
|
if (!text) return '';
|
||||||
const extracted = safeExtractInlineDownloadFiles(text);
|
const extracted = safeExtractInlineDownloadFiles(text);
|
||||||
const displayText = rewriteFileCheckExcelLinksForDisplay(
|
const displayText = rewriteFileCheckExcelLinksForDisplay(
|
||||||
ctx.prepareMarkdownDisplayText(extracted.cleanedText),
|
ctx.prepareMarkdownDisplayText(stripCapabilityListMarker(extracted.cleanedText)),
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
const rendered = marked.parse(displayText, { renderer: chatMarkdownRenderer });
|
const rendered = marked.parse(displayText, { renderer: chatMarkdownRenderer });
|
||||||
|
|||||||
@@ -373,3 +373,12 @@ export interface ChatQueryPreviewPage {
|
|||||||
has_more: boolean;
|
has_more: boolean;
|
||||||
query?: string;
|
query?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 知识库内容清单条目:常用问题中「<应用名>·能力清单条目」的标准答案(GET /api/chat/capability-list)。 */
|
||||||
|
export interface ChatCapabilityListEntry {
|
||||||
|
id: number;
|
||||||
|
agent_id: number;
|
||||||
|
title: string;
|
||||||
|
question: string;
|
||||||
|
answer: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/**
|
||||||
|
* features/chat/utils/capabilityList.spec.ts
|
||||||
|
* 用途:验证知识库未命中兜底回复的触发识别与标记剥离规则。
|
||||||
|
* 依赖:vitest、capabilityList 纯函数。
|
||||||
|
* 逻辑:覆盖完整标记、兼容写法、历史无标记兜底原句、流式半截标记与普通消息不误伤五类场景。
|
||||||
|
*/
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { hasCapabilityListTrigger, stripCapabilityListMarker } from './capabilityList';
|
||||||
|
|
||||||
|
describe('hasCapabilityListTrigger', () => {
|
||||||
|
it('命中完整标记(圈2 草稿形态)', () => {
|
||||||
|
expect(hasCapabilityListTrigger('持续补充; [知识库能力清单]。')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('兼容「内容清单」写法', () => {
|
||||||
|
expect(hasCapabilityListTrigger('持续补充;[知识库内容清单]。')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('命中无标记的历史兜底原句(圈1 已发布形态)', () => {
|
||||||
|
expect(hasCapabilityListTrigger(
|
||||||
|
'这个问题超出了当前知识库的收录范围,所以没能找到答案。欢迎点击页面左下角的【意见反馈】按钮,把想查询的内容告诉我们,我们会根据反馈持续补充;',
|
||||||
|
)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('流式阶段未闭合的半截标记也视为触发', () => {
|
||||||
|
expect(hasCapabilityListTrigger('持续补充; [知识库能力清')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('普通回答不误伤', () => {
|
||||||
|
expect(hasCapabilityListTrigger('公司年假共 10 天,请查看 [考勤制度] 文档。')).toBe(false);
|
||||||
|
expect(hasCapabilityListTrigger('')).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('stripCapabilityListMarker', () => {
|
||||||
|
it('剥离完整标记并清理前导分号与句末句号', () => {
|
||||||
|
expect(stripCapabilityListMarker('我们会根据反馈持续补充; [知识库能力清单]。'))
|
||||||
|
.toBe('我们会根据反馈持续补充');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('剥离中文分号与句号组合', () => {
|
||||||
|
expect(stripCapabilityListMarker('我们会根据反馈持续补充;[知识库内容清单]。'))
|
||||||
|
.toBe('我们会根据反馈持续补充');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('裁剪流式阶段未闭合的半截标记', () => {
|
||||||
|
expect(stripCapabilityListMarker('我们会根据反馈持续补充; [知识库能力清'))
|
||||||
|
.toBe('我们会根据反馈持续补充;');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('无标记文本原样返回', () => {
|
||||||
|
const text = '这个问题超出了当前知识库的收录范围,所以没能找到答案。';
|
||||||
|
expect(stripCapabilityListMarker(text)).toBe(text);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
/**
|
||||||
|
* features/chat/utils/capabilityList.ts
|
||||||
|
* 用途:识别 Dify 知识库未命中兜底回复中的「知识库内容清单」触发条件,并负责展示文本清洗。
|
||||||
|
* 依赖:无(纯函数,供 useChatPageMarkdown 与 ChatMessageBubble 复用)。
|
||||||
|
* 逻辑:Dify「直接回复」节点在兜底语句末尾追加 [知识库能力清单] 标记时,前端据此渲染按钮并
|
||||||
|
* 从正文剥离标记;对未加标记的已发布兜底语句(旧回复、历史会话),按兜底语句稳定特征
|
||||||
|
* 片段兜底识别。检测作用于原始 content,剥离只影响 Markdown 展示文本。
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Dify 兜底回复末尾的触发标记,兼容「能力清单 / 内容清单」两种写法及其前导标点与句末句号。 */
|
||||||
|
const CAPABILITY_LIST_MARKER_REGEX = /\s*[;;,,、]?\s*\[知识库(?:能力|内容)清单\]\s*。?/g;
|
||||||
|
|
||||||
|
/** 流式渲染阶段可能只到达一半的未闭合标记(如「[知识库能力清」),按前缀裁剪避免原始符号闪现。 */
|
||||||
|
const CAPABILITY_LIST_MARKER_PARTIAL_REGEX = /\s*\[知识库[^[\]]*$/;
|
||||||
|
|
||||||
|
/** 已上线兜底语句的稳定特征片段(圈1 原句「这个问题超出了当前知识库的收录范围…」)。 */
|
||||||
|
const KB_FALLBACK_PHRASE = '超出了当前知识库的收录范围';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断一条助手消息是否应展示【知识库内容清单】按钮。
|
||||||
|
* AI 触发时机:渲染助手消息正文下方按钮前调用,用于决定按钮显隐。
|
||||||
|
* 核心逻辑:命中完整标记(含流式半截标记)或兜底语句特征片段即视为触发;用户消息由调用方
|
||||||
|
* 保证不进入本判断。
|
||||||
|
* 参数约束:传入消息原始 content(未剥标记),禁止传入已渲染 HTML。
|
||||||
|
* @param content - 消息原始文本。
|
||||||
|
* @returns 是否展示【知识库内容清单】按钮。
|
||||||
|
*/
|
||||||
|
export function hasCapabilityListTrigger(content: string): boolean {
|
||||||
|
const raw = String(content || '');
|
||||||
|
if (!raw) return false;
|
||||||
|
if (raw.includes(KB_FALLBACK_PHRASE)) return true;
|
||||||
|
return /\[知识库(?:能力|内容)清单\]/.test(raw) || /\[知识库[^[\]]*$/.test(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从展示文本中剥离「知识库内容清单」触发标记,保留其余正文。
|
||||||
|
* 核心逻辑:先移除完整标记(连同其前导标点与句末句号,避免留下「; 。」类残渣),再裁剪
|
||||||
|
* 流式阶段未闭合的半截标记;无标记时原样返回。
|
||||||
|
* 参数约束:仅用于 Markdown 渲染前的展示文本清洗,不落库、不回写消息 content。
|
||||||
|
* @param text - 待渲染的展示文本。
|
||||||
|
* @returns 剥离标记后的展示文本。
|
||||||
|
*/
|
||||||
|
export function stripCapabilityListMarker(text: string): string {
|
||||||
|
const raw = String(text || '');
|
||||||
|
if (!raw) return '';
|
||||||
|
return raw.replace(CAPABILITY_LIST_MARKER_REGEX, '').replace(CAPABILITY_LIST_MARKER_PARTIAL_REGEX, '');
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@
|
|||||||
* 配置只保存天数和系统用户,不保存发送时刻。
|
* 配置只保存天数和系统用户,不保存发送时刻。
|
||||||
* 保存配置自行声明 Content-Type: application/json,供 Flask get_json 解析。
|
* 保存配置自行声明 Content-Type: application/json,供 Flask get_json 解析。
|
||||||
* 发送记录只读已落库的行。每位收件人的 Excel 可再下载。
|
* 发送记录只读已落库的行。每位收件人的 Excel 可再下载。
|
||||||
|
* 扫描/发送改为入队,再用 jobs 接口轮询结果,避免 Nginx 504。
|
||||||
*/
|
*/
|
||||||
import { requestBlob, requestJson } from '@/shared/api/client';
|
import { requestBlob, requestJson } from '@/shared/api/client';
|
||||||
|
|
||||||
@@ -126,33 +127,43 @@ export function syncEquipmentAcceptance() {
|
|||||||
return requestJson<EquipmentAcceptanceSyncResult>('/api/equipment-acceptance/sync', { method: 'POST' });
|
return requestJson<EquipmentAcceptanceSyncResult>('/api/equipment-acceptance/sync', { method: 'POST' });
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface EquipmentAcceptanceScanResult {
|
export interface EquipmentAcceptanceJob {
|
||||||
created: number;
|
id: number;
|
||||||
updated: number;
|
status: string;
|
||||||
cancelled: number;
|
message?: string | null;
|
||||||
}
|
result?: {
|
||||||
|
created?: number;
|
||||||
export interface EquipmentAcceptanceSendResult {
|
updated?: number;
|
||||||
sent: number;
|
cancelled?: number;
|
||||||
failed: number;
|
sent?: number;
|
||||||
records_sent: number;
|
failed?: number;
|
||||||
records_failed: number;
|
records_sent?: number;
|
||||||
|
records_failed?: number;
|
||||||
|
} | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 管理员立即同步 E10 并生成待发送记录。
|
* 管理员将扫描任务入队(Worker 同步并生成待发送,不发企微)。
|
||||||
* @returns 新增、更新和取消条数
|
* @returns 后台任务主键
|
||||||
*/
|
*/
|
||||||
export function scanEquipmentAcceptanceAlerts() {
|
export function enqueueEquipmentAcceptanceAlertScan() {
|
||||||
return requestJson<EquipmentAcceptanceScanResult>('/api/equipment-acceptance/alerts/scan', { method: 'POST' });
|
return requestJson<{ job_id: number }>('/api/equipment-acceptance/alerts/scan', { method: 'POST' });
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 管理员立即把待发送记录按收件人发到企业微信。
|
* 管理员将发送任务入队(Worker 按收件人发企微后改状态)。
|
||||||
* @returns 成功和失败的收件人数
|
* @returns 后台任务主键
|
||||||
*/
|
*/
|
||||||
export function sendEquipmentAcceptanceAlerts() {
|
export function enqueueEquipmentAcceptanceAlertSend() {
|
||||||
return requestJson<EquipmentAcceptanceSendResult>('/api/equipment-acceptance/alerts/send', { method: 'POST' });
|
return requestJson<{ job_id: number }>('/api/equipment-acceptance/alerts/send', { method: 'POST' });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询本人提交的设备验收后台任务状态。
|
||||||
|
* @param jobId - jobs 表主键
|
||||||
|
*/
|
||||||
|
export function getEquipmentAcceptanceJob(jobId: number) {
|
||||||
|
return requestJson<EquipmentAcceptanceJob>(`/api/equipment-acceptance/jobs/${jobId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface EquipmentAcceptanceSendRecord {
|
export interface EquipmentAcceptanceSendRecord {
|
||||||
|
|||||||
+80
-18
@@ -6,6 +6,7 @@
|
|||||||
本文件引入 Element 样式并包住 ElConfigProvider。标题和页签压到两行,下面整块留给当前页。
|
本文件引入 Element 样式并包住 ElConfigProvider。标题和页签压到两行,下面整块留给当前页。
|
||||||
view=config 打开预警配置;view=sends 打开发送记录;orderId 只在停留列表下钻。
|
view=config 打开预警配置;view=sends 打开发送记录;orderId 只在停留列表下钻。
|
||||||
同步只在停留列表。扫描和发送只在发送记录,且仅平台管理员可见。
|
同步只在停留列表。扫描和发送只在发送记录,且仅平台管理员可见。
|
||||||
|
扫描与发送改为入队后轮询 Job,避免长请求被 Nginx 504。
|
||||||
-->
|
-->
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
@@ -27,9 +28,11 @@ import { useAuthStore } from '@/features/auth/stores/auth.store';
|
|||||||
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
|
||||||
import { useMessage } from '@/shared/composables/useMessage';
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
import {
|
import {
|
||||||
scanEquipmentAcceptanceAlerts,
|
enqueueEquipmentAcceptanceAlertScan,
|
||||||
sendEquipmentAcceptanceAlerts,
|
enqueueEquipmentAcceptanceAlertSend,
|
||||||
|
getEquipmentAcceptanceJob,
|
||||||
syncEquipmentAcceptance,
|
syncEquipmentAcceptance,
|
||||||
|
type EquipmentAcceptanceJob,
|
||||||
} from '../api/equipment-acceptance.api';
|
} from '../api/equipment-acceptance.api';
|
||||||
import EquipmentAcceptanceConfigPage from '../views/EquipmentAcceptanceConfigPage.vue';
|
import EquipmentAcceptanceConfigPage from '../views/EquipmentAcceptanceConfigPage.vue';
|
||||||
import EquipmentAcceptanceDetailPage from '../views/EquipmentAcceptanceDetailPage.vue';
|
import EquipmentAcceptanceDetailPage from '../views/EquipmentAcceptanceDetailPage.vue';
|
||||||
@@ -38,6 +41,10 @@ import EquipmentAcceptanceSendsPage from '../views/EquipmentAcceptanceSendsPage.
|
|||||||
|
|
||||||
type WorkspaceView = 'ledger' | 'sends' | 'config';
|
type WorkspaceView = 'ledger' | 'sends' | 'config';
|
||||||
|
|
||||||
|
const JOB_POLL_MS = 2000;
|
||||||
|
const JOB_TIMEOUT_MS = 600_000;
|
||||||
|
const JOB_DONE = new Set(['success', 'failed', 'dead', 'cancelled']);
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -49,6 +56,68 @@ const runningAction = ref<'scan' | 'send' | null>(null);
|
|||||||
const listPage = ref<{ reload: () => Promise<void> } | null>(null);
|
const listPage = ref<{ reload: () => Promise<void> } | null>(null);
|
||||||
const sendsPage = ref<{ reload: () => Promise<void> } | null>(null);
|
const sendsPage = ref<{ reload: () => Promise<void> } | null>(null);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 轮询后台任务直到终态或超时。
|
||||||
|
* 核心逻辑:入队接口立即返回;真正扫描/发送在 schedule worker 里,不能把「已提交」当成完成。
|
||||||
|
* @param jobId - 刚入队的任务主键
|
||||||
|
* @returns 终态任务;超时返回 null
|
||||||
|
*/
|
||||||
|
async function waitForJob(jobId: number): Promise<EquipmentAcceptanceJob | null> {
|
||||||
|
const deadline = Date.now() + JOB_TIMEOUT_MS;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
const job = await getEquipmentAcceptanceJob(jobId);
|
||||||
|
if (JOB_DONE.has(job.status)) return job;
|
||||||
|
await new Promise((resolve) => window.setTimeout(resolve, JOB_POLL_MS));
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按扫描任务结果提示。
|
||||||
|
* @param job - 已结束的任务;null 表示仍在后台跑
|
||||||
|
*/
|
||||||
|
function reportScanJob(job: EquipmentAcceptanceJob | null): void {
|
||||||
|
if (!job) {
|
||||||
|
msg.warning(t('admin.equipmentAcceptance.jobTimeout'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (job.status !== 'success') {
|
||||||
|
msg.error(job.message || t('admin.equipmentAcceptance.jobError'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
msg.success(t('admin.equipmentAcceptance.scanDone', {
|
||||||
|
created: Number(job.result?.created || 0),
|
||||||
|
updated: Number(job.result?.updated || 0),
|
||||||
|
cancelled: Number(job.result?.cancelled || 0),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按发送任务结果提示。
|
||||||
|
* @param job - 已结束的任务;null 表示仍在后台跑
|
||||||
|
*/
|
||||||
|
function reportSendJob(job: EquipmentAcceptanceJob | null): void {
|
||||||
|
if (!job) {
|
||||||
|
msg.warning(t('admin.equipmentAcceptance.jobTimeout'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (job.status !== 'success') {
|
||||||
|
msg.error(job.message || t('admin.equipmentAcceptance.jobError'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const sent = Number(job.result?.sent || 0);
|
||||||
|
const failed = Number(job.result?.failed || 0);
|
||||||
|
if (sent > 0 && failed > 0) {
|
||||||
|
msg.warning(t('admin.equipmentAcceptance.sendPartial', { sent, failed }));
|
||||||
|
} else if (failed > 0) {
|
||||||
|
msg.error(t('admin.equipmentAcceptance.sendFailedCount', { failed }));
|
||||||
|
} else if (sent > 0) {
|
||||||
|
msg.success(t('admin.equipmentAcceptance.sendDone', { sent, failed: 0 }));
|
||||||
|
} else {
|
||||||
|
msg.info(t('admin.equipmentAcceptance.sendEmpty'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const isAdmin = computed(() => Boolean(auth.isAdmin));
|
const isAdmin = computed(() => Boolean(auth.isAdmin));
|
||||||
const activeView = computed<WorkspaceView>(() => {
|
const activeView = computed<WorkspaceView>(() => {
|
||||||
if (route.query.view === 'config') return 'config';
|
if (route.query.view === 'config') return 'config';
|
||||||
@@ -105,8 +174,8 @@ function onTabChange(name: string | number): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 管理员在发送记录页确认后立即扫描或发送。
|
* 管理员在发送记录页确认后,将扫描或发送入队并等待 Worker。
|
||||||
* 核心逻辑:确认框取消会拒绝,这里直接返回。扫描会同步 E10;发送把待发送记录推到企业微信。
|
* 核心逻辑:确认框取消直接返回。入队后轮询 Job,完成再刷新列表并按 sent/failed 提示。
|
||||||
* @param action - scan 或 send
|
* @param action - scan 或 send
|
||||||
*/
|
*/
|
||||||
async function askAlert(action: 'scan' | 'send'): Promise<void> {
|
async function askAlert(action: 'scan' | 'send'): Promise<void> {
|
||||||
@@ -125,21 +194,14 @@ async function askAlert(action: 'scan' | 'send'): Promise<void> {
|
|||||||
}
|
}
|
||||||
runningAction.value = action;
|
runningAction.value = action;
|
||||||
try {
|
try {
|
||||||
if (action === 'scan') {
|
const queued = action === 'scan'
|
||||||
const result = await scanEquipmentAcceptanceAlerts();
|
? await enqueueEquipmentAcceptanceAlertScan()
|
||||||
msg.success(t('admin.equipmentAcceptance.scanDone', {
|
: await enqueueEquipmentAcceptanceAlertSend();
|
||||||
created: result.created,
|
msg.info(t('admin.equipmentAcceptance.jobSubmitted'));
|
||||||
updated: result.updated,
|
const job = await waitForJob(Number(queued.job_id));
|
||||||
cancelled: result.cancelled,
|
|
||||||
}));
|
|
||||||
} else {
|
|
||||||
const result = await sendEquipmentAcceptanceAlerts();
|
|
||||||
msg.success(t('admin.equipmentAcceptance.sendDone', {
|
|
||||||
sent: result.sent,
|
|
||||||
failed: result.failed,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
await sendsPage.value?.reload();
|
await sendsPage.value?.reload();
|
||||||
|
if (action === 'scan') reportScanJob(job);
|
||||||
|
else reportSendJob(job);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.syncFailed'));
|
msg.error(error instanceof BusinessError ? error.message : t('admin.equipmentAcceptance.syncFailed'));
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
/**
|
/**
|
||||||
* features/kb/components/KbJobQueuePanel.vue
|
* features/kb/components/KbJobQueuePanel.vue
|
||||||
* 知识库任务队列展示面板。
|
* 用途:知识库任务队列展示面板。
|
||||||
* 依赖:kb.api 的 KbJob 类型、Vue I18n、lucide-vue-next 图标。
|
* 依赖:kb.api 的 KbJob 类型、Vue I18n、Element Plus 按钮与标签。样式由引用它的页面引入。
|
||||||
* 逻辑:只负责渲染任务列表和触发执行事件;任务执行、反馈和刷新由父级 KbAdminPanel 处理。
|
* 逻辑:只负责渲染任务列表和触发执行事件;任务执行、反馈和刷新由父级处理。
|
||||||
*/
|
*/
|
||||||
|
import { VideoPlay } from '@element-plus/icons-vue';
|
||||||
import { Play } from 'lucide-vue-next';
|
import { ElButton, ElTag } from 'element-plus';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import type { KbJob } from '../api/kb.api';
|
import type { KbJob } from '../api/kb.api';
|
||||||
|
|
||||||
@@ -21,15 +21,33 @@ const emit = defineEmits<{
|
|||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
/** 判断任务是否允许手动执行,避免模板里重复硬编码任务类型条件。 */
|
/**
|
||||||
|
* 判断任务是否允许手动执行,避免模板里重复硬编码任务类型条件。
|
||||||
|
* @param job - 队列中的一条任务
|
||||||
|
* @returns 清洗或同步且尚未成功时为 true
|
||||||
|
*/
|
||||||
const canRunJob = (job: KbJob): boolean => ['clean', 'sync_dify'].includes(job.job_type) && job.status !== 'success';
|
const canRunJob = (job: KbJob): boolean => ['clean', 'sync_dify'].includes(job.job_type) && job.status !== 'success';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把任务状态映射成 Element 标签类型。
|
||||||
|
* 核心逻辑:成功为绿,失败为危险,排队或执行中为警告,其余为信息。
|
||||||
|
* @param status - 任务状态原文
|
||||||
|
* @returns ElTag 的 type
|
||||||
|
*/
|
||||||
|
function jobTagType(status: string): 'success' | 'warning' | 'danger' | 'info' {
|
||||||
|
const normalized = String(status || '').toLowerCase();
|
||||||
|
if (['success', 'synced', 'cleaned'].includes(normalized)) return 'success';
|
||||||
|
if (['failed', 'error'].includes(normalized)) return 'danger';
|
||||||
|
if (['running', 'processing', 'queued'].includes(normalized)) return 'warning';
|
||||||
|
return 'info';
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<section class="kb-admin-section">
|
<section class="kb-admin-section">
|
||||||
<div class="mb-4 flex items-center justify-between">
|
<div class="mb-4 flex items-center justify-between">
|
||||||
<h3 class="section-title">{{ t('kbAdmin.jobsTitle') }}</h3>
|
<h3 class="section-title">{{ t('kbAdmin.jobsTitle') }}</h3>
|
||||||
<span class="text-xs text-muted">/api/kb/jobs</span>
|
<span>/api/kb/jobs</span>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="jobs.length === 0" class="kb-admin-empty">
|
<div v-if="jobs.length === 0" class="kb-admin-empty">
|
||||||
{{ t('kbAdmin.jobsEmpty') }}
|
{{ t('kbAdmin.jobsEmpty') }}
|
||||||
@@ -38,25 +56,24 @@ const canRunJob = (job: KbJob): boolean => ['clean', 'sync_dify'].includes(job.j
|
|||||||
<div v-for="job in jobs" :key="job.id" class="kb-admin-card">
|
<div v-for="job in jobs" :key="job.id" class="kb-admin-card">
|
||||||
<div class="flex items-start justify-between gap-3">
|
<div class="flex items-start justify-between gap-3">
|
||||||
<div class="min-w-0">
|
<div class="min-w-0">
|
||||||
<div class="font-semibold text-primary">{{ job.job_type }}</div>
|
<div>{{ job.job_type }}</div>
|
||||||
<div class="mt-1 text-sm text-muted">{{ job.created_at || '--' }}</div>
|
<div class="mt-1">{{ job.created_at || '--' }}</div>
|
||||||
<div class="mt-2 text-sm text-muted">{{ job.message || t('kbAdmin.noJobMessage') }}</div>
|
<div class="mt-2">{{ job.message || t('kbAdmin.noJobMessage') }}</div>
|
||||||
<div class="mt-2 text-xs text-muted">
|
<div class="mt-2">
|
||||||
{{ t('kbAdmin.jobMeta', { docId: job.document_id ?? '--', versionId: job.document_version_id ?? '--', progress: job.progress ?? 0 }) }}
|
{{ t('kbAdmin.jobMeta', { docId: job.document_id ?? '--', versionId: job.document_version_id ?? '--', progress: job.progress ?? 0 }) }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<span class="kb-admin-badge">{{ job.status }}</span>
|
<ElTag effect="light" :type="jobTagType(job.status)">{{ job.status }}</ElTag>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="canRunJob(job)" class="mt-3 flex justify-end">
|
<div v-if="canRunJob(job)" class="mt-3 flex justify-end">
|
||||||
<button
|
<ElButton
|
||||||
type="button"
|
:icon="VideoPlay"
|
||||||
class="inline-flex items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60"
|
:loading="runningJobId === job.id"
|
||||||
:disabled="runningJobId === job.id"
|
:disabled="runningJobId === job.id"
|
||||||
@click="emit('run-job', job)"
|
@click="emit('run-job', job)"
|
||||||
>
|
>
|
||||||
<Play class="h-3.5 w-3.5" />
|
|
||||||
{{ runningJobId === job.id ? t('kbAdmin.running') : t('kbAdmin.runJob') }}
|
{{ runningJobId === job.id ? t('kbAdmin.running') : t('kbAdmin.runJob') }}
|
||||||
</button>
|
</ElButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -1,12 +1,13 @@
|
|||||||
/**
|
/**
|
||||||
* features/kb/composables/kb-workspace/kb-workspace.state.ts
|
* features/kb/composables/kb-workspace/kb-workspace.state.ts
|
||||||
* 用途:作业面共享响应式状态;各子 composable 通过同一 state 读写,避免重复 ref。
|
* 用途:作业面共享响应式状态;各子 composable 通过同一 state 读写,避免重复 ref。
|
||||||
* 依赖:vue-router、vue-i18n、auth、kb.api 类型、kb-workspace.types。
|
* 依赖:vue-router、vue-i18n、Element Plus ElMessageBox、auth、kb.api 类型、kb-workspace.types。
|
||||||
* 逻辑:createKbWorkspaceState 产出全部 ref;含公共确认弹窗(删除/上传路径等)辅助方法。
|
* 逻辑:createKbWorkspaceState 产出全部 ref;删除与路径确认走 ElMessageBox.confirm,取消时不执行回调。
|
||||||
*/
|
*/
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import { useRouter } from 'vue-router';
|
import { useRouter } from 'vue-router';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { ElMessageBox } from 'element-plus';
|
||||||
import { getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth';
|
import { getStoredAuthUser, isPlatformAdminUser } from '@/shared/utils/auth';
|
||||||
import type {
|
import type {
|
||||||
KbDocumentItem,
|
KbDocumentItem,
|
||||||
@@ -55,12 +56,6 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
|
|||||||
const showFailureModal = ref(false);
|
const showFailureModal = ref(false);
|
||||||
const showPathUploadModal = ref(false);
|
const showPathUploadModal = ref(false);
|
||||||
const showPathUploadHistoryModal = ref(false);
|
const showPathUploadHistoryModal = ref(false);
|
||||||
const showDeleteConfirmDialog = ref(false);
|
|
||||||
const deleteConfirmMessage = ref('');
|
|
||||||
const deleteConfirmTitle = ref('');
|
|
||||||
const deleteConfirmText = ref('');
|
|
||||||
const deleteConfirmTone = ref<'danger' | 'primary'>('danger');
|
|
||||||
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
|
|
||||||
const showPathUploadDetails = ref(false);
|
const showPathUploadDetails = ref(false);
|
||||||
const fileInputRef = ref<HTMLInputElement | null>(null);
|
const fileInputRef = ref<HTMLInputElement | null>(null);
|
||||||
const pathUploadInputRef = ref<HTMLInputElement | null>(null);
|
const pathUploadInputRef = ref<HTMLInputElement | null>(null);
|
||||||
@@ -118,14 +113,15 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
|
|||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 打开公共确认弹窗(删除 / 上传路径等场景复用)。
|
* 弹出 Element 确认框,确认后再执行删除或写入路径清单。
|
||||||
|
* 核心逻辑:ElMessageBox.confirm 在取消或关闭时 reject,catch 后直接返回,不调用 onConfirm。
|
||||||
* @param message - 正文
|
* @param message - 正文
|
||||||
* @param onConfirm - 确认回调
|
* @param onConfirm - 用户确认后的回调
|
||||||
* @param options.title - 标题;空则用删除默认文案
|
* @param options.title - 标题;空则用删除默认文案
|
||||||
* @param options.confirmText - 确认按钮文案
|
* @param options.confirmText - 确认按钮文案
|
||||||
* @param options.confirmTone - danger 删除 / primary 非破坏性确认
|
* @param options.confirmTone - danger 删除 / primary 非破坏性确认
|
||||||
*/
|
*/
|
||||||
const openDeleteConfirmDialog = (
|
const openDeleteConfirmDialog = async (
|
||||||
message: string,
|
message: string,
|
||||||
onConfirm: () => Promise<void> | void,
|
onConfirm: () => Promise<void> | void,
|
||||||
options?: {
|
options?: {
|
||||||
@@ -134,33 +130,29 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
|
|||||||
confirmTone?: 'danger' | 'primary';
|
confirmTone?: 'danger' | 'primary';
|
||||||
},
|
},
|
||||||
) => {
|
) => {
|
||||||
deleteConfirmMessage.value = message;
|
const tone = options?.confirmTone || 'danger';
|
||||||
deleteConfirmTitle.value = options?.title || '';
|
|
||||||
deleteConfirmText.value = options?.confirmText || '';
|
|
||||||
deleteConfirmTone.value = options?.confirmTone || 'danger';
|
|
||||||
pendingDeleteAction = onConfirm;
|
|
||||||
showDeleteConfirmDialog.value = true;
|
|
||||||
};
|
|
||||||
|
|
||||||
const closeDeleteConfirmDialog = () => {
|
|
||||||
showDeleteConfirmDialog.value = false;
|
|
||||||
deleteConfirmMessage.value = '';
|
|
||||||
deleteConfirmTitle.value = '';
|
|
||||||
deleteConfirmText.value = '';
|
|
||||||
deleteConfirmTone.value = 'danger';
|
|
||||||
pendingDeleteAction = null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDeleteConfirm = async () => {
|
|
||||||
if (!pendingDeleteAction) return;
|
|
||||||
try {
|
try {
|
||||||
await pendingDeleteAction();
|
await ElMessageBox.confirm(
|
||||||
|
message,
|
||||||
|
options?.title || t('common.deleteDialog.defaultTitle'),
|
||||||
|
{
|
||||||
|
type: tone === 'primary' ? 'info' : 'warning',
|
||||||
|
confirmButtonText: options?.confirmText || t('common.deleteDialog.confirm'),
|
||||||
|
cancelButtonText: t('common.deleteDialog.cancel'),
|
||||||
|
confirmButtonType: tone === 'primary' ? 'primary' : 'danger',
|
||||||
|
closeOnClickModal: false,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await onConfirm();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('[deleteConfirm]', err);
|
console.error('[deleteConfirm]', err);
|
||||||
feedback.value = String(err) || t('kbWorkspace.msg.operationFailed');
|
feedback.value = String(err) || t('kbWorkspace.msg.operationFailed');
|
||||||
feedbackType.value = 'error';
|
feedbackType.value = 'error';
|
||||||
}
|
}
|
||||||
closeDeleteConfirmDialog();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -190,11 +182,6 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
|
|||||||
showFailureModal,
|
showFailureModal,
|
||||||
showPathUploadModal,
|
showPathUploadModal,
|
||||||
showPathUploadHistoryModal,
|
showPathUploadHistoryModal,
|
||||||
showDeleteConfirmDialog,
|
|
||||||
deleteConfirmMessage,
|
|
||||||
deleteConfirmTitle,
|
|
||||||
deleteConfirmText,
|
|
||||||
deleteConfirmTone,
|
|
||||||
showPathUploadDetails,
|
showPathUploadDetails,
|
||||||
fileInputRef,
|
fileInputRef,
|
||||||
pathUploadInputRef,
|
pathUploadInputRef,
|
||||||
@@ -228,8 +215,6 @@ export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions =
|
|||||||
sourceInfoVersions,
|
sourceInfoVersions,
|
||||||
pathUploadTask,
|
pathUploadTask,
|
||||||
openDeleteConfirmDialog,
|
openDeleteConfirmDialog,
|
||||||
closeDeleteConfirmDialog,
|
|
||||||
handleDeleteConfirm,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
/**
|
/**
|
||||||
* features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts
|
* features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts
|
||||||
* 用途:路径上传编排——选目录、分批 job、轮询进度与历史批次操作。
|
* 用途:路径上传编排——选目录、分批 job、轮询进度与历史批次操作。
|
||||||
* 依赖:kb.api、kb-path-upload.utils、DeleteConfirmDialog(经 state.openDeleteConfirmDialog)。
|
* 依赖:kb.api、kb-path-upload.utils、state.openDeleteConfirmDialog(ElMessageBox.confirm)。
|
||||||
* 逻辑:优先 showDirectoryPicker 避免浏览器原生目录确认;回退 webkitdirectory;确认后写入待上传清单。
|
* 逻辑:优先 showDirectoryPicker 避免浏览器原生目录确认;回退 webkitdirectory;确认后写入待上传清单。
|
||||||
*/
|
*/
|
||||||
import type { KbJob } from '../../api/kb.api';
|
import type { KbJob } from '../../api/kb.api';
|
||||||
@@ -231,7 +231,7 @@ export function useKbWorkspacePathUpload(
|
|||||||
/**
|
/**
|
||||||
* 打开目录选择器;优先 showDirectoryPicker(无 Windows 原生上传确认),
|
* 打开目录选择器;优先 showDirectoryPicker(无 Windows 原生上传确认),
|
||||||
* 不支持时回退隐藏 input[webkitdirectory]。
|
* 不支持时回退隐藏 input[webkitdirectory]。
|
||||||
* 选完后用公共 DeleteConfirmDialog 二次确认再写入清单。
|
* 选完后调用 openDeleteConfirmDialog,由 Element 确认框确认后再写入清单;取消则不写入。
|
||||||
*/
|
*/
|
||||||
const triggerPathUploadSelection = async () => {
|
const triggerPathUploadSelection = async () => {
|
||||||
const picker = (window as Window & {
|
const picker = (window as Window & {
|
||||||
@@ -277,7 +277,7 @@ export function useKbWorkspacePathUpload(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 旧版 input[webkitdirectory] 回退:浏览器会先弹原生确认,再进入本回调。
|
* 旧版 input[webkitdirectory] 回退:浏览器会先弹原生确认,再进入本回调。
|
||||||
* 仍用公共确认弹窗二次确认后写入清单。
|
* 仍调用 openDeleteConfirmDialog,由 Element 确认框确认后写入清单;取消则不写入。
|
||||||
*/
|
*/
|
||||||
const handlePathFilesSelected = (event: Event) => {
|
const handlePathFilesSelected = (event: Event) => {
|
||||||
const input = event.target as HTMLInputElement;
|
const input = event.target as HTMLInputElement;
|
||||||
|
|||||||
@@ -1,12 +1,35 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
/**
|
/**
|
||||||
* features/kb/views/KbWorkspaceView.vue
|
* features/kb/views/KbWorkspaceView.vue
|
||||||
* 知识库作业面视图壳:模板与弹窗布局,业务逻辑见 useKbWorkspace。
|
* 用途:知识库作业面视图壳。分组概览、文档列表、路径上传进度与筛选。
|
||||||
|
* 依赖:Element Plus、useKbWorkspace、KbWorkspaceOverlays。样式只在本页入口引入。
|
||||||
|
* 逻辑:业务仍走 useKbWorkspace。按钮、输入、筛选、表格、分页换成 Element;隐藏文件框保留。
|
||||||
|
* 本页没有 PDF/canvas 绘制。Markdown 与源文件操作在 KbWorkspaceOverlays。
|
||||||
*/
|
*/
|
||||||
import { ArrowLeft, BookOpen, ChevronDown, ChevronUp, FileText, Info, RefreshCw, Search, Settings, SquareCheck, Trash2, Upload } from 'lucide-vue-next';
|
import { ArrowDown, ArrowLeft, ArrowUp, Delete, Document, InfoFilled, Reading, Refresh, Search, Select, Setting, Upload } from '@element-plus/icons-vue';
|
||||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
import {
|
||||||
|
ElAlert,
|
||||||
|
ElButton,
|
||||||
|
ElCheckbox,
|
||||||
|
ElIcon,
|
||||||
|
ElInput,
|
||||||
|
ElLoading,
|
||||||
|
ElPagination,
|
||||||
|
ElRadioButton,
|
||||||
|
ElRadioGroup,
|
||||||
|
ElTable,
|
||||||
|
ElTableColumn,
|
||||||
|
ElTag,
|
||||||
|
ElText,
|
||||||
|
ElTooltip,
|
||||||
|
} from 'element-plus';
|
||||||
|
import 'element-plus/dist/index.css';
|
||||||
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
|
import '@/shared/styles/element-theme.css';
|
||||||
import KbWorkspaceOverlays from '../components/KbWorkspaceOverlays.vue';
|
import KbWorkspaceOverlays from '../components/KbWorkspaceOverlays.vue';
|
||||||
import { useKbWorkspace } from '../composables/useKbWorkspace';
|
import { useKbWorkspace } from '../composables/useKbWorkspace';
|
||||||
|
import type { KbDocumentItem } from '../api/kb.api';
|
||||||
|
import type { PathUploadTaskItem } from '../types/kb-workspace.types';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
embedded?: boolean;
|
embedded?: boolean;
|
||||||
@@ -14,6 +37,40 @@ const props = defineProps<{
|
|||||||
|
|
||||||
/** 作业面状态与操作:模板统一通过 kb.xxx 访问,含 fileInputRef / pathUploadInputRef */
|
/** 作业面状态与操作:模板统一通过 kb.xxx 访问,含 fileInputRef / pathUploadInputRef */
|
||||||
const kb = useKbWorkspace({ embedded: props.embedded });
|
const kb = useKbWorkspace({ embedded: props.embedded });
|
||||||
|
const vLoading = ElLoading.directive;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把现有状态色映射成 Element 标签类型。
|
||||||
|
* 核心逻辑:绿为成功、琥珀为警告、玫红为危险,其余为信息。不改工作流判定。
|
||||||
|
* @param className - getStatusBadgeClass 或路径项展示态返回的样式类
|
||||||
|
* @returns ElTag 的 type
|
||||||
|
*/
|
||||||
|
function statusTagType(className: string): 'success' | 'warning' | 'danger' | 'info' {
|
||||||
|
if (className.includes('emerald')) return 'success';
|
||||||
|
if (className.includes('amber')) return 'warning';
|
||||||
|
if (className.includes('rose')) return 'danger';
|
||||||
|
return 'info';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按当前打开的文档给出表格行类名。
|
||||||
|
* 核心逻辑:渲染时读取 selectedId,选中行跟着详情开关更新。
|
||||||
|
* @param selectedId - 当前文档 id,没有打开详情时为 null
|
||||||
|
* @returns Element 表格 row-class-name 回调
|
||||||
|
*/
|
||||||
|
function documentRowClass(selectedId: number | null) {
|
||||||
|
return ({ row }: { row: KbDocumentItem }) => (selectedId === row.id ? 'kb-doc-row--current' : '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 点击分组摘要。只有失败数大于 0 的格子才打开对应失败列表。
|
||||||
|
* @param item - 摘要格,含是否可点以及失败阶段
|
||||||
|
*/
|
||||||
|
function openFailureSummary(item: { clickable: boolean; failureType?: 'upload' | 'clean' | 'sync' }) {
|
||||||
|
if (item.clickable && item.failureType) {
|
||||||
|
kb.openFailureModal(item.failureType);
|
||||||
|
}
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
@@ -21,72 +78,70 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
|||||||
<div :class="!kb.embedded ? 'mx-auto max-w-7xl page-shell-mobile py-6' : ''">
|
<div :class="!kb.embedded ? 'mx-auto max-w-7xl page-shell-mobile py-6' : ''">
|
||||||
<div class="card mb-6 flex flex-col gap-4 p-6 md:flex-row md:items-center md:justify-between">
|
<div class="card mb-6 flex flex-col gap-4 p-6 md:flex-row md:items-center md:justify-between">
|
||||||
<div class="flex items-start gap-4">
|
<div class="flex items-start gap-4">
|
||||||
<button
|
<ElButton
|
||||||
v-if="!kb.embedded || (kb.embedded && kb.viewMode === 'group_detail')"
|
v-if="!kb.embedded || (kb.embedded && kb.viewMode === 'group_detail')"
|
||||||
@click="kb.embedded ? kb.backToGroupOverview() : kb.router.push('/workspace')"
|
:icon="ArrowLeft"
|
||||||
class="kb-ws-icon-btn"
|
|
||||||
:title="kb.embedded ? kb.t('kbWorkspace.actions.backToOverview') : kb.t('kbWorkspace.actions.backToWorkspace')"
|
:title="kb.embedded ? kb.t('kbWorkspace.actions.backToOverview') : kb.t('kbWorkspace.actions.backToWorkspace')"
|
||||||
>
|
:aria-label="kb.embedded ? kb.t('kbWorkspace.actions.backToOverview') : kb.t('kbWorkspace.actions.backToWorkspace')"
|
||||||
<ArrowLeft class="h-5 w-5" />
|
@click="kb.embedded ? kb.backToGroupOverview() : kb.router.push('/workspace')"
|
||||||
</button>
|
/>
|
||||||
<div>
|
<div>
|
||||||
<div class="flex items-center gap-3">
|
<div class="flex items-center gap-3">
|
||||||
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-brand-50 text-brand-600 ">
|
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-brand-50 text-brand-600">
|
||||||
<BookOpen class="h-6 w-6" />
|
<ElIcon :size="24"><Reading /></ElIcon>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<h1 class="text-2xl font-bold text-primary">
|
<h1 class="section-title">
|
||||||
{{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.header.groupOverviewTitle') : kb.t('kbWorkspace.header.workspaceTitle') }}
|
{{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.header.groupOverviewTitle') : kb.t('kbWorkspace.header.workspaceTitle') }}
|
||||||
</h1>
|
</h1>
|
||||||
<p class="mt-1 text-sm text-muted">
|
<p class="section-desc">
|
||||||
{{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.header.groupOverviewSubtitle') : kb.t('kbWorkspace.header.workspaceSubtitle') }}
|
{{ kb.viewMode === 'group_overview' ? kb.t('kbWorkspace.header.groupOverviewSubtitle') : kb.t('kbWorkspace.header.workspaceSubtitle') }}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-wrap items-center gap-3">
|
<div class="kb-toolbar">
|
||||||
<button
|
<ElButton
|
||||||
v-if="kb.viewMode === 'group_overview'"
|
v-if="kb.viewMode === 'group_overview'"
|
||||||
type="button"
|
type="primary"
|
||||||
|
:icon="Setting"
|
||||||
@click="kb.router.push('/admin/knowledge-base')"
|
@click="kb.router.push('/admin/knowledge-base')"
|
||||||
class="btn-primary"
|
|
||||||
>
|
>
|
||||||
<Settings class="h-4 w-4" />
|
|
||||||
{{ kb.t('kbWorkspace.actions.manageGroups') }}
|
{{ kb.t('kbWorkspace.actions.manageGroups') }}
|
||||||
</button>
|
</ElButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<template v-if="kb.viewMode === 'group_overview'">
|
<template v-if="kb.viewMode === 'group_overview'">
|
||||||
<section class="kb-ws-section">
|
<section class="kb-ws-section">
|
||||||
<div class="mb-4 flex items-center">
|
<div class="mb-4 flex items-center">
|
||||||
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.overview.title') }}</h2>
|
<h2 class="section-title">{{ kb.t('kbWorkspace.overview.title') }}</h2>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="kb.isLoading" class="py-10 text-center text-sm text-muted">{{ kb.t('kbWorkspace.overview.loadingGroups') }}</div>
|
<div v-if="kb.isLoading" class="py-10 text-center">{{ kb.t('kbWorkspace.overview.loadingGroups') }}</div>
|
||||||
<div v-else-if="kb.groups.length === 0" class="kb-ws-empty py-10 text-center text-sm text-muted">
|
<div v-else-if="kb.groups.length === 0" class="kb-ws-empty py-10 text-center">
|
||||||
{{ kb.t('kbWorkspace.overview.emptyGroups') }}
|
{{ kb.t('kbWorkspace.overview.emptyGroups') }}
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">
|
<div v-else class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">
|
||||||
<div
|
<div
|
||||||
v-for="group in kb.groups"
|
v-for="group in kb.groups"
|
||||||
:key="group.id"
|
:key="group.id"
|
||||||
@click="kb.openGroupDetail(group.id)"
|
|
||||||
class="kb-ws-card--interactive !min-h-[150px]"
|
class="kb-ws-card--interactive !min-h-[150px]"
|
||||||
|
@click="kb.openGroupDetail(group.id)"
|
||||||
>
|
>
|
||||||
<div class="w-full text-left">
|
<div class="w-full text-left">
|
||||||
<div class="flex items-start justify-between gap-3">
|
<div class="flex items-start justify-between gap-3">
|
||||||
<div class="min-w-0">
|
<div class="min-w-0">
|
||||||
<div class="text-xl font-bold leading-tight text-primary break-words">{{ group.name }}</div>
|
<div class="section-title break-words">{{ group.name }}</div>
|
||||||
<div class="mt-1 line-clamp-2 text-sm text-muted" :title="group.description || kb.t('kbWorkspace.overview.noDescription')">
|
<div class="section-desc line-clamp-2" :title="group.description || kb.t('kbWorkspace.overview.noDescription')">
|
||||||
{{ group.description || kb.t('kbWorkspace.overview.noDescription') }}
|
{{ group.description || kb.t('kbWorkspace.overview.noDescription') }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="rounded-full bg-surface-soft px-2.5 py-1 text-xs font-medium text-secondary whitespace-nowrap">
|
<ElTag effect="light">
|
||||||
{{ kb.t('kbWorkspace.overview.documentCount', { count: group.document_count ?? 0 }) }}
|
{{ kb.t('kbWorkspace.overview.documentCount', { count: group.document_count ?? 0 }) }}
|
||||||
</div>
|
</ElTag>
|
||||||
</div>
|
</div>
|
||||||
<div class="mt-3 text-xs text-muted">{{ kb.t('kbWorkspace.overview.updatedAt') }}{{ kb.formatDateTime(group.updated_at) }}</div>
|
<div class="mt-3">{{ kb.t('kbWorkspace.overview.updatedAt') }}{{ kb.formatDateTime(group.updated_at) }}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -114,24 +169,22 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
|||||||
<div class="kb-ws-section">
|
<div class="kb-ws-section">
|
||||||
<div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
<div class="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
|
||||||
<div class="min-w-0">
|
<div class="min-w-0">
|
||||||
<div class="text-xs font-medium text-muted">{{ kb.t('kbWorkspace.summary.currentGroup') }}</div>
|
<div>{{ kb.t('kbWorkspace.summary.currentGroup') }}</div>
|
||||||
<h2 class="mt-1 text-2xl font-bold text-primary break-words">{{ kb.selectedGroup?.name || '--' }}</h2>
|
<h2 class="section-title mt-1 break-words">{{ kb.selectedGroup?.name || '--' }}</h2>
|
||||||
<p class="mt-2 max-w-3xl text-sm text-muted">
|
<p class="section-desc mt-2 max-w-3xl">
|
||||||
{{ kb.selectedGroup?.description || kb.t('kbWorkspace.overview.noDescription') }}
|
{{ kb.selectedGroup?.description || kb.t('kbWorkspace.overview.noDescription') }}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="grid min-w-full grid-cols-2 gap-2 sm:grid-cols-5 lg:min-w-[520px]">
|
<div class="kb-stat-grid">
|
||||||
<button
|
<ElButton
|
||||||
v-for="item in kb.groupSummaryItems.filter((summary) => !summary.wide)"
|
v-for="item in kb.groupSummaryItems.filter((summary) => !summary.wide)"
|
||||||
:key="item.label"
|
:key="item.label"
|
||||||
type="button"
|
class="kb-stat-tile"
|
||||||
class="rounded-2xl border border-default bg-surface-soft px-3 py-3 text-left transition-colors"
|
@click="openFailureSummary(item)"
|
||||||
:class="item.clickable ? 'hover:border-rose-200 hover:bg-rose-50' : ''"
|
|
||||||
@click="item.clickable && item.failureType ? kb.openFailureModal(item.failureType) : undefined"
|
|
||||||
>
|
>
|
||||||
<div class="text-lg font-semibold text-primary">{{ item.value }}</div>
|
<span>{{ item.value }}</span>
|
||||||
<div class="mt-1 text-xs text-muted">{{ item.label }}</div>
|
<span>{{ item.label }}</span>
|
||||||
</button>
|
</ElButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -140,346 +193,301 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
|||||||
<div class="mb-4 space-y-3">
|
<div class="mb-4 space-y-3">
|
||||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||||
<div class="flex items-center gap-2">
|
<div class="flex items-center gap-2">
|
||||||
<h2 class="text-lg font-semibold text-primary">{{ kb.t('kbWorkspace.documents.title') }}</h2>
|
<h2 class="section-title">{{ kb.t('kbWorkspace.documents.title') }}</h2>
|
||||||
<div class="group relative">
|
<ElTooltip :content="kb.t('kbWorkspace.documents.infoTip')" placement="bottom-start">
|
||||||
<button
|
<ElButton
|
||||||
type="button"
|
:icon="InfoFilled"
|
||||||
class="inline-flex h-6 w-6 items-center justify-center rounded-full border border-default text-muted transition-colors hover:border-brand-300 hover:text-brand-600"
|
:title="kb.t('kbWorkspace.documents.infoTip')"
|
||||||
>
|
:aria-label="kb.t('kbWorkspace.documents.infoTip')"
|
||||||
<Info class="h-3.5 w-3.5" />
|
/>
|
||||||
</button>
|
</ElTooltip>
|
||||||
<div class="pointer-events-none absolute left-0 top-8 z-10 hidden w-80 rounded-2xl border border-default bg-surface px-4 py-3 text-sm text-muted shadow-xl group-hover:block">
|
|
||||||
{{ kb.t('kbWorkspace.documents.infoTip') }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-wrap items-center gap-3">
|
<div class="kb-toolbar">
|
||||||
<button
|
<ElButton
|
||||||
v-if="kb.selectedGroupId"
|
v-if="kb.selectedGroupId"
|
||||||
@click="kb.openPathUploadModal"
|
:icon="Upload"
|
||||||
:disabled="kb.pathUploadRunning"
|
:disabled="kb.pathUploadRunning"
|
||||||
class="inline-flex items-center gap-2 rounded-2xl border border-brand-200 px-4 py-2.5 text-sm font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 border-brand-200 hover:bg-brand-50"
|
@click="kb.openPathUploadModal"
|
||||||
>
|
>
|
||||||
<Upload class="h-4 w-4" />
|
|
||||||
{{ kb.t('kbWorkspace.documents.uploadPath') }}
|
{{ kb.t('kbWorkspace.documents.uploadPath') }}
|
||||||
</button>
|
</ElButton>
|
||||||
<button
|
<ElButton
|
||||||
v-if="kb.selectedGroupId"
|
v-if="kb.selectedGroupId"
|
||||||
@click="kb.triggerMultiUpload"
|
type="primary"
|
||||||
|
:icon="Upload"
|
||||||
|
:loading="kb.isSubmitting"
|
||||||
:disabled="kb.isSubmitting"
|
:disabled="kb.isSubmitting"
|
||||||
class="btn-primary"
|
@click="kb.triggerMultiUpload"
|
||||||
>
|
>
|
||||||
<Upload class="h-4 w-4" />
|
|
||||||
{{ kb.t('kbWorkspace.documents.uploadFile') }}
|
{{ kb.t('kbWorkspace.documents.uploadFile') }}
|
||||||
</button>
|
</ElButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p
|
<ElAlert
|
||||||
v-if="kb.feedback"
|
v-if="kb.feedback"
|
||||||
class="mb-4 text-sm"
|
class="mb-4"
|
||||||
:class="kb.feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600'"
|
:closable="false"
|
||||||
>
|
:title="kb.feedback"
|
||||||
{{ kb.feedback }}
|
:type="kb.feedbackType === 'error' ? 'error' : 'success'"
|
||||||
</p>
|
/>
|
||||||
<div
|
<div
|
||||||
v-if="kb.pathUploadTask.total"
|
v-if="kb.pathUploadTask.total"
|
||||||
class="mb-4 rounded-2xl border border-default bg-surface-soft p-4"
|
class="mb-4 rounded-2xl border border-default bg-surface-soft p-4"
|
||||||
>
|
>
|
||||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<div class="text-sm font-semibold text-primary">
|
<div>
|
||||||
{{ kb.t('kbWorkspace.pathUpload.progressTitle') }}
|
{{ kb.t('kbWorkspace.pathUpload.progressTitle') }}
|
||||||
<span
|
<ElTag class="ml-2" effect="light" :type="kb.pathUploadRunning ? 'warning' : 'success'">
|
||||||
class="ml-2 inline-flex items-center rounded-full border px-2.5 py-1 text-xs"
|
|
||||||
:class="kb.pathUploadRunning
|
|
||||||
? 'border-amber-200 bg-amber-50 text-amber-700 border-amber-200'
|
|
||||||
: 'border-emerald-200 bg-emerald-50 text-emerald-700 border-emerald-200 '"
|
|
||||||
>
|
|
||||||
{{ kb.pathUploadRunning ? kb.t('kbWorkspace.pathUpload.uploading') : kb.t('kbWorkspace.pathUpload.completed') }}
|
{{ kb.pathUploadRunning ? kb.t('kbWorkspace.pathUpload.uploading') : kb.t('kbWorkspace.pathUpload.completed') }}
|
||||||
</span>
|
</ElTag>
|
||||||
</div>
|
</div>
|
||||||
<div class="mt-1 text-sm text-muted">
|
<div class="mt-1">
|
||||||
{{ kb.t('kbWorkspace.pathUpload.batchHint', { batchSize: kb.pathUploadTask.batchSize, seconds: kb.PATH_UPLOAD_BATCH_INTERVAL_MS / 1000 }) }}
|
{{ kb.t('kbWorkspace.pathUpload.batchHint', { batchSize: kb.pathUploadTask.batchSize, seconds: kb.PATH_UPLOAD_BATCH_INTERVAL_MS / 1000 }) }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="grid grid-cols-2 gap-2 text-sm text-secondary md:grid-cols-4">
|
<div class="grid grid-cols-2 gap-2 md:grid-cols-4">
|
||||||
<div>{{ kb.t('kbWorkspace.pathUpload.total', { count: kb.pathUploadSummary.total }) }}</div>
|
<div>{{ kb.t('kbWorkspace.pathUpload.total', { count: kb.pathUploadSummary.total }) }}</div>
|
||||||
<div>{{ kb.t('kbWorkspace.pathUpload.pending', { count: kb.pathUploadSummary.pending }) }}</div>
|
<div>{{ kb.t('kbWorkspace.pathUpload.pending', { count: kb.pathUploadSummary.pending }) }}</div>
|
||||||
<div>{{ kb.t('kbWorkspace.pathUpload.uploaded', { count: kb.pathUploadSummary.uploaded }) }}</div>
|
<div>{{ kb.t('kbWorkspace.pathUpload.uploaded', { count: kb.pathUploadSummary.uploaded }) }}</div>
|
||||||
<div>{{ kb.t('kbWorkspace.pathUpload.failed', { count: kb.pathUploadSummary.failed }) }}</div>
|
<div>{{ kb.t('kbWorkspace.pathUpload.failed', { count: kb.pathUploadSummary.failed }) }}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="kb.pathUploadTask.currentFile" class="mt-3 text-sm text-brand-600 ">
|
<div v-if="kb.pathUploadTask.currentFile" class="mt-3">
|
||||||
{{ kb.t('kbWorkspace.pathUpload.currentFile', { name: kb.pathUploadTask.currentFile }) }}
|
{{ kb.t('kbWorkspace.pathUpload.currentFile', { name: kb.pathUploadTask.currentFile }) }}
|
||||||
</div>
|
</div>
|
||||||
<div class="mt-4 space-y-2">
|
<div class="mt-4 space-y-2">
|
||||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||||
<button
|
<ElButton
|
||||||
type="button"
|
link
|
||||||
|
type="primary"
|
||||||
|
:icon="kb.showPathUploadDetails ? ArrowUp : ArrowDown"
|
||||||
@click="kb.showPathUploadDetails = !kb.showPathUploadDetails"
|
@click="kb.showPathUploadDetails = !kb.showPathUploadDetails"
|
||||||
class="inline-flex items-center gap-2 text-sm font-medium text-secondary transition-colors hover:text-brand-600 hover:text-brand-600"
|
>
|
||||||
>
|
{{ kb.t('kbWorkspace.pathUpload.details') }}
|
||||||
<span>{{ kb.t('kbWorkspace.pathUpload.details') }}</span>
|
</ElButton>
|
||||||
<ChevronDown v-if="!kb.showPathUploadDetails" class="h-4 w-4" />
|
<ElButton
|
||||||
<ChevronUp v-else class="h-4 w-4" />
|
v-if="kb.latestPathUploadJob && kb.hasRetryablePathUploadFailure(kb.latestPathUploadJob) && !kb.pathUploadRunning"
|
||||||
</button>
|
link
|
||||||
<div class="flex items-center gap-2">
|
type="danger"
|
||||||
<button
|
:loading="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all`"
|
||||||
v-if="kb.latestPathUploadJob && kb.hasRetryablePathUploadFailure(kb.latestPathUploadJob) && !kb.pathUploadRunning"
|
:disabled="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all`"
|
||||||
@click="kb.handleRetryFailedPathUpload(kb.latestPathUploadJob)"
|
@click="kb.handleRetryFailedPathUpload(kb.latestPathUploadJob)"
|
||||||
:disabled="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all`"
|
>
|
||||||
class="inline-flex items-center rounded-xl border border-rose-200 px-3 py-1.5 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
|
{{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.pathUpload.retryFailedFiles') }}
|
||||||
>
|
</ElButton>
|
||||||
{{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:all` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.pathUpload.retryFailedFiles') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<div v-if="kb.showPathUploadDetails" class="max-h-72 space-y-2 overflow-y-auto pr-1">
|
<ElTable
|
||||||
<div
|
v-if="kb.showPathUploadDetails"
|
||||||
v-for="item in kb.recentPathUploadItems"
|
:data="kb.recentPathUploadItems"
|
||||||
:key="item.key"
|
row-key="key"
|
||||||
class="flex flex-wrap items-start justify-between gap-3 rounded-xl border border-default bg-surface px-3 py-3 text-sm"
|
max-height="288"
|
||||||
>
|
:empty-text="kb.t('kbWorkspace.pathUpload.noBatchMessage')"
|
||||||
<div class="min-w-0 flex-1">
|
>
|
||||||
<div class="truncate font-medium text-primary">{{ item.title }}</div>
|
<ElTableColumn prop="title" min-width="160" show-overflow-tooltip />
|
||||||
<div class="mt-1 truncate text-xs text-muted">{{ item.displayPath }}</div>
|
<ElTableColumn prop="displayPath" min-width="200" show-overflow-tooltip />
|
||||||
<div v-if="item.error" class="mt-1 text-xs text-rose-500">{{ kb.t('kbWorkspace.common.failureReason', { reason: item.error }) }}</div>
|
<ElTableColumn min-width="160" show-overflow-tooltip>
|
||||||
</div>
|
<template #default="{ row }">
|
||||||
<div class="flex items-center gap-2">
|
<ElText v-if="row.error" type="danger">
|
||||||
<span
|
{{ kb.t('kbWorkspace.common.failureReason', { reason: row.error }) }}
|
||||||
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
|
</ElText>
|
||||||
:class="kb.getPathUploadItemDisplayState(item).className"
|
</template>
|
||||||
>
|
</ElTableColumn>
|
||||||
{{ kb.getPathUploadItemDisplayState(item).label }}
|
<ElTableColumn width="120">
|
||||||
</span>
|
<template #default="{ row }">
|
||||||
<button
|
<ElTag effect="light" :type="statusTagType(kb.getPathUploadItemDisplayState(row as PathUploadTaskItem).className)">
|
||||||
v-if="item.retryable && kb.latestPathUploadJob && !kb.pathUploadRunning"
|
{{ kb.getPathUploadItemDisplayState(row as PathUploadTaskItem).label }}
|
||||||
@click="kb.handleRetryFailedPathUpload(kb.latestPathUploadJob, [item.displayPath])"
|
</ElTag>
|
||||||
:disabled="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${item.displayPath}`"
|
</template>
|
||||||
class="inline-flex items-center rounded-xl border border-rose-200 px-2.5 py-1 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
|
</ElTableColumn>
|
||||||
>
|
<ElTableColumn width="160" align="right">
|
||||||
{{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${item.displayPath}` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.common.retry') }}
|
<template #default="{ row }">
|
||||||
</button>
|
<ElButton
|
||||||
<button
|
v-if="row.retryable && kb.latestPathUploadJob && !kb.pathUploadRunning"
|
||||||
|
link
|
||||||
|
type="primary"
|
||||||
|
:loading="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${row.displayPath}`"
|
||||||
|
:disabled="kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${row.displayPath}`"
|
||||||
|
@click="kb.handleRetryFailedPathUpload(kb.latestPathUploadJob, [row.displayPath])"
|
||||||
|
>
|
||||||
|
{{ kb.retryingPathUploadKey === `${kb.latestPathUploadJob.id}:${row.displayPath}` ? kb.t('kbWorkspace.common.processing') : kb.t('kbWorkspace.common.retry') }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton
|
||||||
v-if="kb.latestPathUploadJob && !kb.pathUploadRunning"
|
v-if="kb.latestPathUploadJob && !kb.pathUploadRunning"
|
||||||
@click="kb.handleDeletePathUploadItem(kb.latestPathUploadJob, item)"
|
link
|
||||||
class="inline-flex items-center rounded-xl border border-default px-2.5 py-1 text-xs font-medium text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
|
type="danger"
|
||||||
>
|
@click="kb.handleDeletePathUploadItem(kb.latestPathUploadJob, row as PathUploadTaskItem)"
|
||||||
|
>
|
||||||
{{ kb.t('kbWorkspace.common.delete') }}
|
{{ kb.t('kbWorkspace.common.delete') }}
|
||||||
</button>
|
</ElButton>
|
||||||
</div>
|
</template>
|
||||||
</div>
|
</ElTableColumn>
|
||||||
</div>
|
</ElTable>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
v-if="kb.selectedGroupId"
|
v-if="kb.selectedGroupId"
|
||||||
class="mb-4 space-y-3 rounded-2xl bg-surface-soft px-4 py-3"
|
class="mb-4 space-y-3 rounded-2xl bg-surface-soft px-4 py-3"
|
||||||
>
|
>
|
||||||
<div class="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
|
<div class="kb-toolbar">
|
||||||
<div class="flex flex-wrap items-center gap-2">
|
<ElButton
|
||||||
<button
|
v-if="kb.isKbAdmin"
|
||||||
v-if="kb.isKbAdmin"
|
:icon="Refresh"
|
||||||
@click="kb.handleBatchClean"
|
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
||||||
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
@click="kb.handleBatchClean"
|
||||||
class="inline-flex items-center gap-2 rounded-full border border-amber-200 bg-surface px-4 py-2 text-sm font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-60"
|
>
|
||||||
>
|
{{ kb.batchActionLabel('clean', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
||||||
<RefreshCw class="h-4 w-4" />
|
</ElButton>
|
||||||
{{ kb.batchActionLabel('clean', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
<ElButton
|
||||||
</button>
|
v-if="kb.isKbAdmin"
|
||||||
<button
|
:icon="Refresh"
|
||||||
v-if="kb.isKbAdmin"
|
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
||||||
@click="kb.handleBatchSync"
|
@click="kb.handleBatchSync"
|
||||||
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
>
|
||||||
class="inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-surface px-4 py-2 text-sm font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60"
|
{{ kb.batchActionLabel('sync', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
||||||
>
|
</ElButton>
|
||||||
<RefreshCw class="h-4 w-4" />
|
<ElButton
|
||||||
{{ kb.batchActionLabel('sync', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
type="danger"
|
||||||
</button>
|
:icon="Delete"
|
||||||
<button
|
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
||||||
@click="kb.handleBatchDelete"
|
@click="kb.handleBatchDelete"
|
||||||
:disabled="kb.batchSubmitting || kb.selectedDocuments.length === 0"
|
>
|
||||||
class="inline-flex items-center gap-2 rounded-full border border-rose-200 bg-surface px-4 py-2 text-sm font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60"
|
{{ kb.batchActionLabel('delete', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
||||||
>
|
</ElButton>
|
||||||
<Trash2 class="h-4 w-4" />
|
|
||||||
{{ kb.batchActionLabel('delete', kb.batchSubmitting, kb.selectedDocuments.length) }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
|
<div class="kb-filter-row">
|
||||||
<label class="relative w-full max-w-md">
|
<div class="kb-doc-search">
|
||||||
<Search class="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted" />
|
<ElInput
|
||||||
<input
|
|
||||||
v-model.trim="kb.documentKeyword"
|
v-model.trim="kb.documentKeyword"
|
||||||
type="text"
|
clearable
|
||||||
class="w-full rounded-2xl border border-default bg-surface py-2.5 pl-10 pr-4 text-sm text-primary outline-none transition-colors focus:border-brand-300"
|
:prefix-icon="Search"
|
||||||
:placeholder="kb.t('kbWorkspace.documents.searchPlaceholder')"
|
:placeholder="kb.t('kbWorkspace.documents.searchPlaceholder')"
|
||||||
/>
|
/>
|
||||||
</label>
|
|
||||||
<button
|
|
||||||
v-if="kb.documentKeyword"
|
|
||||||
type="button"
|
|
||||||
@click="kb.documentKeyword = ''"
|
|
||||||
class="inline-flex items-center rounded-xl border border-default bg-surface px-3 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft"
|
|
||||||
>
|
|
||||||
{{ kb.t('kbWorkspace.documents.clearSearch') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="flex flex-col gap-3 border-t border-default pt-3 xl:flex-row xl:items-center xl:justify-between">
|
|
||||||
<div class="flex flex-wrap items-center gap-2">
|
|
||||||
<button
|
|
||||||
@click="kb.toggleSelectAllFiltered"
|
|
||||||
class="inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full text-muted transition-colors hover:bg-surface hover:text-brand-600"
|
|
||||||
:class="kb.isAllFilteredSelected ? 'bg-brand-50 text-brand-600' : ''"
|
|
||||||
:title="kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered')"
|
|
||||||
:aria-label="kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered')"
|
|
||||||
>
|
|
||||||
<SquareCheck class="h-[18px] w-[18px]" />
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
v-for="tab in kb.stageFilterTabs.filter((item) => item.key !== 'all')"
|
|
||||||
:key="tab.key"
|
|
||||||
@click="kb.documentStageFilter = kb.documentStageFilter === tab.key ? 'all' : tab.key"
|
|
||||||
class="inline-flex items-center gap-2 rounded-full border px-4 py-2 text-sm font-medium transition-colors"
|
|
||||||
:class="kb.documentStageFilter === tab.key
|
|
||||||
? 'border-brand-200 bg-brand-50 text-brand-700'
|
|
||||||
: 'border-default bg-surface text-secondary hover:bg-surface-soft'"
|
|
||||||
>
|
|
||||||
<span>{{ tab.label }}</span>
|
|
||||||
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs">{{ tab.count }}</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
<ElButton
|
||||||
|
:icon="Select"
|
||||||
|
:type="kb.isAllFilteredSelected ? 'primary' : 'default'"
|
||||||
|
:title="kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered')"
|
||||||
|
:aria-label="kb.isAllFilteredSelected ? kb.t('kbWorkspace.pathUpload.deselectAllFiltered') : kb.t('kbWorkspace.pathUpload.selectAllFiltered')"
|
||||||
|
@click="kb.toggleSelectAllFiltered"
|
||||||
|
/>
|
||||||
|
<ElRadioGroup v-model="kb.documentStageFilter" class="kb-stage-filter">
|
||||||
|
<ElRadioButton
|
||||||
|
v-for="tab in kb.stageFilterTabs"
|
||||||
|
:key="tab.key"
|
||||||
|
:value="tab.key"
|
||||||
|
>
|
||||||
|
{{ tab.label }} {{ tab.count }}
|
||||||
|
</ElRadioButton>
|
||||||
|
</ElRadioGroup>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="!kb.selectedGroupId" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted ">
|
<div v-if="!kb.selectedGroupId" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center">
|
||||||
{{ kb.t('kbWorkspace.documents.selectGroup') }}
|
{{ kb.t('kbWorkspace.documents.selectGroup') }}
|
||||||
</div>
|
</div>
|
||||||
<div v-else-if="kb.isDocumentsLoading" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted ">
|
<template v-else>
|
||||||
{{ kb.t('kbWorkspace.documents.loadingDocuments') }}
|
<ElTable
|
||||||
</div>
|
v-loading="kb.isDocumentsLoading"
|
||||||
<div v-else-if="kb.filteredDocuments.length === 0" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted ">
|
:data="kb.pagedFilteredDocuments"
|
||||||
{{ kb.documentEmptyMessage(kb.documents.length, !!kb.documentKeyword) }}
|
row-key="id"
|
||||||
</div>
|
:row-class-name="documentRowClass(kb.selectedDocumentId)"
|
||||||
<div v-else class="space-y-3">
|
:empty-text="kb.isDocumentsLoading ? kb.t('kbWorkspace.documents.loadingDocuments') : kb.documentEmptyMessage(kb.documents.length, !!kb.documentKeyword)"
|
||||||
<div
|
>
|
||||||
v-for="doc in kb.pagedFilteredDocuments"
|
<ElTableColumn width="52">
|
||||||
:key="doc.id"
|
<template #default="{ row }">
|
||||||
class="rounded-2xl border px-4 py-3 transition-colors"
|
<ElCheckbox
|
||||||
:class="kb.selectedDocumentId === doc.id
|
:model-value="kb.selectedDocumentIds.includes(row.id)"
|
||||||
? 'border-brand-200 bg-brand-50/50 border-brand-200'
|
@change="kb.toggleDocumentSelection(row.id)"
|
||||||
: 'border-default'"
|
/>
|
||||||
>
|
</template>
|
||||||
<div class="space-y-3">
|
</ElTableColumn>
|
||||||
<div class="grid gap-3 lg:grid-cols-[minmax(360px,1fr)_auto] lg:items-start">
|
<ElTableColumn :label="kb.t('kbWorkspace.documents.title')" min-width="280">
|
||||||
<div class="flex min-w-0 gap-3">
|
<template #default="{ row }">
|
||||||
<label class="mt-1 inline-flex shrink-0 cursor-pointer items-center">
|
<ElButton link type="primary" @click="kb.openMarkdownEditor(row as KbDocumentItem)">
|
||||||
<input
|
{{ kb.getDocumentDisplayTitle(row as KbDocumentItem) }}
|
||||||
type="checkbox"
|
</ElButton>
|
||||||
class="h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
|
<div>
|
||||||
:checked="kb.selectedDocumentIds.includes(doc.id)"
|
<ElButton link type="primary" @click="kb.openSourceInfo(row as KbDocumentItem)">
|
||||||
@change="kb.toggleDocumentSelection(doc.id)"
|
{{ kb.getDocumentDisplayDescription(row as KbDocumentItem) }}
|
||||||
/>
|
</ElButton>
|
||||||
</label>
|
|
||||||
<div class="min-w-0 flex-1">
|
|
||||||
<button
|
|
||||||
@click="kb.openMarkdownEditor(doc)"
|
|
||||||
class="block max-w-full truncate text-left font-semibold text-primary transition-colors hover:text-brand-600 hover:text-brand-600"
|
|
||||||
>
|
|
||||||
{{ kb.getDocumentDisplayTitle(doc) }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
@click="kb.openSourceInfo(doc)"
|
|
||||||
class="mt-1 block max-w-full truncate text-left text-sm text-muted transition-colors hover:text-brand-600 hover:text-brand-600"
|
|
||||||
>
|
|
||||||
{{ kb.getDocumentDisplayDescription(doc) }}
|
|
||||||
</button>
|
|
||||||
<div class="mt-2 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted">
|
|
||||||
<span class="shrink-0">{{ kb.t('kbWorkspace.documents.versionCount', { count: doc.version_count ?? 0 }) }}</span>
|
|
||||||
<span v-if="doc.latest_version" class="shrink-0">{{ kb.t('kbWorkspace.documents.currentVersion', { version: doc.latest_version.version_no }) }}</span>
|
|
||||||
<button
|
|
||||||
v-if="doc.latest_version"
|
|
||||||
type="button"
|
|
||||||
@click="kb.openSourceInfo(doc)"
|
|
||||||
class="min-w-0 max-w-full truncate text-xs text-muted underline-offset-2 transition-colors hover:text-brand-600 hover:underline hover:text-brand-600"
|
|
||||||
>
|
|
||||||
{{ doc.latest_version.source_file_name }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
v-if="kb.getDocumentWorkflowState(doc).primaryError"
|
|
||||||
class="mt-1 max-w-xl text-xs text-rose-500"
|
|
||||||
>
|
|
||||||
{{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(doc).primaryError }) }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div>
|
||||||
<div class="flex min-w-0 flex-wrap items-center gap-2 lg:justify-end">
|
<span>{{ kb.t('kbWorkspace.documents.versionCount', { count: row.version_count ?? 0 }) }}</span>
|
||||||
<button
|
<span v-if="row.latest_version"> {{ kb.t('kbWorkspace.documents.currentVersion', { version: row.latest_version.version_no }) }}</span>
|
||||||
@click="kb.openDocumentDetail(doc.id)"
|
<ElButton
|
||||||
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-violet-200 px-3 py-2 text-xs font-medium text-violet-700 transition-colors hover:bg-violet-50"
|
v-if="row.latest_version"
|
||||||
>
|
link
|
||||||
<FileText class="h-3.5 w-3.5" />
|
type="primary"
|
||||||
{{ kb.t('kbWorkspace.documents.viewRecord') }}
|
@click="kb.openSourceInfo(row as KbDocumentItem)"
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
@click="kb.triggerUploadForDocument(doc.id)"
|
|
||||||
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 border-brand-200 hover:bg-brand-50"
|
|
||||||
>
|
|
||||||
<Upload class="h-3.5 w-3.5" />
|
|
||||||
{{ kb.t('kbWorkspace.documents.uploadVersion') }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
v-if="kb.isKbAdmin"
|
|
||||||
@click="kb.handleSyncDocument(doc.id)"
|
|
||||||
:disabled="kb.syncingDocumentId === doc.id || !doc.latest_version"
|
|
||||||
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-emerald-200 px-3 py-2 text-xs font-medium text-emerald-700 transition-colors hover:bg-emerald-50 disabled:cursor-not-allowed disabled:opacity-60 border-emerald-200"
|
|
||||||
>
|
|
||||||
<RefreshCw class="h-3.5 w-3.5" />
|
|
||||||
{{ kb.syncingDocumentId === doc.id ? kb.t('kbWorkspace.documents.syncingDify') : kb.t('kbWorkspace.documents.syncDify') }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
@click="kb.handleDeleteDocument(doc)"
|
|
||||||
class="inline-flex shrink-0 items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 border-rose-200 hover:bg-rose-50"
|
|
||||||
>
|
|
||||||
<Trash2 class="h-3.5 w-3.5" />
|
|
||||||
{{ kb.t('kbWorkspace.common.delete') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="grid gap-3 border-t border-default pt-3 lg:grid-cols-[minmax(260px,1fr)_auto] lg:items-center">
|
|
||||||
<span class="min-w-0 text-xs text-muted">
|
|
||||||
{{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(doc.updated_at) }) }}
|
|
||||||
</span>
|
|
||||||
<div class="flex min-w-0 flex-wrap items-center gap-2 lg:justify-end">
|
|
||||||
<div
|
|
||||||
v-for="badge in kb.getWorkflowBadges(doc)"
|
|
||||||
:key="`${doc.id}-${badge.label}`"
|
|
||||||
class="inline-flex shrink-0 items-center rounded-full border px-3 py-1 text-xs font-semibold"
|
|
||||||
:class="badge.className"
|
|
||||||
>
|
>
|
||||||
{{ badge.label }}:{{ badge.value }}
|
{{ row.latest_version.source_file_name }}
|
||||||
</div>
|
</ElButton>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<ElText v-if="kb.getDocumentWorkflowState(row as KbDocumentItem).primaryError" type="danger">
|
||||||
</div>
|
{{ kb.t('kbWorkspace.common.failureReason', { reason: kb.getDocumentWorkflowState(row as KbDocumentItem).primaryError }) }}
|
||||||
|
</ElText>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn min-width="220">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<ElTag
|
||||||
|
v-for="badge in kb.getWorkflowBadges(row as KbDocumentItem)"
|
||||||
|
:key="`${row.id}-${badge.label}`"
|
||||||
|
class="kb-workflow-tag"
|
||||||
|
effect="light"
|
||||||
|
:type="statusTagType(badge.className)"
|
||||||
|
>
|
||||||
|
{{ badge.label }}:{{ badge.value }}
|
||||||
|
</ElTag>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn min-width="160">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ kb.t('kbWorkspace.documents.updatedAt', { time: kb.formatDateTime(row.updated_at) }) }}
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn width="280" align="right" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div class="kb-row-actions">
|
||||||
|
<ElButton link type="primary" :icon="Document" @click="kb.openDocumentDetail(row.id)">
|
||||||
|
{{ kb.t('kbWorkspace.documents.viewRecord') }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton link type="primary" :icon="Upload" @click="kb.triggerUploadForDocument(row.id)">
|
||||||
|
{{ kb.t('kbWorkspace.documents.uploadVersion') }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton
|
||||||
|
v-if="kb.isKbAdmin"
|
||||||
|
link
|
||||||
|
type="primary"
|
||||||
|
:icon="Refresh"
|
||||||
|
:loading="kb.syncingDocumentId === row.id"
|
||||||
|
:disabled="kb.syncingDocumentId === row.id || !row.latest_version"
|
||||||
|
@click="kb.handleSyncDocument(row.id)"
|
||||||
|
>
|
||||||
|
{{ kb.syncingDocumentId === row.id ? kb.t('kbWorkspace.documents.syncingDify') : kb.t('kbWorkspace.documents.syncDify') }}
|
||||||
|
</ElButton>
|
||||||
|
<ElButton link type="danger" :icon="Delete" @click="kb.handleDeleteDocument(row as KbDocumentItem)">
|
||||||
|
{{ kb.t('kbWorkspace.common.delete') }}
|
||||||
|
</ElButton>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
</ElTable>
|
||||||
|
<div v-if="kb.filteredDocuments.length > 0" class="kb-doc-pagination">
|
||||||
|
<ElPagination
|
||||||
|
v-model:current-page="kb.documentListPage"
|
||||||
|
v-model:page-size="kb.documentListPageSize"
|
||||||
|
:total="kb.filteredDocuments.length"
|
||||||
|
:page-sizes="[...kb.DOCUMENT_PAGE_SIZE_OPTIONS]"
|
||||||
|
layout="total, sizes, prev, pager, next"
|
||||||
|
background
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
<PaginationBar
|
</template>
|
||||||
v-if="kb.filteredDocuments.length > 0"
|
|
||||||
v-model:page="kb.documentListPage"
|
|
||||||
v-model:page-size="kb.documentListPageSize"
|
|
||||||
:total="kb.filteredDocuments.length"
|
|
||||||
:pages="kb.filteredDocumentTotalPages"
|
|
||||||
:page-size-options="[...kb.DOCUMENT_PAGE_SIZE_OPTIONS]"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
@@ -489,4 +497,91 @@ const kb = useKbWorkspace({ embedded: props.embedded });
|
|||||||
<KbWorkspaceOverlays :kb="kb" />
|
<KbWorkspaceOverlays :kb="kb" />
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.kb-toolbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-toolbar :deep(.el-button) {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-stat-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 8px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 640px) {
|
||||||
|
.kb-stat-grid {
|
||||||
|
grid-template-columns: repeat(5, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 1024px) {
|
||||||
|
.kb-stat-grid {
|
||||||
|
min-width: 520px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-stat-grid :deep(.el-button.kb-stat-tile) {
|
||||||
|
width: 100%;
|
||||||
|
height: auto;
|
||||||
|
margin: 0;
|
||||||
|
white-space: normal;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-filter-row {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-filter-row :deep(.el-button) {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-doc-search {
|
||||||
|
width: 16rem;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-stage-filter {
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-doc-pagination {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
margin-top: 16px;
|
||||||
|
padding-top: 12px;
|
||||||
|
border-top: 1px solid var(--el-border-color-lighter);
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-row-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-row-actions :deep(.el-button) {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.kb-workflow-tag {
|
||||||
|
margin: 0 4px 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
:deep(.kb-doc-row--current) {
|
||||||
|
--el-table-tr-bg-color: var(--el-fill-color-light);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
* features/order-delivery-reply/views/OrderDeliveryReplyPage.vue
|
* features/order-delivery-reply/views/OrderDeliveryReplyPage.vue
|
||||||
* 用途:订单交期回复工作台操作页——筛选分页、单行/联合回复批次、单行/批量通知、手动同步。
|
* 用途:订单交期回复工作台操作页——筛选分页、单行/联合回复批次、单行/批量通知、手动同步。
|
||||||
* 依赖:api/orderDeliveryReply.api(统一 requestJson)、useMessage、auth store(manage/access 权限)、
|
* 依赖:api/orderDeliveryReply.api(统一 requestJson)、useMessage、auth store(manage/access 权限)、
|
||||||
* shared DeleteConfirmDialog(批量通知二次确认)、PaginationBar。
|
* element-plus、PaginationBar。
|
||||||
* 逻辑:所有数据只读本地快照;保存与通知是两步(联合回复只保存,批量通知才发送并锁定);
|
* 逻辑:所有数据只读本地快照;保存与通知是两步(联合回复只保存,批量通知才发送并锁定);
|
||||||
* 保存/通知成功后即时刷新列表(需求 §9);仅 access 用户隐藏全部写操作。
|
* 保存/通知成功后即时刷新列表(需求 §9);仅 access 用户隐藏全部写操作。
|
||||||
* 回复弹窗数量守恒(2026-09-23 由「超额仅提醒」修订):每行各批次合计必须等于订单数量
|
* 回复弹窗数量守恒(2026-09-23 由「超额仅提醒」修订):每行各批次合计必须等于订单数量
|
||||||
@@ -32,9 +32,9 @@
|
|||||||
* 表格对齐(2026-10-09):除交期回复列(批次条按既定左对齐布局)外,全列内容水平居中、
|
* 表格对齐(2026-10-09):除交期回复列(批次条按既定左对齐布局)外,全列内容水平居中、
|
||||||
* 行内容垂直居中,列头文字全部居中;交期回复状态徽标统一等宽(min-w-68px)。
|
* 行内容垂直居中,列头文字全部居中;交期回复状态徽标统一等宽(min-w-68px)。
|
||||||
* 设计系统(docs/ui/DESIGN_SYSTEM.md):根节点挂 page-shell;区块容器用 surface-panel;
|
* 设计系统(docs/ui/DESIGN_SYSTEM.md):根节点挂 page-shell;区块容器用 surface-panel;
|
||||||
* 弹窗用 dialog-overlay/panel/header/body/footer;输入用 input-field/select-field;
|
* 筛选和回复弹窗用 Element Plus;冻结列和批次条就地编辑保持原表格。
|
||||||
* 状态与交互色一律走 --status-* 令牌(badge-*/bg-row-*/frozen-cell-*),品牌强调用 brand-*。
|
* 状态与交互色一律走 --status-* 令牌(badge-*/bg-row-*/frozen-cell-*),品牌强调用 brand-*。
|
||||||
* 批量通知确认使用共享 DeleteConfirmDialog(confirmTone=primary),不再用原生 window.confirm。
|
* 批量通知确认使用 ElMessageBox.confirm。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
@@ -45,8 +45,21 @@ import { useAuthStore } from '@/features/auth/stores/auth.store';
|
|||||||
import { useMessage } from '@/shared/composables/useMessage';
|
import { useMessage } from '@/shared/composables/useMessage';
|
||||||
import { requestJson } from '@/shared/api/client';
|
import { requestJson } from '@/shared/api/client';
|
||||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
||||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
import { Download } from '@element-plus/icons-vue';
|
||||||
import { ChevronDown, ChevronUp, Download, Plus } from 'lucide-vue-next';
|
import {
|
||||||
|
ElButton,
|
||||||
|
ElCheckbox,
|
||||||
|
ElDatePicker,
|
||||||
|
ElDialog,
|
||||||
|
ElInput,
|
||||||
|
ElMessageBox,
|
||||||
|
ElOption,
|
||||||
|
ElSelect,
|
||||||
|
} from 'element-plus';
|
||||||
|
import 'element-plus/dist/index.css';
|
||||||
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
|
import '@/shared/styles/element-theme.css';
|
||||||
|
import { ChevronDown, ChevronUp, Plus } from 'lucide-vue-next';
|
||||||
import {
|
import {
|
||||||
ORDER_DELIVERY_REPLY_MANAGE_PERMISSION,
|
ORDER_DELIVERY_REPLY_MANAGE_PERMISSION,
|
||||||
} from '@/features/order-delivery-reply/constants';
|
} from '@/features/order-delivery-reply/constants';
|
||||||
@@ -242,6 +255,24 @@ function applyQuickDate() {
|
|||||||
modalLines.value.forEach((entry) => entry.batches.forEach((batch) => { batch.planned_date = quickDate.value; }));
|
modalLines.value.forEach((entry) => entry.batches.forEach((batch) => { batch.planned_date = quickDate.value; }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 日期选择器清空后写回空字符串,保持筛选和批次交期的原有字符串。
|
||||||
|
* @param value - 日期选择器回传值
|
||||||
|
* @returns YYYY-MM-DD 或空字符串
|
||||||
|
*/
|
||||||
|
function dateText(value: unknown): string {
|
||||||
|
return typeof value === 'string' ? value : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 筛选状态下拉。清空后回到全部,并立即查询。
|
||||||
|
* @param value - 已回复、未完全回复或空
|
||||||
|
*/
|
||||||
|
function onFilterStatus(value: unknown): void {
|
||||||
|
filters.status = value === 'replied' || value === 'not_fully_replied' ? value : '';
|
||||||
|
doSearch();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 行填写问题文案(实时校验,2026-09-23):
|
* 行填写问题文案(实时校验,2026-09-23):
|
||||||
* [规则 1] 已填数量但未填交期的批次 → 「第 N 批未填交期」;
|
* [规则 1] 已填数量但未填交期的批次 → 「第 N 批未填交期」;
|
||||||
@@ -476,12 +507,26 @@ async function doExportExcel() {
|
|||||||
|
|
||||||
/* ============ 通知 ============ */
|
/* ============ 通知 ============ */
|
||||||
const notifying = ref(false);
|
const notifying = ref(false);
|
||||||
const notifyConfirmVisible = ref(false);
|
|
||||||
|
|
||||||
/** 批量通知入口:先弹共享 DeleteConfirmDialog(primary 语气)二次确认,确认后执行 doNotifyBatch。 */
|
/**
|
||||||
function requestNotifyBatch() {
|
* 批量通知入口。确认后执行 doNotifyBatch,取消不发送。
|
||||||
|
*/
|
||||||
|
async function requestNotifyBatch() {
|
||||||
if (!notifiableSelected.value.length) return;
|
if (!notifiableSelected.value.length) return;
|
||||||
notifyConfirmVisible.value = true;
|
try {
|
||||||
|
await ElMessageBox.confirm(
|
||||||
|
t('workspace.orderDeliveryReply.notifyBatchConfirm', { count: notifiableSelected.value.length }),
|
||||||
|
t('workspace.orderDeliveryReply.batchNotify'),
|
||||||
|
{
|
||||||
|
type: 'warning',
|
||||||
|
confirmButtonText: t('common.deleteDialog.confirm'),
|
||||||
|
cancelButtonText: t('common.deleteDialog.cancel'),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await doNotifyBatch();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 批量通知:部分成功 warning 汇总,全部失败 error;提示后刷新列表让锁定即时生效。 */
|
/** 批量通知:部分成功 warning 汇总,全部失败 error;提示后刷新列表让锁定即时生效。 */
|
||||||
@@ -608,9 +653,9 @@ onMounted(async () => {
|
|||||||
{{ latestSyncText }}
|
{{ latestSyncText }}
|
||||||
</span>
|
</span>
|
||||||
<div class="flex-1" />
|
<div class="flex-1" />
|
||||||
<button v-if="canManage" type="button" class="btn-ghost" :disabled="syncing" @click="doSync">
|
<ElButton v-if="canManage" :disabled="syncing" :loading="syncing" @click="doSync">
|
||||||
{{ syncing ? t('workspace.orderDeliveryReply.syncing') : t('workspace.orderDeliveryReply.syncNow') }}
|
{{ syncing ? t('workspace.orderDeliveryReply.syncing') : t('workspace.orderDeliveryReply.syncNow') }}
|
||||||
</button>
|
</ElButton>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 搜索区:合并关键词搜索(订单/产品/客户命中任一字段),shrink-0 防压缩;surface-panel 为设计系统 L2 区块容器(无 hover 阴影)。
|
<!-- 搜索区:合并关键词搜索(订单/产品/客户命中任一字段),shrink-0 防压缩;surface-panel 为设计系统 L2 区块容器(无 hover 阴影)。
|
||||||
@@ -618,40 +663,55 @@ onMounted(async () => {
|
|||||||
字段含义由输入框 placeholder / 选项承担,无障碍语义用 aria-label 保留(复用 filterKeyword 等 i18n 键)。
|
字段含义由输入框 placeholder / 选项承担,无障碍语义用 aria-label 保留(复用 filterKeyword 等 i18n 键)。
|
||||||
输入控件显式 text-sm(14px)+h-9(36px):与 .contract-filter-input(14px/36px/圆角8px)渲染规格逐项一致 -->
|
输入控件显式 text-sm(14px)+h-9(36px):与 .contract-filter-input(14px/36px/圆角8px)渲染规格逐项一致 -->
|
||||||
<div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2.5">
|
<div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2.5">
|
||||||
<input v-model="filters.keyword" class="input-field h-9 w-auto min-w-[340px] rounded-lg px-3 py-1 text-sm" :placeholder="t('workspace.orderDeliveryReply.filterKeywordPh')" :aria-label="t('workspace.orderDeliveryReply.filterKeyword')" @keyup.enter="doSearch" />
|
<ElInput
|
||||||
<input v-model="filters.order_date" type="date" class="input-field h-9 w-auto rounded-lg px-3 py-1 text-sm" :aria-label="t('workspace.orderDeliveryReply.filterOrderDate')" />
|
v-model="filters.keyword"
|
||||||
<!-- 状态筛选选择即生效(无需再点查询);其余条件仍由「查询」统一提交 -->
|
class="order-reply-keyword"
|
||||||
<select v-model="filters.status" class="select-field h-9 w-auto min-w-[140px] rounded-lg px-3 py-1 text-sm" :aria-label="t('workspace.orderDeliveryReply.filterStatus')" @change="doSearch">
|
clearable
|
||||||
<option value="">{{ t('workspace.orderDeliveryReply.statusAll') }}</option>
|
:placeholder="t('workspace.orderDeliveryReply.filterKeywordPh')"
|
||||||
<option value="replied">{{ t('workspace.orderDeliveryReply.statusReplied') }}</option>
|
:aria-label="t('workspace.orderDeliveryReply.filterKeyword')"
|
||||||
<option value="not_fully_replied">{{ t('workspace.orderDeliveryReply.statusNotFully') }}</option>
|
@keyup.enter="doSearch"
|
||||||
</select>
|
/>
|
||||||
<!-- 查询/重置:text-sm(14px)+font-semibold(600)+h-9(36px),与合同付款预警 .contract-filter-submit 完全一致 -->
|
<ElDatePicker
|
||||||
<button type="button" class="btn-primary h-9 text-sm font-semibold" @click="doSearch">{{ t('workspace.orderDeliveryReply.search') }}</button>
|
:model-value="filters.order_date || undefined"
|
||||||
<button type="button" class="btn-ghost h-9 text-sm font-semibold" @click="doReset">{{ t('workspace.orderDeliveryReply.reset') }}</button>
|
type="date"
|
||||||
|
value-format="YYYY-MM-DD"
|
||||||
|
:aria-label="t('workspace.orderDeliveryReply.filterOrderDate')"
|
||||||
|
@update:model-value="filters.order_date = dateText($event)"
|
||||||
|
/>
|
||||||
|
<ElSelect
|
||||||
|
class="order-reply-status"
|
||||||
|
:model-value="filters.status || undefined"
|
||||||
|
clearable
|
||||||
|
:placeholder="t('workspace.orderDeliveryReply.statusAll')"
|
||||||
|
:aria-label="t('workspace.orderDeliveryReply.filterStatus')"
|
||||||
|
@update:model-value="onFilterStatus"
|
||||||
|
>
|
||||||
|
<ElOption value="replied" :label="t('workspace.orderDeliveryReply.statusReplied')" />
|
||||||
|
<ElOption value="not_fully_replied" :label="t('workspace.orderDeliveryReply.statusNotFully')" />
|
||||||
|
</ElSelect>
|
||||||
|
<ElButton type="primary" @click="doSearch">{{ t('workspace.orderDeliveryReply.search') }}</ElButton>
|
||||||
|
<ElButton @click="doReset">{{ t('workspace.orderDeliveryReply.reset') }}</ElButton>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 工具栏:全选 + 联合回复 + 批量通知(shrink-0 防压缩,py-2 紧凑高度) -->
|
<!-- 工具栏:全选 + 联合回复 + 批量通知(shrink-0 防压缩,py-2 紧凑高度) -->
|
||||||
<div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2">
|
<div class="surface-panel flex shrink-0 flex-wrap items-center gap-3 px-4 py-2">
|
||||||
<label class="flex items-center gap-2 text-primary">
|
<ElCheckbox :model-value="allChecked" :indeterminate="someChecked" @change="togglePageAll(Boolean($event))">
|
||||||
<input type="checkbox" class="admin-checkbox" :checked="allChecked" :indeterminate.prop="someChecked" @change="togglePageAll(($event.target as HTMLInputElement).checked)" />
|
|
||||||
{{ t('workspace.orderDeliveryReply.selectAll') }}
|
{{ t('workspace.orderDeliveryReply.selectAll') }}
|
||||||
</label>
|
</ElCheckbox>
|
||||||
<span class="text-muted">{{ t('workspace.orderDeliveryReply.selectedCount', { count: selectedLines.length }) }}</span>
|
<span class="text-muted">{{ t('workspace.orderDeliveryReply.selectedCount', { count: selectedLines.length }) }}</span>
|
||||||
<template v-if="canManage">
|
<template v-if="canManage">
|
||||||
<button type="button" class="btn-primary h-9 text-sm font-semibold" :disabled="selectedLines.length === 0" @click="openBatchReply">
|
<ElButton type="primary" :disabled="selectedLines.length === 0" @click="openBatchReply">
|
||||||
{{ t('workspace.orderDeliveryReply.batchReply') }}
|
{{ t('workspace.orderDeliveryReply.batchReply') }}
|
||||||
</button>
|
</ElButton>
|
||||||
<button type="button" class="btn-primary h-9 text-sm font-semibold" :disabled="notifiableSelected.length === 0 || notifying" @click="requestNotifyBatch">
|
<ElButton type="primary" :disabled="notifiableSelected.length === 0 || notifying" :loading="notifying" @click="requestNotifyBatch">
|
||||||
{{ t('workspace.orderDeliveryReply.batchNotify') }}
|
{{ t('workspace.orderDeliveryReply.batchNotify') }}
|
||||||
</button>
|
</ElButton>
|
||||||
</template>
|
</template>
|
||||||
<div class="flex-1" />
|
<div class="flex-1" />
|
||||||
<!-- 导出 Excel(2026-10-09 增补,原提示文字胶囊取消):按当前筛选导出全部行 -->
|
<!-- 导出 Excel(2026-10-09 增补,原提示文字胶囊取消):按当前筛选导出全部行 -->
|
||||||
<button type="button" class="btn-primary h-9 text-sm font-semibold" :disabled="exporting" @click="doExportExcel">
|
<ElButton type="primary" :icon="Download" :disabled="exporting" :loading="exporting" @click="doExportExcel">
|
||||||
<Download class="h-4 w-4" aria-hidden="true" />
|
|
||||||
{{ t('workspace.orderDeliveryReply.exportExcel') }}
|
{{ t('workspace.orderDeliveryReply.exportExcel') }}
|
||||||
</button>
|
</ElButton>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 列表 -->
|
<!-- 列表 -->
|
||||||
@@ -864,67 +924,126 @@ onMounted(async () => {
|
|||||||
@update:page-size="changePageSize"
|
@update:page-size="changePageSize"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<!-- 回复弹窗:dialog-overlay/panel/header/body/footer 设计系统 L2 结构 -->
|
<ElDialog
|
||||||
<div v-if="modalVisible" class="dialog-overlay items-center" @click.self="modalVisible = false">
|
v-model="modalVisible"
|
||||||
<div class="dialog-panel max-h-[88vh] w-[min(960px,94vw)]">
|
:title="modalTitle"
|
||||||
<div class="dialog-header">
|
width="960px"
|
||||||
<h3 class="font-bold text-primary">{{ modalTitle }}</h3>
|
align-center
|
||||||
<button type="button" class="btn-ghost h-8 w-8 px-0 text-lg leading-none" @click="modalVisible = false">×</button>
|
append-to-body
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
>
|
||||||
|
<div v-if="modalMode === 'batch'" class="order-reply-quick">
|
||||||
|
<span>{{ t('workspace.orderDeliveryReply.quickDate') }}</span>
|
||||||
|
<ElDatePicker
|
||||||
|
:model-value="quickDate || undefined"
|
||||||
|
type="date"
|
||||||
|
value-format="YYYY-MM-DD"
|
||||||
|
@update:model-value="quickDate = dateText($event)"
|
||||||
|
/>
|
||||||
|
<ElButton @click="applyQuickDate">{{ t('workspace.orderDeliveryReply.applyQuickDate') }}</ElButton>
|
||||||
|
<span>{{ t('workspace.orderDeliveryReply.modalHint') }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-for="entry in modalLines" :key="lineKey(entry.line)" class="order-reply-line">
|
||||||
|
<div class="order-reply-line__head">
|
||||||
|
<span class="order-reply-line__no">{{ entry.line.order_no }}</span>
|
||||||
|
<span>{{ t('workspace.orderDeliveryReply.itemLabel', { item: entry.line.line_no }) }}</span>
|
||||||
|
<span>{{ entry.line.customer_no }} · {{ entry.line.customer_short_name }}</span>
|
||||||
|
<span>{{ entry.line.part_no }} · {{ entry.line.part_name }}</span>
|
||||||
|
<span class="order-reply-line__qty">
|
||||||
|
{{ t('workspace.orderDeliveryReply.orderQtyLabel', { qty: entry.line.qty ?? 0, unit: entry.line.unit || '' }) }}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="dialog-body">
|
<div class="order-reply-line__body">
|
||||||
<!-- 快速统一交期:仅联合回复弹窗显示;单行回复/修改回复弹窗已取消该区(2026-10-07),直接逐批次填写 -->
|
<div v-for="(batch, idx) in entry.batches" :key="idx" class="order-reply-batch">
|
||||||
<div v-if="modalMode === 'batch'" class="flex flex-wrap items-end gap-3 rounded-xl border border-default bg-surface-soft px-4 py-3">
|
<ElDatePicker
|
||||||
<label class="flex flex-col gap-1 text-muted">
|
:model-value="batch.planned_date || undefined"
|
||||||
{{ t('workspace.orderDeliveryReply.quickDate') }}
|
type="date"
|
||||||
<input v-model="quickDate" type="date" class="input-field h-9 w-auto rounded-lg px-3 py-1.5" />
|
value-format="YYYY-MM-DD"
|
||||||
</label>
|
@update:model-value="batch.planned_date = dateText($event)"
|
||||||
<button type="button" class="btn-secondary btn-sm h-9" @click="applyQuickDate">
|
/>
|
||||||
{{ t('workspace.orderDeliveryReply.applyQuickDate') }}
|
<ElInput v-model="batch.qty" type="number" :placeholder="t('workspace.orderDeliveryReply.qtyPh')" />
|
||||||
</button>
|
<ElInput v-model="batch.remark" :placeholder="t('workspace.orderDeliveryReply.remarkPh')" />
|
||||||
<span class="text-muted">{{ t('workspace.orderDeliveryReply.modalHint') }}</span>
|
<ElButton link type="danger" :title="t('workspace.orderDeliveryReply.removeBatch')" @click="entry.batches.splice(idx, 1)">✕</ElButton>
|
||||||
</div>
|
</div>
|
||||||
<!-- 每行批次编辑器 -->
|
<ElButton class="order-reply-add" @click="entry.batches.push({ planned_date: '', qty: '', remark: '' })">
|
||||||
<div v-for="entry in modalLines" :key="lineKey(entry.line)" class="overflow-hidden rounded-xl border border-default">
|
{{ t('workspace.orderDeliveryReply.addBatch') }}
|
||||||
<div class="flex flex-wrap items-center gap-2 bg-surface-soft px-3 py-2">
|
</ElButton>
|
||||||
<span class="rounded bg-surface-strong px-2 py-0.5 font-semibold text-primary">{{ entry.line.order_no }}</span>
|
<p v-if="lineIssueText(entry)" class="order-reply-issue">{{ lineIssueText(entry) }}</p>
|
||||||
<span>{{ t('workspace.orderDeliveryReply.itemLabel', { item: entry.line.line_no }) }}</span>
|
|
||||||
<span class="text-muted">{{ entry.line.customer_no }} · {{ entry.line.customer_short_name }}</span>
|
|
||||||
<span class="text-muted">{{ entry.line.part_no }} · {{ entry.line.part_name }}</span>
|
|
||||||
<span class="ml-auto whitespace-nowrap">
|
|
||||||
{{ t('workspace.orderDeliveryReply.orderQtyLabel', { qty: entry.line.qty ?? 0, unit: entry.line.unit || '' }) }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div class="flex flex-col gap-2 px-3 py-3">
|
|
||||||
<div v-for="(batch, idx) in entry.batches" :key="idx" class="grid grid-cols-[170px_120px_1fr_40px] items-center gap-2">
|
|
||||||
<input v-model="batch.planned_date" type="date" class="input-field h-9 rounded-lg px-2 py-1.5" />
|
|
||||||
<input v-model="batch.qty" type="number" min="0" :placeholder="t('workspace.orderDeliveryReply.qtyPh')" class="input-field h-9 rounded-lg px-2 py-1.5" />
|
|
||||||
<input v-model="batch.remark" :placeholder="t('workspace.orderDeliveryReply.remarkPh')" class="input-field h-9 rounded-lg px-2 py-1.5" />
|
|
||||||
<button type="button" class="btn-danger btn-sm" :title="t('workspace.orderDeliveryReply.removeBatch')" @click="entry.batches.splice(idx, 1)">✕</button>
|
|
||||||
</div>
|
|
||||||
<button type="button" class="w-full rounded-lg border border-dashed border-default py-2 text-brand-600 transition-colors hover-surface-soft" @click="entry.batches.push({ planned_date: '', qty: '', remark: '' })">
|
|
||||||
{{ t('workspace.orderDeliveryReply.addBatch') }}
|
|
||||||
</button>
|
|
||||||
<!-- 行级实时校验提示:缺交期/缺数量按批次序号指出,合计不等给出已填/应填;随填写实时切换 -->
|
|
||||||
<p v-if="lineIssueText(entry)" class="text-status-error">{{ lineIssueText(entry) }}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="dialog-footer">
|
|
||||||
<button type="button" class="btn-secondary" @click="modalVisible = false">{{ t('common.cancel') }}</button>
|
|
||||||
<button type="button" class="btn-primary" :disabled="saving" @click="saveReplies">
|
|
||||||
{{ saving ? t('workspace.orderDeliveryReply.saving') : t('workspace.orderDeliveryReply.saveReply') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<template #footer>
|
||||||
|
<ElButton @click="modalVisible = false">{{ t('common.cancel') }}</ElButton>
|
||||||
<!-- 批量通知二次确认:共享 DeleteConfirmDialog(primary 语气,非删除;确认/取消文案用组件默认 i18n) -->
|
<ElButton type="primary" :loading="saving" :disabled="saving" @click="saveReplies">
|
||||||
<DeleteConfirmDialog
|
{{ saving ? t('workspace.orderDeliveryReply.saving') : t('workspace.orderDeliveryReply.saveReply') }}
|
||||||
v-model="notifyConfirmVisible"
|
</ElButton>
|
||||||
:title="t('workspace.orderDeliveryReply.batchNotify')"
|
</template>
|
||||||
:message="t('workspace.orderDeliveryReply.notifyBatchConfirm', { count: notifiableSelected.length })"
|
</ElDialog>
|
||||||
confirm-tone="primary"
|
|
||||||
@confirm="doNotifyBatch"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.order-reply-keyword {
|
||||||
|
width: min(100%, 22rem);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-status {
|
||||||
|
width: 11rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-quick,
|
||||||
|
.order-reply-line__head,
|
||||||
|
.order-reply-batch {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-quick,
|
||||||
|
.order-reply-line {
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-line {
|
||||||
|
overflow: hidden;
|
||||||
|
border: 1px solid var(--el-border-color-lighter);
|
||||||
|
border-radius: var(--el-border-radius-base);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-line__head {
|
||||||
|
padding: 8px 12px;
|
||||||
|
background: var(--el-fill-color-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-line__no {
|
||||||
|
padding: 0 8px;
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--el-fill-color);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-line__qty {
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-line__body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-batch {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 170px 120px minmax(0, 1fr) 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-add {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-reply-issue {
|
||||||
|
margin: 0;
|
||||||
|
color: var(--el-color-danger);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,26 +1,90 @@
|
|||||||
<!--
|
<!--
|
||||||
features/shipping-notice/customers/ShippingCustomersPage.vue
|
features/shipping-notice/customers/ShippingCustomersPage.vue
|
||||||
用途:货代客户主数据管理入口,提供列表、识别证据和期初导入工作台。
|
用途:货代客户主数据管理入口,提供列表、识别证据和期初导入工作台。
|
||||||
依赖:useShippingCustomersAdmin、PaginationBar、三个域内组件。
|
依赖:useShippingCustomersAdmin、element-plus、域内弹窗与影子质量面板。
|
||||||
逻辑:路由加载后查询客户;页面只组合展示与事件,业务状态由 composable 管理。
|
逻辑:路由加载后查询客户;页面只组合展示与事件,业务状态由 composable 管理。
|
||||||
|
Element 样式只在本页引入;停用与证据变更的确认在 composable 内完成。
|
||||||
-->
|
-->
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { onMounted, watch } from 'vue';
|
import { onMounted, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { Edit, FileSpreadsheet, Fingerprint, GitMerge, History, Plus, Search, Trash2, UserX } from 'lucide-vue-next';
|
import {
|
||||||
|
Clock,
|
||||||
|
Connection,
|
||||||
|
Delete,
|
||||||
|
Document,
|
||||||
|
Edit,
|
||||||
|
Key,
|
||||||
|
Plus,
|
||||||
|
Remove,
|
||||||
|
Search,
|
||||||
|
} from '@element-plus/icons-vue';
|
||||||
|
import {
|
||||||
|
ElButton,
|
||||||
|
ElInput,
|
||||||
|
ElLoading,
|
||||||
|
ElOption,
|
||||||
|
ElPagination,
|
||||||
|
ElSelect,
|
||||||
|
ElSpace,
|
||||||
|
ElTable,
|
||||||
|
ElTableColumn,
|
||||||
|
ElTag,
|
||||||
|
ElText,
|
||||||
|
} from 'element-plus';
|
||||||
|
import 'element-plus/dist/index.css';
|
||||||
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
|
import '@/shared/styles/element-theme.css';
|
||||||
import CustomerDeleteDialog from './components/CustomerDeleteDialog.vue';
|
import CustomerDeleteDialog from './components/CustomerDeleteDialog.vue';
|
||||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
|
||||||
import CustomerMergeDialog from './components/CustomerMergeDialog.vue';
|
import CustomerMergeDialog from './components/CustomerMergeDialog.vue';
|
||||||
import PaginationBar from '@/shared/components/PaginationBar.vue';
|
|
||||||
import CustomerFormModal from './components/CustomerFormModal.vue';
|
import CustomerFormModal from './components/CustomerFormModal.vue';
|
||||||
import CustomerIdentifiersPanel from './components/CustomerIdentifiersPanel.vue';
|
import CustomerIdentifiersPanel from './components/CustomerIdentifiersPanel.vue';
|
||||||
import CustomerImportDialog from './components/CustomerImportDialog.vue';
|
import CustomerImportDialog from './components/CustomerImportDialog.vue';
|
||||||
import CustomerShadowQualityPanel from './components/CustomerShadowQualityPanel.vue';
|
import CustomerShadowQualityPanel from './components/CustomerShadowQualityPanel.vue';
|
||||||
import CustomerLifecyclePanel from './components/CustomerLifecyclePanel.vue';
|
import CustomerLifecyclePanel from './components/CustomerLifecyclePanel.vue';
|
||||||
import { useShippingCustomersAdmin } from './composables/useShippingCustomersAdmin';
|
import { useShippingCustomersAdmin } from './composables/useShippingCustomersAdmin';
|
||||||
|
import type { ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
|
||||||
|
|
||||||
|
const vLoading = ElLoading.directive;
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const admin = useShippingCustomersAdmin();
|
const admin = useShippingCustomersAdmin();
|
||||||
|
const pageSizes = [10, 20, 50, 100];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 状态筛选。清空时写回空字符串,列表仍按全部状态查询。
|
||||||
|
* @param value - 选中的状态;清空为 undefined
|
||||||
|
*/
|
||||||
|
function onStatusFilter(value: string | undefined): void {
|
||||||
|
admin.statusFilter.value = value ?? '';
|
||||||
|
void admin.searchCustomers();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 翻页。每页条数不变,监听会重新拉列表。
|
||||||
|
* @param page - 1-based 页码
|
||||||
|
*/
|
||||||
|
function onPageChange(page: number): void {
|
||||||
|
admin.page.value = page;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修改每页条数并回到第一页,与原分页条一致。
|
||||||
|
* @param size - 新的每页条数
|
||||||
|
*/
|
||||||
|
function onPageSizeChange(size: number): void {
|
||||||
|
admin.pageSize.value = size;
|
||||||
|
admin.page.value = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 状态标签颜色:启用成功,停用信息,归并警告。
|
||||||
|
* @param status - 客户状态
|
||||||
|
*/
|
||||||
|
function statusTagType(status: string): 'success' | 'info' | 'warning' {
|
||||||
|
if (status === 'active') return 'success';
|
||||||
|
if (status === 'merged') return 'warning';
|
||||||
|
return 'info';
|
||||||
|
}
|
||||||
|
|
||||||
/** 页码或每页条数改变时重新读取服务端分页。 */
|
/** 页码或每页条数改变时重新读取服务端分页。 */
|
||||||
watch([admin.page, admin.pageSize], () => { void admin.loadCustomers(); });
|
watch([admin.page, admin.pageSize], () => { void admin.loadCustomers(); });
|
||||||
@@ -30,67 +94,116 @@ onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowRepor
|
|||||||
<template>
|
<template>
|
||||||
<section class="admin-table-section animate-fade-in-up">
|
<section class="admin-table-section animate-fade-in-up">
|
||||||
<div class="admin-table-header admin-table-header--stacked">
|
<div class="admin-table-header admin-table-header--stacked">
|
||||||
<div><h2 class="section-title">{{ t('admin.shippingCustomers.title') }}</h2><p class="section-desc mt-1">{{ t('admin.shippingCustomers.subtitle') }}</p></div>
|
<div>
|
||||||
<div class="flex flex-wrap gap-2">
|
<h2 class="section-title">{{ t('admin.shippingCustomers.title') }}</h2>
|
||||||
<button type="button" class="btn-ghost flex items-center gap-2" @click="admin.openImport"><FileSpreadsheet class="w-4 h-4" />{{ t('admin.shippingCustomers.importButton') }}</button>
|
<p class="section-desc mt-1">{{ t('admin.shippingCustomers.subtitle') }}</p>
|
||||||
<button type="button" class="btn-primary flex items-center gap-2" @click="admin.openCreateCustomer"><Plus class="w-4 h-4" />{{ t('admin.shippingCustomers.add') }}</button>
|
|
||||||
</div>
|
</div>
|
||||||
|
<ElSpace wrap>
|
||||||
|
<ElButton :icon="Document" @click="admin.openImport">{{ t('admin.shippingCustomers.importButton') }}</ElButton>
|
||||||
|
<ElButton type="primary" :icon="Plus" @click="admin.openCreateCustomer">{{ t('admin.shippingCustomers.add') }}</ElButton>
|
||||||
|
</ElSpace>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="admin-table-filters--inline gap-3">
|
<div class="customers-filters">
|
||||||
<div class="relative flex-1 min-w-[220px] max-w-md">
|
<ElInput
|
||||||
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted" />
|
v-model="admin.searchQuery.value"
|
||||||
<input v-model="admin.searchQuery.value" type="search" class="admin-table-filter-input w-full pl-9" :placeholder="t('admin.shippingCustomers.searchPlaceholder')" @keyup.enter="admin.searchCustomers" />
|
clearable
|
||||||
</div>
|
class="customers-filter-search"
|
||||||
<select v-model="admin.statusFilter.value" class="admin-table-filter-input" @change="admin.searchCustomers">
|
:prefix-icon="Search"
|
||||||
<option value="">{{ t('admin.shippingCustomers.status.all') }}</option>
|
:placeholder="t('admin.shippingCustomers.searchPlaceholder')"
|
||||||
<option value="active">{{ t('admin.shippingCustomers.status.active') }}</option>
|
@keyup.enter="admin.searchCustomers"
|
||||||
<option value="inactive">{{ t('admin.shippingCustomers.status.inactive') }}</option>
|
/>
|
||||||
<option value="merged">{{ t('admin.shippingCustomers.status.merged') }}</option>
|
<ElSelect
|
||||||
</select>
|
class="customers-filter-status"
|
||||||
<button type="button" class="btn-ghost" @click="admin.searchCustomers">{{ t('admin.shippingCustomers.search') }}</button>
|
:model-value="admin.statusFilter.value || undefined"
|
||||||
|
clearable
|
||||||
|
:placeholder="t('admin.shippingCustomers.status.all')"
|
||||||
|
@update:model-value="onStatusFilter"
|
||||||
|
>
|
||||||
|
<ElOption value="active" :label="t('admin.shippingCustomers.status.active')" />
|
||||||
|
<ElOption value="inactive" :label="t('admin.shippingCustomers.status.inactive')" />
|
||||||
|
<ElOption value="merged" :label="t('admin.shippingCustomers.status.merged')" />
|
||||||
|
</ElSelect>
|
||||||
|
<ElButton @click="admin.searchCustomers">{{ t('admin.shippingCustomers.search') }}</ElButton>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-if="admin.isLoading.value" class="flex justify-center py-20"><div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" /></div>
|
<ElTable
|
||||||
<div v-else class="admin-table-wrap">
|
v-loading="admin.isLoading.value"
|
||||||
<table class="admin-table min-w-[860px]">
|
:data="admin.customers.value"
|
||||||
<thead><tr>
|
row-key="id"
|
||||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.name') }}</th>
|
:empty-text="t('admin.shippingCustomers.empty')"
|
||||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.shortCode') }}</th>
|
>
|
||||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.status') }}</th>
|
<ElTableColumn :label="t('admin.shippingCustomers.headers.name')" min-width="180">
|
||||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.odmIds') }}</th>
|
<template #default="{ row }">
|
||||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.identityEvidences') }}</th>
|
<div>{{ (row as ShippingCustomerRow).standard_name }}</div>
|
||||||
<th class="px-5 py-4 text-left">{{ t('admin.shippingCustomers.headers.notices') }}</th>
|
<ElText v-if="(row as ShippingCustomerRow).remark" type="info" size="small">{{ (row as ShippingCustomerRow).remark }}</ElText>
|
||||||
<th class="px-5 py-4 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th>
|
</template>
|
||||||
</tr></thead>
|
</ElTableColumn>
|
||||||
<tbody>
|
<ElTableColumn :label="t('admin.shippingCustomers.headers.shortCode')" min-width="100">
|
||||||
<tr v-if="admin.customers.value.length === 0"><td colspan="7" class="admin-table-empty px-5">{{ t('admin.shippingCustomers.empty') }}</td></tr>
|
<template #default="{ row }">{{ (row as ShippingCustomerRow).short_code }}</template>
|
||||||
<tr v-for="customer in admin.customers.value" :key="customer.id">
|
</ElTableColumn>
|
||||||
<td class="px-5 py-4"><div class="font-medium text-primary">{{ customer.standard_name }}</div><div v-if="customer.remark" class="text-xs text-muted truncate max-w-sm">{{ customer.remark }}</div></td>
|
<ElTableColumn :label="t('admin.shippingCustomers.headers.status')" min-width="100">
|
||||||
<td class="px-5 py-4 font-mono text-sm">{{ customer.short_code }}</td>
|
<template #default="{ row }">
|
||||||
<td class="px-5 py-4"><span class="text-sm" :class="customer.status === 'active' ? 'text-emerald-600' : 'text-muted'">{{ t(`admin.shippingCustomers.status.${customer.status}`) }}</span></td>
|
<ElTag :type="statusTagType((row as ShippingCustomerRow).status)" effect="light">
|
||||||
<td class="px-5 py-4 text-sm">
|
{{ t(`admin.shippingCustomers.status.${(row as ShippingCustomerRow).status}`) }}
|
||||||
<span v-if="customer.odm_ids?.length" class="font-mono text-xs">{{ customer.odm_ids.join(', ') }}</span>
|
</ElTag>
|
||||||
<span v-else class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsUnlimited') }}</span>
|
</template>
|
||||||
</td>
|
</ElTableColumn>
|
||||||
<td class="px-5 py-4 text-sm">{{ customer.identity_evidence_count || 0 }}</td>
|
<ElTableColumn :label="t('admin.shippingCustomers.headers.odmIds')" min-width="140">
|
||||||
<td class="px-5 py-4 text-sm">{{ customer.notice_count }}</td>
|
<template #default="{ row }">
|
||||||
<td class="px-5 py-4"><div class="flex justify-end gap-1">
|
<span v-if="(row as ShippingCustomerRow).odm_ids?.length">{{ (row as ShippingCustomerRow).odm_ids?.join(', ') }}</span>
|
||||||
<button type="button" class="p-2 text-indigo-600 hover:bg-indigo-50 rounded-lg" :title="t('admin.shippingCustomers.identifiers.title')" @click="admin.openIdentifiers(customer)"><Fingerprint class="w-4 h-4" /></button>
|
<ElText v-else type="info" size="small">{{ t('admin.shippingCustomers.fields.odmIdsUnlimited') }}</ElText>
|
||||||
<button type="button" class="p-2 text-slate-600 hover:bg-slate-100 rounded-lg" :title="t('admin.shippingCustomers.lifecycle.open')" @click="admin.openLifecycleTimeline(customer)"><History class="w-4 h-4" /></button>
|
</template>
|
||||||
<button type="button" class="p-2 text-indigo-600 hover:bg-indigo-50 rounded-lg" :title="t('admin.edit')" @click="admin.openEditCustomer(customer)"><Edit class="w-4 h-4" /></button>
|
</ElTableColumn>
|
||||||
<button v-if="customer.status === 'active'" type="button" class="p-2 text-red-600 hover:bg-red-50 rounded-lg" :title="t('admin.shippingCustomers.deactivate')" @click="admin.deactivateCustomer(customer)"><UserX class="w-4 h-4" /></button>
|
<ElTableColumn :label="t('admin.shippingCustomers.headers.identityEvidences')" min-width="100">
|
||||||
<button v-if="customer.status !== 'merged'" type="button" class="p-2 text-amber-700 hover:bg-amber-50 rounded-lg" :title="t('admin.shippingCustomers.mergeDialog.open')" @click="admin.openMergeCustomer(customer)"><GitMerge class="w-4 h-4" /></button>
|
<template #default="{ row }">{{ (row as ShippingCustomerRow).identity_evidence_count || 0 }}</template>
|
||||||
<button type="button" class="p-2 text-red-700 hover:bg-red-50 rounded-lg" :title="t('admin.shippingCustomers.deleteDialog.open')" @click="admin.openDeleteCustomer(customer)"><Trash2 class="w-4 h-4" /></button>
|
</ElTableColumn>
|
||||||
</div></td>
|
<ElTableColumn prop="notice_count" :label="t('admin.shippingCustomers.headers.notices')" min-width="80" />
|
||||||
</tr>
|
<ElTableColumn :label="t('admin.shippingCustomers.headers.actions')" width="280" align="right">
|
||||||
</tbody>
|
<template #default="{ row }">
|
||||||
</table>
|
<ElButton link type="primary" :icon="Key" :title="t('admin.shippingCustomers.identifiers.title')" @click="admin.openIdentifiers(row as ShippingCustomerRow)" />
|
||||||
|
<ElButton link type="primary" :icon="Clock" :title="t('admin.shippingCustomers.lifecycle.open')" @click="admin.openLifecycleTimeline(row as ShippingCustomerRow)" />
|
||||||
|
<ElButton link type="primary" :icon="Edit" :title="t('admin.edit')" @click="admin.openEditCustomer(row as ShippingCustomerRow)" />
|
||||||
|
<ElButton
|
||||||
|
v-if="(row as ShippingCustomerRow).status === 'active'"
|
||||||
|
link
|
||||||
|
type="danger"
|
||||||
|
:icon="Remove"
|
||||||
|
:title="t('admin.shippingCustomers.deactivate')"
|
||||||
|
@click="admin.deactivateCustomer(row as ShippingCustomerRow)"
|
||||||
|
/>
|
||||||
|
<ElButton
|
||||||
|
v-if="(row as ShippingCustomerRow).status !== 'merged'"
|
||||||
|
link
|
||||||
|
:icon="Connection"
|
||||||
|
:title="t('admin.shippingCustomers.mergeDialog.open')"
|
||||||
|
@click="admin.openMergeCustomer(row as ShippingCustomerRow)"
|
||||||
|
/>
|
||||||
|
<ElButton link type="danger" :icon="Delete" :title="t('admin.shippingCustomers.deleteDialog.open')" @click="admin.openDeleteCustomer(row as ShippingCustomerRow)" />
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
</ElTable>
|
||||||
|
|
||||||
|
<div v-if="admin.total.value > 0" class="customers-pager">
|
||||||
|
<ElPagination
|
||||||
|
:current-page="admin.page.value"
|
||||||
|
:page-size="admin.pageSize.value"
|
||||||
|
:total="admin.total.value"
|
||||||
|
:page-sizes="pageSizes"
|
||||||
|
layout="total, sizes, prev, pager, next"
|
||||||
|
background
|
||||||
|
@current-change="onPageChange"
|
||||||
|
@size-change="onPageSizeChange"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<PaginationBar v-model:page="admin.page.value" v-model:page-size="admin.pageSize.value" :total="admin.total.value" :pages="admin.pages.value" />
|
<CustomerShadowQualityPanel
|
||||||
|
:report="admin.shadowReport.value"
|
||||||
<CustomerShadowQualityPanel :report="admin.shadowReport.value" :customers="admin.importTargetCustomers.value.length ? admin.importTargetCustomers.value : admin.customers.value" :loading="admin.isShadowLoading.value" @refresh="admin.loadShadowReport" @label="admin.labelShadowResolution" />
|
:customers="admin.importTargetCustomers.value.length ? admin.importTargetCustomers.value : admin.customers.value"
|
||||||
|
:loading="admin.isShadowLoading.value"
|
||||||
|
@refresh="admin.loadShadowReport"
|
||||||
|
@label="admin.labelShadowResolution"
|
||||||
|
/>
|
||||||
|
|
||||||
<CustomerFormModal :visible="admin.showCustomerModal.value" :form="admin.customerForm.value" :is-saving="admin.isSaving.value" @close="admin.closeCustomerModal" @save="admin.saveCustomer" />
|
<CustomerFormModal :visible="admin.showCustomerModal.value" :form="admin.customerForm.value" :is-saving="admin.isSaving.value" @close="admin.closeCustomerModal" @save="admin.saveCustomer" />
|
||||||
<CustomerIdentifiersPanel :visible="admin.showIdentifiersPanel.value" :customer="admin.selectedCustomer.value" :published-definitions="admin.publishedEvidenceDefinitions.value" :is-saving="admin.isSaving.value" @close="admin.showIdentifiersPanel.value = false" @add-evidence="admin.addIdentityEvidence" @update-evidence="admin.updateIdentityEvidence" @add-external-ref="admin.addExternalRef" @add-site="admin.addSite" />
|
<CustomerIdentifiersPanel :visible="admin.showIdentifiersPanel.value" :customer="admin.selectedCustomer.value" :published-definitions="admin.publishedEvidenceDefinitions.value" :is-saving="admin.isSaving.value" @close="admin.showIdentifiersPanel.value = false" @add-evidence="admin.addIdentityEvidence" @update-evidence="admin.updateIdentityEvidence" @add-external-ref="admin.addExternalRef" @add-site="admin.addSite" />
|
||||||
@@ -98,18 +211,31 @@ onMounted(() => { void Promise.all([admin.loadCustomers(), admin.loadShadowRepor
|
|||||||
<CustomerDeleteDialog :visible="admin.showDeleteDialog.value" :customer="admin.deleteCustomer.value" :impact="admin.deleteImpact.value" :is-saving="admin.isSaving.value" @close="admin.closeDeleteCustomer" @confirm="admin.confirmDeleteCustomer" />
|
<CustomerDeleteDialog :visible="admin.showDeleteDialog.value" :customer="admin.deleteCustomer.value" :impact="admin.deleteImpact.value" :is-saving="admin.isSaving.value" @close="admin.closeDeleteCustomer" @confirm="admin.confirmDeleteCustomer" />
|
||||||
<CustomerLifecyclePanel :visible="admin.showLifecyclePanel.value" :customer="admin.lifecycleCustomer.value" :timeline="admin.lifecycleTimeline.value" @close="admin.closeLifecycleTimeline" />
|
<CustomerLifecyclePanel :visible="admin.showLifecyclePanel.value" :customer="admin.lifecycleCustomer.value" :timeline="admin.lifecycleTimeline.value" @close="admin.closeLifecycleTimeline" />
|
||||||
<CustomerMergeDialog :visible="admin.showMergeDialog.value" :source="admin.mergeCustomer.value" :impact="admin.mergeImpact.value" :customers="admin.importTargetCustomers.value" :is-saving="admin.isSaving.value" @close="admin.closeMergeCustomer" @preview="admin.previewMergeCustomer" @confirm="admin.confirmMergeCustomer" />
|
<CustomerMergeDialog :visible="admin.showMergeDialog.value" :source="admin.mergeCustomer.value" :impact="admin.mergeImpact.value" :customers="admin.importTargetCustomers.value" :is-saving="admin.isSaving.value" @close="admin.closeMergeCustomer" @preview="admin.previewMergeCustomer" @confirm="admin.confirmMergeCustomer" />
|
||||||
<DeleteConfirmDialog
|
|
||||||
:model-value="admin.pendingReasonAction.value !== null"
|
|
||||||
:title="admin.pendingReasonAction.value?.kind === 'deactivate' ? t('admin.shippingCustomers.deactivate') : t('admin.shippingCustomers.identifiers.title')"
|
|
||||||
:message="admin.pendingReasonAction.value?.kind === 'deactivate' ? t('admin.shippingCustomers.confirmDeactivate', { name: admin.pendingReasonAction.value.customer.standard_name }) : t('admin.shippingCustomers.prompts.identifierChangeReason')"
|
|
||||||
:reason-label="admin.pendingReasonAction.value?.kind === 'deactivate' ? t('admin.shippingCustomers.prompts.deactivateReason') : t('admin.shippingCustomers.prompts.identifierChangeReason')"
|
|
||||||
:reason-placeholder="admin.pendingReasonAction.value?.kind === 'deactivate' ? t('admin.shippingCustomers.prompts.deactivateReason') : t('admin.shippingCustomers.prompts.identifierChangeReason')"
|
|
||||||
reason-required
|
|
||||||
confirm-tone="primary"
|
|
||||||
:confirm-loading="admin.isSaving.value"
|
|
||||||
@update:model-value="(visible) => { if (!visible) admin.cancelReasonAction(); }"
|
|
||||||
@cancel="admin.cancelReasonAction"
|
|
||||||
@confirm="admin.confirmReasonAction"
|
|
||||||
/>
|
|
||||||
</section>
|
</section>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.customers-filters {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 16px 32px;
|
||||||
|
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||||
|
}
|
||||||
|
|
||||||
|
.customers-filter-search {
|
||||||
|
width: 16rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customers-filter-status {
|
||||||
|
width: 11rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customers-pager {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
padding: 16px 32px;
|
||||||
|
border-top: 1px solid var(--el-border-color-lighter);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
+62
-39
@@ -1,12 +1,20 @@
|
|||||||
<!--
|
<!--
|
||||||
features/shipping-notice/customers/components/CustomerDeleteDialog.vue
|
features/shipping-notice/customers/components/CustomerDeleteDialog.vue
|
||||||
用途:展示客户永久删除预检,并收集简码二次确认和删除原因。
|
用途:展示客户永久删除预检,并收集简码二次确认和删除原因。
|
||||||
依赖:customer-master.types、vue-i18n。
|
依赖:customer-master.types、element-plus、vue-i18n。
|
||||||
逻辑:有任何服务端生命周期阻断项时不暴露确认按钮;提交仍由父级调用后端原子校验。
|
逻辑:有任何服务端生命周期阻断项时不暴露确认按钮;提交仍由父级调用后端原子校验。样式由客户页引入。
|
||||||
-->
|
-->
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref, watch } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import {
|
||||||
|
ElButton,
|
||||||
|
ElDialog,
|
||||||
|
ElForm,
|
||||||
|
ElFormItem,
|
||||||
|
ElInput,
|
||||||
|
ElText,
|
||||||
|
} from 'element-plus';
|
||||||
import type { ShippingCustomerLifecycleImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
|
import type { ShippingCustomerLifecycleImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -36,46 +44,61 @@ const canSubmit = computed(() => Boolean(
|
|||||||
&& reason.value.trim()
|
&& reason.value.trim()
|
||||||
&& !props.isSaving,
|
&& !props.isSaving,
|
||||||
));
|
));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交简码与原因。按钮已按 canSubmit 禁用,这里再挡一次空值。
|
||||||
|
*/
|
||||||
|
function submitDelete(): void {
|
||||||
|
if (!canSubmit.value) return;
|
||||||
|
emit('confirm', confirmationShortCode.value, reason.value);
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
<ElDialog
|
||||||
<div class="admin-modal-panel max-w-xl max-h-[92vh] scale-100">
|
:model-value="visible"
|
||||||
<div class="px-6 py-5 border-b border-subtle">
|
:title="t('admin.shippingCustomers.deleteDialog.title')"
|
||||||
<h3 class="section-title text-red-700">{{ t('admin.shippingCustomers.deleteDialog.title') }}</h3>
|
width="680px"
|
||||||
<p class="section-desc mt-1">{{ t('admin.shippingCustomers.deleteDialog.subtitle') }}</p>
|
align-center
|
||||||
|
append-to-body
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
@update:model-value="(open) => { if (!open) emit('close'); }"
|
||||||
|
>
|
||||||
|
<ElText type="info">{{ t('admin.shippingCustomers.deleteDialog.subtitle') }}</ElText>
|
||||||
|
<div v-if="!impact" class="customers-delete-block">{{ t('admin.shippingCustomers.deleteDialog.loading') }}</div>
|
||||||
|
<template v-else>
|
||||||
|
<div class="customers-delete-block">
|
||||||
|
<div>{{ impact.customer.standard_name }} ({{ impact.customer.short_code }})</div>
|
||||||
|
<ElText type="info" size="small">{{ t('admin.shippingCustomers.deleteDialog.identifiers', { count: impact.cascade.identifiers }) }}</ElText>
|
||||||
</div>
|
</div>
|
||||||
<div class="px-6 py-5 space-y-4 overflow-y-auto">
|
<div v-if="!impact.can_delete" class="customers-delete-block">
|
||||||
<div v-if="!impact" class="text-sm text-muted">{{ t('admin.shippingCustomers.deleteDialog.loading') }}</div>
|
<ElText type="danger">{{ t('admin.shippingCustomers.deleteDialog.blocked') }}</ElText>
|
||||||
<template v-else>
|
<ul>
|
||||||
<div class="rounded-lg border border-default bg-surface-secondary p-4 text-sm">
|
<li v-for="[key, count] in blockerEntries" :key="key">{{ t(`admin.shippingCustomers.deleteDialog.blockers.${key}`) }}: {{ count }}</li>
|
||||||
<div class="font-medium text-primary">{{ impact.customer.standard_name }} <span class="font-mono">({{ impact.customer.short_code }})</span></div>
|
</ul>
|
||||||
<div class="mt-1 text-muted">{{ t('admin.shippingCustomers.deleteDialog.identifiers', { count: impact.cascade.identifiers }) }}</div>
|
<ElText type="danger">{{ t('admin.shippingCustomers.deleteDialog.blockedHint') }}</ElText>
|
||||||
</div>
|
|
||||||
<div v-if="!impact.can_delete" class="rounded-lg border border-red-200 bg-red-50 p-4">
|
|
||||||
<div class="font-medium text-red-700">{{ t('admin.shippingCustomers.deleteDialog.blocked') }}</div>
|
|
||||||
<ul class="mt-2 space-y-1 text-sm text-red-700">
|
|
||||||
<li v-for="[key, count] in blockerEntries" :key="key">{{ t(`admin.shippingCustomers.deleteDialog.blockers.${key}`) }}: {{ count }}</li>
|
|
||||||
</ul>
|
|
||||||
<p class="mt-3 text-sm text-red-700">{{ t('admin.shippingCustomers.deleteDialog.blockedHint') }}</p>
|
|
||||||
</div>
|
|
||||||
<template v-else>
|
|
||||||
<p class="text-sm text-red-700">{{ t('admin.shippingCustomers.deleteDialog.warning') }}</p>
|
|
||||||
<label class="block space-y-1.5">
|
|
||||||
<span class="label-field">{{ t('admin.shippingCustomers.deleteDialog.confirmationShortCode', { shortCode: impact.customer.short_code }) }}</span>
|
|
||||||
<input v-model="confirmationShortCode" class="input-field text-sm uppercase" maxlength="6" />
|
|
||||||
</label>
|
|
||||||
<label class="block space-y-1.5">
|
|
||||||
<span class="label-field">{{ t('admin.shippingCustomers.deleteDialog.reason') }}</span>
|
|
||||||
<textarea v-model="reason" rows="3" class="input-field text-sm resize-y" />
|
|
||||||
</label>
|
|
||||||
</template>
|
|
||||||
</template>
|
|
||||||
</div>
|
</div>
|
||||||
<div class="admin-modal-footer">
|
<ElForm v-else label-position="top" @submit.prevent>
|
||||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
<ElText type="danger">{{ t('admin.shippingCustomers.deleteDialog.warning') }}</ElText>
|
||||||
<button v-if="impact?.can_delete" type="button" class="btn-danger" :disabled="!canSubmit" @click="emit('confirm', confirmationShortCode, reason)">{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.deleteDialog.confirm') }}</button>
|
<ElFormItem :label="t('admin.shippingCustomers.deleteDialog.confirmationShortCode', { shortCode: impact.customer.short_code })">
|
||||||
</div>
|
<ElInput v-model="confirmationShortCode" maxlength="6" />
|
||||||
</div>
|
</ElFormItem>
|
||||||
</div>
|
<ElFormItem :label="t('admin.shippingCustomers.deleteDialog.reason')">
|
||||||
|
<ElInput v-model="reason" type="textarea" :rows="3" />
|
||||||
|
</ElFormItem>
|
||||||
|
</ElForm>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
|
||||||
|
<ElButton v-if="impact?.can_delete" type="danger" :loading="isSaving" :disabled="!canSubmit" @click="submitDelete">
|
||||||
|
{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.deleteDialog.confirm') }}
|
||||||
|
</ElButton>
|
||||||
|
</template>
|
||||||
|
</ElDialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.customers-delete-block {
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,11 +1,21 @@
|
|||||||
<!--
|
<!--
|
||||||
features/shipping-notice/customers/components/CustomerFormModal.vue
|
features/shipping-notice/customers/components/CustomerFormModal.vue
|
||||||
用途:创建或编辑货代标准客户。
|
用途:创建或编辑货代标准客户。
|
||||||
依赖:customer-master.types、admin 通用表单样式、vue-i18n。
|
依赖:customer-master.types、element-plus、vue-i18n。
|
||||||
逻辑:父页面传入可变表单;提交事件交由 useShippingCustomersAdmin 保存。
|
逻辑:父页面传入可变表单;提交事件交由 useShippingCustomersAdmin 保存。样式由客户页引入。
|
||||||
-->
|
-->
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import {
|
||||||
|
ElButton,
|
||||||
|
ElDialog,
|
||||||
|
ElForm,
|
||||||
|
ElFormItem,
|
||||||
|
ElInput,
|
||||||
|
ElOption,
|
||||||
|
ElSelect,
|
||||||
|
ElText,
|
||||||
|
} from 'element-plus';
|
||||||
import type { ShippingCustomerFormState } from '@/features/shipping-notice/types/customer-master.types';
|
import type { ShippingCustomerFormState } from '@/features/shipping-notice/types/customer-master.types';
|
||||||
|
|
||||||
defineProps<{ visible: boolean; form: ShippingCustomerFormState; isSaving: boolean }>();
|
defineProps<{ visible: boolean; form: ShippingCustomerFormState; isSaving: boolean }>();
|
||||||
@@ -14,55 +24,65 @@ const { t } = useI18n();
|
|||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
<ElDialog
|
||||||
<div class="admin-modal-panel max-w-lg max-h-[92vh] scale-100">
|
:model-value="visible"
|
||||||
<div class="px-6 py-5 border-b border-subtle">
|
:title="form.id ? t('admin.shippingCustomers.edit') : t('admin.shippingCustomers.add')"
|
||||||
<h3 class="section-title">{{ form.id ? t('admin.shippingCustomers.edit') : t('admin.shippingCustomers.add') }}</h3>
|
width="680px"
|
||||||
|
align-center
|
||||||
|
append-to-body
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
@update:model-value="(open) => { if (!open) emit('close'); }"
|
||||||
|
>
|
||||||
|
<ElForm label-position="top" @submit.prevent>
|
||||||
|
<ElFormItem :label="t('admin.shippingCustomers.fields.standardName')">
|
||||||
|
<ElInput v-model="form.standard_name" />
|
||||||
|
</ElFormItem>
|
||||||
|
<div class="customers-form-grid">
|
||||||
|
<ElFormItem :label="t('admin.shippingCustomers.fields.shortCode')">
|
||||||
|
<ElInput v-model="form.short_code" maxlength="6" />
|
||||||
|
<ElText type="info" size="small">{{ t('admin.shippingCustomers.fields.shortCodeHint') }}</ElText>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem :label="t('admin.shippingCustomers.fields.status')">
|
||||||
|
<ElSelect v-model="form.status">
|
||||||
|
<ElOption value="active" :label="t('admin.shippingCustomers.status.active')" />
|
||||||
|
<ElOption value="inactive" :label="t('admin.shippingCustomers.status.inactive')" />
|
||||||
|
</ElSelect>
|
||||||
|
</ElFormItem>
|
||||||
</div>
|
</div>
|
||||||
<div class="px-6 py-5 space-y-4 overflow-y-auto">
|
<ElFormItem :label="t('admin.shippingCustomers.fields.remark')">
|
||||||
<label class="block space-y-1.5">
|
<ElInput v-model="form.remark" type="textarea" :rows="3" />
|
||||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.standardName') }}</span>
|
</ElFormItem>
|
||||||
<input v-model="form.standard_name" class="input-field text-sm" />
|
<ElFormItem :label="t('admin.shippingCustomers.fields.odmIds')">
|
||||||
</label>
|
<ElInput
|
||||||
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
v-model="form.odm_ids_text"
|
||||||
<label class="block space-y-1.5">
|
type="textarea"
|
||||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.shortCode') }}</span>
|
:rows="3"
|
||||||
<input v-model="form.short_code" maxlength="6" class="input-field text-sm uppercase" />
|
:placeholder="t('admin.shippingCustomers.fields.odmIdsHint')"
|
||||||
<span class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.shortCodeHint') }}</span>
|
/>
|
||||||
</label>
|
<ElText type="info" size="small">{{ t('admin.shippingCustomers.fields.odmIdsHint') }}</ElText>
|
||||||
<label class="block space-y-1.5">
|
</ElFormItem>
|
||||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.status') }}</span>
|
<ElFormItem v-if="form.id" :label="t('admin.shippingCustomers.fields.changeReason')">
|
||||||
<select v-model="form.status" class="input-field text-sm">
|
<ElInput
|
||||||
<option value="active">{{ t('admin.shippingCustomers.status.active') }}</option>
|
v-model="form.reason"
|
||||||
<option value="inactive">{{ t('admin.shippingCustomers.status.inactive') }}</option>
|
type="textarea"
|
||||||
</select>
|
:rows="2"
|
||||||
</label>
|
:placeholder="t('admin.shippingCustomers.fields.changeReasonHint')"
|
||||||
</div>
|
/>
|
||||||
<label class="block space-y-1.5">
|
</ElFormItem>
|
||||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.remark') }}</span>
|
</ElForm>
|
||||||
<textarea v-model="form.remark" rows="3" class="input-field text-sm resize-y" />
|
<template #footer>
|
||||||
</label>
|
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
|
||||||
<label class="block space-y-1.5">
|
<ElButton type="primary" :loading="isSaving" @click="emit('save')">
|
||||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.odmIds') }}</span>
|
{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.save') }}
|
||||||
<textarea
|
</ElButton>
|
||||||
v-model="form.odm_ids_text"
|
</template>
|
||||||
rows="3"
|
</ElDialog>
|
||||||
class="input-field text-sm resize-y font-mono"
|
|
||||||
:placeholder="t('admin.shippingCustomers.fields.odmIdsHint')"
|
|
||||||
/>
|
|
||||||
<span class="text-xs text-muted">{{ t('admin.shippingCustomers.fields.odmIdsHint') }}</span>
|
|
||||||
</label>
|
|
||||||
<label v-if="form.id" class="block space-y-1.5">
|
|
||||||
<span class="label-field">{{ t('admin.shippingCustomers.fields.changeReason') }}</span>
|
|
||||||
<textarea v-model="form.reason" rows="2" class="input-field text-sm resize-y" :placeholder="t('admin.shippingCustomers.fields.changeReasonHint')" />
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
<div class="admin-modal-footer">
|
|
||||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button>
|
|
||||||
<button type="button" class="btn-primary" :disabled="isSaving" @click="emit('save')">
|
|
||||||
{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.save') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.customers-form-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
+204
-42
@@ -1,14 +1,28 @@
|
|||||||
<!--
|
<!--
|
||||||
features/shipping-notice/customers/components/CustomerIdentifiersPanel.vue
|
features/shipping-notice/customers/components/CustomerIdentifiersPanel.vue
|
||||||
用途:维护客户主体和送货站点的全配置识别证据。
|
用途:维护客户主体和送货站点的全配置识别证据。
|
||||||
依赖:customer-master.types、vue-i18n。
|
依赖:customer-master.types、element-plus、vue-i18n。
|
||||||
逻辑:定义目录由服务端按已发布规则集提供;组件不维护类型枚举,也不直接调用 API。
|
逻辑:定义目录由服务端按已发布规则集提供;组件不维护类型枚举,也不直接调用 API。样式由客户页引入。
|
||||||
-->
|
-->
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref, watch } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import {
|
||||||
|
ElButton,
|
||||||
|
ElCheckbox,
|
||||||
|
ElDialog,
|
||||||
|
ElForm,
|
||||||
|
ElFormItem,
|
||||||
|
ElInput,
|
||||||
|
ElOption,
|
||||||
|
ElSelect,
|
||||||
|
ElTable,
|
||||||
|
ElTableColumn,
|
||||||
|
ElText,
|
||||||
|
} from 'element-plus';
|
||||||
import type {
|
import type {
|
||||||
ShippingCustomerRow,
|
ShippingCustomerRow,
|
||||||
|
ShippingIdentityEvidence,
|
||||||
ShippingIdentityEvidenceFormState,
|
ShippingIdentityEvidenceFormState,
|
||||||
ShippingPublishedEvidenceDefinitions,
|
ShippingPublishedEvidenceDefinitions,
|
||||||
} from '@/features/shipping-notice/types/customer-master.types';
|
} from '@/features/shipping-notice/types/customer-master.types';
|
||||||
@@ -81,50 +95,198 @@ const submitSite = (): void => {
|
|||||||
emit('addSite', { ...siteForm.value });
|
emit('addSite', { ...siteForm.value });
|
||||||
siteForm.value = { site_name: '', site_code: '', address: '', city: '', country: '', remark: '' };
|
siteForm.value = { site_name: '', site_code: '', address: '', city: '', country: '', remark: '' };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 证据定义。清空写回空字符串,提交校验仍要求有定义。
|
||||||
|
* @param value - 定义 id;清空为 undefined
|
||||||
|
*/
|
||||||
|
function onDefinitionChange(value: string | undefined): void {
|
||||||
|
form.value.definition_id = value ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 站点目标。清空写回 undefined,与原下拉空值一致。
|
||||||
|
* @param value - 站点 id
|
||||||
|
*/
|
||||||
|
function onSiteTargetChange(value: number | undefined): void {
|
||||||
|
form.value.target_id = value ?? undefined;
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="visible && customer" class="admin-modal-overlay animate-fade-in items-center">
|
<ElDialog
|
||||||
<div class="admin-modal-panel max-w-5xl max-h-[92vh] scale-100">
|
:model-value="visible && Boolean(customer)"
|
||||||
<div class="px-6 py-5 border-b border-subtle flex items-start justify-between gap-4">
|
:title="customer ? `${t('admin.shippingCustomers.identifiers.title')} · ${customer.standard_name} · ${customer.short_code}` : t('admin.shippingCustomers.identifiers.title')"
|
||||||
<div><h3 class="section-title">{{ t('admin.shippingCustomers.identifiers.title') }}</h3><p class="section-desc mt-1">{{ customer.standard_name }} · {{ customer.short_code }}</p></div>
|
width="680px"
|
||||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.close') }}</button>
|
align-center
|
||||||
</div>
|
append-to-body
|
||||||
<div class="px-6 py-5 overflow-y-auto space-y-6">
|
:close-on-click-modal="false"
|
||||||
<section class="rounded-xl border border-default p-4 space-y-4">
|
@update:model-value="(open) => { if (!open) emit('close'); }"
|
||||||
<div><h4 class="font-semibold text-primary">{{ t('admin.shippingCustomers.externalRefs.title') }}</h4><p class="text-xs text-muted mt-1">{{ t('admin.shippingCustomers.externalRefs.hint') }}</p></div>
|
>
|
||||||
<div v-if="customer.external_refs?.length" class="flex flex-wrap gap-2"><span v-for="item in customer.external_refs" :key="item.id" class="badge">{{ item.source_system }} · {{ item.customer_code }}</span></div>
|
<template v-if="customer">
|
||||||
<p v-else class="text-sm text-muted">{{ t('admin.shippingCustomers.externalRefs.empty') }}</p>
|
<section>
|
||||||
<div class="grid grid-cols-1 md:grid-cols-[1fr_1fr_auto] gap-3"><input v-model="externalRefForm.source_system" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.externalRefs.sourceSystem')"><input v-model="externalRefForm.customer_code" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.externalRefs.customerCode')"><button type="button" class="btn-primary" :disabled="isSaving || !externalRefForm.source_system.trim() || !externalRefForm.customer_code.trim()" @click="submitExternalRef">{{ t('admin.add') }}</button></div>
|
<h4>{{ t('admin.shippingCustomers.externalRefs.title') }}</h4>
|
||||||
</section>
|
<ElText type="info" size="small">{{ t('admin.shippingCustomers.externalRefs.hint') }}</ElText>
|
||||||
|
<div v-if="customer.external_refs?.length">
|
||||||
<section class="rounded-xl border border-default p-4 space-y-4">
|
<ElText v-for="item in customer.external_refs" :key="item.id">{{ item.source_system }} · {{ item.customer_code }}</ElText>
|
||||||
<div><h4 class="font-semibold text-primary">{{ t('admin.shippingCustomers.sites.title') }}</h4><p class="text-xs text-muted mt-1">{{ t('admin.shippingCustomers.sites.hint') }}</p></div>
|
</div>
|
||||||
<div v-if="customer.sites?.length" class="grid gap-2"><div v-for="site in customer.sites" :key="site.id" class="rounded-lg bg-surface-soft p-3"><div class="font-medium text-primary">{{ site.site_name }} · {{ site.site_code }}</div><div class="text-xs text-muted mt-1">{{ [site.address, site.city, site.country].filter(Boolean).join(' · ') || '-' }}</div><div v-if="site.identity_evidences?.length" class="mt-2 space-y-1 text-xs text-muted"><div>{{ t('admin.shippingCustomers.identifiers.siteEvidenceCount', { count: site.identity_evidences.length }) }}</div><div v-for="evidence in site.identity_evidences" :key="evidence.id" class="flex items-center justify-between gap-2"><span>{{ evidence.definition?.display_name || evidence.definition?.definition_code || evidence.definition_id }} · {{ evidence.raw_value }}</span><span class="flex gap-2"><button v-if="evidence.status !== 'approved'" type="button" class="btn-ghost text-xs" @click="emit('updateEvidence', evidence.id, { status: 'approved' })">{{ t('admin.shippingCustomers.identifiers.approve') }}</button><button v-if="evidence.status === 'approved' && !evidence.auto_match_allowed && evidence.definition?.max_automation === 'conditional'" type="button" class="btn-ghost text-xs" @click="emit('updateEvidence', evidence.id, { auto_match_allowed: true })">{{ t('admin.shippingCustomers.identifiers.enableAuto') }}</button><button v-if="evidence.status !== 'disabled'" type="button" class="btn-ghost text-xs text-red-600" @click="emit('updateEvidence', evidence.id, { status: 'disabled' })">{{ t('admin.shippingCustomers.identifiers.disable') }}</button></span></div></div></div></div>
|
<ElText v-else type="info">{{ t('admin.shippingCustomers.externalRefs.empty') }}</ElText>
|
||||||
<p v-else class="text-sm text-muted">{{ t('admin.shippingCustomers.sites.empty') }}</p>
|
<ElForm label-position="top">
|
||||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-3"><input v-model="siteForm.site_name" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.siteName')"><input v-model="siteForm.site_code" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.siteCode')"><input v-model="siteForm.address" class="input-field text-sm md:col-span-2" :placeholder="t('admin.shippingCustomers.sites.address')"><input v-model="siteForm.city" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.city')"><input v-model="siteForm.country" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.sites.country')"></div>
|
<div class="customers-id-grid">
|
||||||
<div class="flex justify-end"><button type="button" class="btn-primary" :disabled="isSaving || !siteForm.site_name.trim() || !siteForm.site_code.trim()" @click="submitSite">{{ t('admin.add') }}</button></div>
|
<ElFormItem>
|
||||||
</section>
|
<ElInput v-model="externalRefForm.source_system" :placeholder="t('admin.shippingCustomers.externalRefs.sourceSystem')" />
|
||||||
|
</ElFormItem>
|
||||||
<section class="rounded-xl border border-default p-4 space-y-4">
|
<ElFormItem>
|
||||||
<div><h4 class="font-semibold text-primary">{{ t('admin.shippingCustomers.identifiers.add') }}</h4><p class="text-xs text-muted mt-1">{{ t('admin.shippingCustomers.identifiers.definitionHint') }}</p></div>
|
<ElInput v-model="externalRefForm.customer_code" :placeholder="t('admin.shippingCustomers.externalRefs.customerCode')" />
|
||||||
<p v-if="publishedDefinitions?.disabled_reason" class="text-sm text-amber-700">{{ t('admin.shippingCustomers.identifiers.publishedRuleRequired') }}</p>
|
</ElFormItem>
|
||||||
<div v-else class="grid grid-cols-1 md:grid-cols-3 gap-3">
|
<ElButton type="primary" :disabled="isSaving || !externalRefForm.source_system.trim() || !externalRefForm.customer_code.trim()" @click="submitExternalRef">{{ t('admin.add') }}</ElButton>
|
||||||
<select v-model="form.target_type" class="input-field text-sm"><option value="customer">{{ t('admin.shippingCustomers.identifiers.targets.customer') }}</option><option value="site">{{ t('admin.shippingCustomers.identifiers.targets.site') }}</option></select>
|
|
||||||
<select v-if="form.target_type === 'site'" v-model.number="form.target_id" class="input-field text-sm"><option :value="undefined">{{ t('admin.shippingCustomers.identifiers.selectSite') }}</option><option v-for="site in customer.sites || []" :key="site.id" :value="site.id">{{ site.site_name }} · {{ site.site_code }}</option></select><div v-else class="input-field text-sm bg-surface-soft">{{ customer.standard_name }}</div>
|
|
||||||
<select v-model="form.definition_id" class="input-field text-sm"><option value="">{{ t('admin.shippingCustomers.identifiers.selectDefinition') }}</option><option v-for="definition in currentDefinitions" :key="definition.id" :value="definition.id">{{ definition.display_name }} · {{ definition.context_field?.display_name || definition.context_field?.field_code || '-' }}</option></select>
|
|
||||||
<input v-model="form.raw_value" class="input-field text-sm md:col-span-2" :placeholder="t('admin.shippingCustomers.identifiers.valuePlaceholder')">
|
|
||||||
<select v-model="form.status" class="input-field text-sm"><option value="pending">{{ t('admin.shippingCustomers.identifierStatus.pending') }}</option><option value="approved">{{ t('admin.shippingCustomers.identifierStatus.approved') }}</option></select>
|
|
||||||
<label class="flex items-center gap-2 text-sm text-secondary"><input v-model="form.auto_match_allowed" type="checkbox" :disabled="form.status !== 'approved' || selectedDefinition?.max_automation !== 'conditional'">{{ t('admin.shippingCustomers.identifiers.allowAuto') }}</label>
|
|
||||||
<input v-model="form.remark" class="input-field text-sm" :placeholder="t('admin.shippingCustomers.fields.remark')">
|
|
||||||
</div>
|
</div>
|
||||||
<p v-if="selectedDefinition && selectedDefinition.max_automation === 'none'" class="text-xs text-muted">{{ t('admin.shippingCustomers.identifiers.manualOnly') }}</p>
|
</ElForm>
|
||||||
<div class="flex justify-end"><button type="button" class="btn-primary" :disabled="isSaving || Boolean(publishedDefinitions?.disabled_reason) || !targetReady || !form.definition_id || !form.raw_value.trim()" @click="submitEvidence">{{ t('admin.add') }}</button></div>
|
</section>
|
||||||
</section>
|
|
||||||
|
|
||||||
<section class="rounded-xl border border-default overflow-x-auto"><table class="admin-table min-w-[780px]"><thead><tr><th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.definition') }}</th><th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.value') }}</th><th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.status') }}</th><th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.identifiers.autoMatch') }}</th><th class="px-4 py-3 text-right">{{ t('admin.shippingCustomers.headers.actions') }}</th></tr></thead><tbody><tr v-if="!customer.identity_evidences?.length"><td colspan="5" class="admin-table-empty px-4">{{ t('admin.shippingCustomers.identifiers.empty') }}</td></tr><tr v-for="item in customer.identity_evidences" :key="item.id"><td class="px-4 py-3 text-sm"><div>{{ item.definition?.display_name || item.definition?.definition_code || item.definition_id }}</div><div class="text-xs text-muted">{{ item.definition?.evidence_label }}</div></td><td class="px-4 py-3 text-sm"><div>{{ item.raw_value }}</div><div class="text-xs text-muted">{{ item.normalized_value }}</div></td><td class="px-4 py-3 text-sm">{{ t(`admin.shippingCustomers.identifierStatus.${item.status}`) }}</td><td class="px-4 py-3 text-sm">{{ item.auto_match_allowed ? t('admin.shippingCustomers.yes') : t('admin.shippingCustomers.no') }}</td><td class="px-4 py-3"><div class="flex justify-end gap-2"><button v-if="item.status !== 'approved'" type="button" class="btn-ghost text-xs" @click="emit('updateEvidence', item.id, { status: 'approved' })">{{ t('admin.shippingCustomers.identifiers.approve') }}</button><button v-if="item.status === 'approved' && !item.auto_match_allowed && item.definition?.max_automation === 'conditional'" type="button" class="btn-ghost text-xs" @click="emit('updateEvidence', item.id, { auto_match_allowed: true })">{{ t('admin.shippingCustomers.identifiers.enableAuto') }}</button><button v-if="item.status !== 'disabled'" type="button" class="btn-ghost text-xs text-red-600" @click="emit('updateEvidence', item.id, { status: 'disabled' })">{{ t('admin.shippingCustomers.identifiers.disable') }}</button></div></td></tr></tbody></table></section>
|
<section>
|
||||||
|
<h4>{{ t('admin.shippingCustomers.sites.title') }}</h4>
|
||||||
|
<ElText type="info" size="small">{{ t('admin.shippingCustomers.sites.hint') }}</ElText>
|
||||||
|
<div v-if="customer.sites?.length">
|
||||||
|
<div v-for="site in customer.sites" :key="site.id">
|
||||||
|
<div>{{ site.site_name }} · {{ site.site_code }}</div>
|
||||||
|
<ElText type="info" size="small">{{ [site.address, site.city, site.country].filter(Boolean).join(' · ') || '-' }}</ElText>
|
||||||
|
<div v-if="site.identity_evidences?.length">
|
||||||
|
<div>{{ t('admin.shippingCustomers.identifiers.siteEvidenceCount', { count: site.identity_evidences.length }) }}</div>
|
||||||
|
<div v-for="evidence in site.identity_evidences" :key="evidence.id" class="customers-id-row">
|
||||||
|
<span>{{ evidence.definition?.display_name || evidence.definition?.definition_code || evidence.definition_id }} · {{ evidence.raw_value }}</span>
|
||||||
|
<span>
|
||||||
|
<ElButton v-if="evidence.status !== 'approved'" link type="primary" @click="emit('updateEvidence', evidence.id, { status: 'approved' })">{{ t('admin.shippingCustomers.identifiers.approve') }}</ElButton>
|
||||||
|
<ElButton v-if="evidence.status === 'approved' && !evidence.auto_match_allowed && evidence.definition?.max_automation === 'conditional'" link type="primary" @click="emit('updateEvidence', evidence.id, { auto_match_allowed: true })">{{ t('admin.shippingCustomers.identifiers.enableAuto') }}</ElButton>
|
||||||
|
<ElButton v-if="evidence.status !== 'disabled'" link type="danger" @click="emit('updateEvidence', evidence.id, { status: 'disabled' })">{{ t('admin.shippingCustomers.identifiers.disable') }}</ElButton>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ElText v-else type="info">{{ t('admin.shippingCustomers.sites.empty') }}</ElText>
|
||||||
|
<ElForm label-position="top">
|
||||||
|
<div class="customers-id-grid">
|
||||||
|
<ElInput v-model="siteForm.site_name" :placeholder="t('admin.shippingCustomers.sites.siteName')" />
|
||||||
|
<ElInput v-model="siteForm.site_code" :placeholder="t('admin.shippingCustomers.sites.siteCode')" />
|
||||||
|
<ElInput v-model="siteForm.address" :placeholder="t('admin.shippingCustomers.sites.address')" />
|
||||||
|
<ElInput v-model="siteForm.city" :placeholder="t('admin.shippingCustomers.sites.city')" />
|
||||||
|
<ElInput v-model="siteForm.country" :placeholder="t('admin.shippingCustomers.sites.country')" />
|
||||||
|
</div>
|
||||||
|
<ElButton type="primary" :disabled="isSaving || !siteForm.site_name.trim() || !siteForm.site_code.trim()" @click="submitSite">{{ t('admin.add') }}</ElButton>
|
||||||
|
</ElForm>
|
||||||
|
</section>
|
||||||
|
|
||||||
</div>
|
<section>
|
||||||
</div>
|
<h4>{{ t('admin.shippingCustomers.identifiers.add') }}</h4>
|
||||||
</div>
|
<ElText type="info" size="small">{{ t('admin.shippingCustomers.identifiers.definitionHint') }}</ElText>
|
||||||
|
<ElText v-if="publishedDefinitions?.disabled_reason" type="warning">{{ t('admin.shippingCustomers.identifiers.publishedRuleRequired') }}</ElText>
|
||||||
|
<ElForm v-else label-position="top">
|
||||||
|
<ElFormItem>
|
||||||
|
<ElSelect v-model="form.target_type">
|
||||||
|
<ElOption value="customer" :label="t('admin.shippingCustomers.identifiers.targets.customer')" />
|
||||||
|
<ElOption value="site" :label="t('admin.shippingCustomers.identifiers.targets.site')" />
|
||||||
|
</ElSelect>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem v-if="form.target_type === 'site'">
|
||||||
|
<ElSelect
|
||||||
|
:model-value="form.target_id"
|
||||||
|
clearable
|
||||||
|
:placeholder="t('admin.shippingCustomers.identifiers.selectSite')"
|
||||||
|
@update:model-value="onSiteTargetChange"
|
||||||
|
>
|
||||||
|
<ElOption v-for="site in customer.sites || []" :key="site.id" :value="site.id" :label="`${site.site_name} · ${site.site_code}`" />
|
||||||
|
</ElSelect>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem v-else>
|
||||||
|
<ElInput :model-value="customer.standard_name" disabled />
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem>
|
||||||
|
<ElSelect
|
||||||
|
:model-value="form.definition_id || undefined"
|
||||||
|
clearable
|
||||||
|
:placeholder="t('admin.shippingCustomers.identifiers.selectDefinition')"
|
||||||
|
@update:model-value="onDefinitionChange"
|
||||||
|
>
|
||||||
|
<ElOption
|
||||||
|
v-for="definition in currentDefinitions"
|
||||||
|
:key="definition.id"
|
||||||
|
:value="definition.id"
|
||||||
|
:label="`${definition.display_name} · ${definition.context_field?.display_name || definition.context_field?.field_code || '-'}`"
|
||||||
|
/>
|
||||||
|
</ElSelect>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem>
|
||||||
|
<ElInput v-model="form.raw_value" :placeholder="t('admin.shippingCustomers.identifiers.valuePlaceholder')" />
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem>
|
||||||
|
<ElSelect v-model="form.status">
|
||||||
|
<ElOption value="pending" :label="t('admin.shippingCustomers.identifierStatus.pending')" />
|
||||||
|
<ElOption value="approved" :label="t('admin.shippingCustomers.identifierStatus.approved')" />
|
||||||
|
</ElSelect>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem>
|
||||||
|
<ElCheckbox v-model="form.auto_match_allowed" :disabled="form.status !== 'approved' || selectedDefinition?.max_automation !== 'conditional'">
|
||||||
|
{{ t('admin.shippingCustomers.identifiers.allowAuto') }}
|
||||||
|
</ElCheckbox>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem>
|
||||||
|
<ElInput v-model="form.remark" :placeholder="t('admin.shippingCustomers.fields.remark')" />
|
||||||
|
</ElFormItem>
|
||||||
|
</ElForm>
|
||||||
|
<ElText v-if="selectedDefinition && selectedDefinition.max_automation === 'none'" type="info" size="small">{{ t('admin.shippingCustomers.identifiers.manualOnly') }}</ElText>
|
||||||
|
<ElButton type="primary" :disabled="isSaving || Boolean(publishedDefinitions?.disabled_reason) || !targetReady || !form.definition_id || !form.raw_value.trim()" @click="submitEvidence">{{ t('admin.add') }}</ElButton>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<ElTable :data="customer.identity_evidences || []" row-key="id" :empty-text="t('admin.shippingCustomers.identifiers.empty')">
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.identifiers.definition')" min-width="160">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div>{{ (row as ShippingIdentityEvidence).definition?.display_name || (row as ShippingIdentityEvidence).definition?.definition_code || (row as ShippingIdentityEvidence).definition_id }}</div>
|
||||||
|
<ElText type="info" size="small">{{ (row as ShippingIdentityEvidence).definition?.evidence_label }}</ElText>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.identifiers.value')" min-width="140">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div>{{ (row as ShippingIdentityEvidence).raw_value }}</div>
|
||||||
|
<ElText type="info" size="small">{{ (row as ShippingIdentityEvidence).normalized_value }}</ElText>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.identifiers.status')" min-width="100">
|
||||||
|
<template #default="{ row }">{{ t(`admin.shippingCustomers.identifierStatus.${(row as ShippingIdentityEvidence).status}`) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.identifiers.autoMatch')" min-width="100">
|
||||||
|
<template #default="{ row }">{{ (row as ShippingIdentityEvidence).auto_match_allowed ? t('admin.shippingCustomers.yes') : t('admin.shippingCustomers.no') }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.headers.actions')" width="220" align="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<ElButton v-if="(row as ShippingIdentityEvidence).status !== 'approved'" link type="primary" @click="emit('updateEvidence', (row as ShippingIdentityEvidence).id, { status: 'approved' })">{{ t('admin.shippingCustomers.identifiers.approve') }}</ElButton>
|
||||||
|
<ElButton v-if="(row as ShippingIdentityEvidence).status === 'approved' && !(row as ShippingIdentityEvidence).auto_match_allowed && (row as ShippingIdentityEvidence).definition?.max_automation === 'conditional'" link type="primary" @click="emit('updateEvidence', (row as ShippingIdentityEvidence).id, { auto_match_allowed: true })">{{ t('admin.shippingCustomers.identifiers.enableAuto') }}</ElButton>
|
||||||
|
<ElButton v-if="(row as ShippingIdentityEvidence).status !== 'disabled'" link type="danger" @click="emit('updateEvidence', (row as ShippingIdentityEvidence).id, { status: 'disabled' })">{{ t('admin.shippingCustomers.identifiers.disable') }}</ElButton>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
</ElTable>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
|
||||||
|
</template>
|
||||||
|
</ElDialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.customers-id-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 12px;
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customers-id-row {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
section {
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
+190
-68
@@ -1,12 +1,26 @@
|
|||||||
<!--
|
<!--
|
||||||
features/shipping-notice/customers/components/CustomerImportDialog.vue
|
features/shipping-notice/customers/components/CustomerImportDialog.vue
|
||||||
用途:上传期初客户 Excel、查看预检结果、处理 warning、发布并下载对账。
|
用途:上传期初客户 Excel、查看预检结果、处理 warning、发布并下载对账。
|
||||||
依赖:customer-master.types、vue-i18n。
|
依赖:customer-master.types、element-plus、vue-i18n。
|
||||||
逻辑:组件只收集文件和行级决定;上传、发布与下载均委托父级 composable。
|
逻辑:组件只收集文件和行级决定;上传、发布与下载均委托父级 composable。样式由客户页引入。
|
||||||
|
隐藏文件选择保持原生 input。
|
||||||
-->
|
-->
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref } from 'vue';
|
import { computed, ref } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import {
|
||||||
|
ElButton,
|
||||||
|
ElDialog,
|
||||||
|
ElForm,
|
||||||
|
ElFormItem,
|
||||||
|
ElInput,
|
||||||
|
ElOption,
|
||||||
|
ElSelect,
|
||||||
|
ElTable,
|
||||||
|
ElTableColumn,
|
||||||
|
ElTag,
|
||||||
|
ElText,
|
||||||
|
} from 'element-plus';
|
||||||
import type { ShippingCustomerImportBatch, ShippingCustomerImportRow, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
|
import type { ShippingCustomerImportBatch, ShippingCustomerImportRow, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -48,74 +62,182 @@ const saveDecision = (row: ShippingCustomerImportRow): void => {
|
|||||||
if (!action) return;
|
if (!action) return;
|
||||||
emit('decide', row, action, rowTargets.value[row.id]);
|
emit('decide', row, action, rowTargets.value[row.id]);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 行级动作。清空写回空字符串,保存时仍视为未选择。
|
||||||
|
* @param rowId - 导入行 id
|
||||||
|
* @param value - create/update/merge/skip;清空为 undefined
|
||||||
|
*/
|
||||||
|
function onRowAction(rowId: number, value: string | undefined): void {
|
||||||
|
rowActions.value[rowId] = value ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归并或更新的目标客户。清空写回 undefined。
|
||||||
|
* @param rowId - 导入行 id
|
||||||
|
* @param value - 目标客户 id
|
||||||
|
*/
|
||||||
|
function onRowTarget(rowId: number, value: number | undefined): void {
|
||||||
|
rowTargets.value[rowId] = value ?? undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验状态标签色。
|
||||||
|
* @param status - valid / warning / error
|
||||||
|
*/
|
||||||
|
function validationTag(status: string): 'success' | 'warning' | 'danger' | 'info' {
|
||||||
|
if (status === 'error') return 'danger';
|
||||||
|
if (status === 'warning') return 'warning';
|
||||||
|
if (status === 'valid') return 'success';
|
||||||
|
return 'info';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预览列主文案。normalized 是开放对象。
|
||||||
|
* @param row - 导入行
|
||||||
|
*/
|
||||||
|
function previewMain(row: ShippingCustomerImportRow): string {
|
||||||
|
const normalized = row.normalized as { standard_name?: string; identifier_value?: string };
|
||||||
|
return normalized.standard_name || normalized.identifier_value || '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预览列次文案。
|
||||||
|
* @param row - 导入行
|
||||||
|
*/
|
||||||
|
function previewSub(row: ShippingCustomerImportRow): string {
|
||||||
|
const normalized = row.normalized as { short_code?: string; identifier_type?: string };
|
||||||
|
return normalized.short_code || normalized.identifier_type || '';
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
<ElDialog
|
||||||
<div class="admin-modal-panel max-w-6xl max-h-[94vh] scale-100">
|
:model-value="visible"
|
||||||
<div class="px-6 py-5 border-b border-subtle flex items-start justify-between gap-4">
|
:title="t('admin.shippingCustomers.import.title')"
|
||||||
<div><h3 class="section-title">{{ t('admin.shippingCustomers.import.title') }}</h3><p class="section-desc mt-1">{{ t('admin.shippingCustomers.import.subtitle') }}</p></div>
|
width="680px"
|
||||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.close') }}</button>
|
align-center
|
||||||
</div>
|
append-to-body
|
||||||
<div class="px-6 py-5 overflow-y-auto space-y-5">
|
:close-on-click-modal="false"
|
||||||
<div class="rounded-xl border border-default p-4 grid grid-cols-1 md:grid-cols-[1fr_220px_auto_auto] gap-3 items-end">
|
@update:model-value="(open) => { if (!open) emit('close'); }"
|
||||||
<label class="space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.import.file') }}</span><input type="file" accept=".xlsx" class="block w-full text-sm" @change="onFileChange" /></label>
|
>
|
||||||
<label class="space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.import.sourceSystem') }}</span><input v-model="sourceSystem" class="input-field text-sm uppercase" /></label>
|
<ElText type="info">{{ t('admin.shippingCustomers.import.subtitle') }}</ElText>
|
||||||
<button type="button" class="btn-ghost" @click="emit('template')">{{ t('admin.shippingCustomers.import.downloadTemplate') }}</button>
|
<ElForm label-position="top" @submit.prevent>
|
||||||
<button type="button" class="btn-primary" :disabled="!selectedFile || isImporting" @click="upload">{{ t('admin.shippingCustomers.import.upload') }}</button>
|
<ElFormItem :label="t('admin.shippingCustomers.import.file')">
|
||||||
</div>
|
<input type="file" accept=".xlsx" @change="onFileChange" />
|
||||||
|
</ElFormItem>
|
||||||
<template v-if="batch">
|
<ElFormItem :label="t('admin.shippingCustomers.import.sourceSystem')">
|
||||||
<div class="grid grid-cols-2 md:grid-cols-5 gap-3">
|
<ElInput v-model="sourceSystem" />
|
||||||
<div v-for="item in [
|
</ElFormItem>
|
||||||
['total', batch.total_rows], ['valid', batch.valid_rows], ['warning', batch.warning_rows], ['error', batch.error_rows], ['published', batch.published_rows]
|
</ElForm>
|
||||||
]" :key="String(item[0])" class="rounded-xl border border-default p-3">
|
<div class="customers-import-actions">
|
||||||
<div class="text-xs text-muted">{{ t(`admin.shippingCustomers.import.stats.${item[0]}`) }}</div><div class="text-xl font-semibold text-primary">{{ item[1] }}</div>
|
<ElButton @click="emit('template')">{{ t('admin.shippingCustomers.import.downloadTemplate') }}</ElButton>
|
||||||
</div>
|
<ElButton type="primary" :loading="isImporting" :disabled="!selectedFile" @click="upload">{{ t('admin.shippingCustomers.import.upload') }}</ElButton>
|
||||||
</div>
|
|
||||||
<div class="text-sm text-secondary">{{ batch.batch_no }} · {{ batch.source_system }} · {{ batch.file_name }}</div>
|
|
||||||
<div class="rounded-xl border border-default overflow-x-auto">
|
|
||||||
<table class="admin-table min-w-[1050px]">
|
|
||||||
<thead><tr>
|
|
||||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.row') }}</th>
|
|
||||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.type') }}</th>
|
|
||||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.key') }}</th>
|
|
||||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.preview') }}</th>
|
|
||||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.validation') }}</th>
|
|
||||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.import.decision') }}</th>
|
|
||||||
</tr></thead>
|
|
||||||
<tbody><tr v-for="row in batch.rows" :key="row.id">
|
|
||||||
<td class="px-3 py-3 text-sm">{{ row.sheet_name }}!{{ row.row_no }}</td>
|
|
||||||
<td class="px-3 py-3 text-sm">{{ t(`admin.shippingCustomers.import.rowTypes.${row.row_type}`) }}</td>
|
|
||||||
<td class="px-3 py-3 text-sm font-mono">{{ row.legacy_customer_key || '-' }}</td>
|
|
||||||
<td class="px-3 py-3 text-sm max-w-[320px]"><div class="truncate">{{ row.normalized.standard_name || row.normalized.identifier_value || '-' }}</div><div class="text-xs text-muted">{{ row.normalized.short_code || row.normalized.identifier_type || '' }}</div></td>
|
|
||||||
<td class="px-3 py-3 text-sm"><span :class="row.validation_status === 'error' ? 'text-red-600' : row.validation_status === 'warning' ? 'text-amber-600' : 'text-emerald-600'">{{ t(`admin.shippingCustomers.import.validationStatus.${row.validation_status}`) }}</span><div v-for="issue in [...row.errors, ...row.warnings]" :key="issue.code" class="text-xs text-muted">{{ t(`errors.codes.${issue.code.replace(/\./g, '_')}`) }}</div></td>
|
|
||||||
<td class="px-3 py-3 text-sm">
|
|
||||||
<div v-if="row.validation_status === 'warning' && batch.status !== 'published'" class="flex flex-wrap gap-2">
|
|
||||||
<select v-model="rowActions[row.id]" class="admin-table-filter-input text-xs">
|
|
||||||
<option value="">{{ t('admin.shippingCustomers.import.choose') }}</option>
|
|
||||||
<option value="create">{{ t('admin.shippingCustomers.import.actions.create') }}</option>
|
|
||||||
<option v-if="row.row_type === 'customer'" value="update">{{ t('admin.shippingCustomers.import.actions.update') }}</option>
|
|
||||||
<option v-if="row.row_type === 'customer'" value="merge">{{ t('admin.shippingCustomers.import.actions.merge') }}</option>
|
|
||||||
<option value="skip">{{ t('admin.shippingCustomers.import.actions.skip') }}</option>
|
|
||||||
</select>
|
|
||||||
<select v-if="row.row_type === 'customer' && ['update','merge'].includes(rowActions[row.id] || '')" v-model="rowTargets[row.id]" class="admin-table-filter-input text-xs">
|
|
||||||
<option :value="undefined">{{ t('admin.shippingCustomers.import.target') }}</option>
|
|
||||||
<option v-for="customer in customers" :key="customer.id" :value="customer.id">{{ customer.standard_name }} ({{ customer.short_code }})</option>
|
|
||||||
</select>
|
|
||||||
<button type="button" class="btn-ghost text-xs" @click="saveDecision(row)">{{ t('admin.save') }}</button>
|
|
||||||
</div>
|
|
||||||
<span v-else>{{ row.decision_action || row.result_message || row.suggested_action || '-' }}</span>
|
|
||||||
</td>
|
|
||||||
</tr></tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
<div class="flex flex-wrap justify-between gap-3">
|
|
||||||
<button type="button" class="btn-ghost" @click="emit('reconciliation')">{{ t('admin.shippingCustomers.import.downloadReconciliation') }}</button>
|
|
||||||
<button type="button" class="btn-primary" :disabled="!canPublish || isImporting" @click="emit('publish')">{{ batch.status === 'published' ? t('admin.shippingCustomers.import.alreadyPublished') : t('admin.shippingCustomers.import.publish') }}</button>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
<template v-if="batch">
|
||||||
|
<div class="customers-import-stats">
|
||||||
|
<div v-for="item in [
|
||||||
|
['total', batch.total_rows], ['valid', batch.valid_rows], ['warning', batch.warning_rows], ['error', batch.error_rows], ['published', batch.published_rows]
|
||||||
|
]" :key="String(item[0])">
|
||||||
|
<ElText type="info" size="small">{{ t(`admin.shippingCustomers.import.stats.${item[0]}`) }}</ElText>
|
||||||
|
<div>{{ item[1] }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ElText>{{ batch.batch_no }} · {{ batch.source_system }} · {{ batch.file_name }}</ElText>
|
||||||
|
<ElTable :data="batch.rows" row-key="id">
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.import.row')" min-width="120">
|
||||||
|
<template #default="{ row }">{{ (row as ShippingCustomerImportRow).sheet_name }}!{{ (row as ShippingCustomerImportRow).row_no }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.import.type')" min-width="100">
|
||||||
|
<template #default="{ row }">{{ t(`admin.shippingCustomers.import.rowTypes.${(row as ShippingCustomerImportRow).row_type}`) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.import.key')" min-width="120">
|
||||||
|
<template #default="{ row }">{{ (row as ShippingCustomerImportRow).legacy_customer_key || '-' }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.import.preview')" min-width="160">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div>{{ previewMain(row as ShippingCustomerImportRow) }}</div>
|
||||||
|
<ElText type="info" size="small">{{ previewSub(row as ShippingCustomerImportRow) }}</ElText>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.import.validation')" min-width="160">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<ElTag :type="validationTag((row as ShippingCustomerImportRow).validation_status)" effect="light">
|
||||||
|
{{ t(`admin.shippingCustomers.import.validationStatus.${(row as ShippingCustomerImportRow).validation_status}`) }}
|
||||||
|
</ElTag>
|
||||||
|
<div v-for="issue in [...(row as ShippingCustomerImportRow).errors, ...(row as ShippingCustomerImportRow).warnings]" :key="issue.code">
|
||||||
|
<ElText type="info" size="small">{{ t(`errors.codes.${issue.code.replace(/\./g, '_')}`) }}</ElText>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.import.decision')" min-width="280">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div v-if="(row as ShippingCustomerImportRow).validation_status === 'warning' && batch.status !== 'published'" class="customers-import-decision">
|
||||||
|
<ElSelect
|
||||||
|
class="customers-import-select"
|
||||||
|
:model-value="rowActions[(row as ShippingCustomerImportRow).id] || undefined"
|
||||||
|
clearable
|
||||||
|
:placeholder="t('admin.shippingCustomers.import.choose')"
|
||||||
|
@update:model-value="onRowAction((row as ShippingCustomerImportRow).id, $event)"
|
||||||
|
>
|
||||||
|
<ElOption value="create" :label="t('admin.shippingCustomers.import.actions.create')" />
|
||||||
|
<ElOption v-if="(row as ShippingCustomerImportRow).row_type === 'customer'" value="update" :label="t('admin.shippingCustomers.import.actions.update')" />
|
||||||
|
<ElOption v-if="(row as ShippingCustomerImportRow).row_type === 'customer'" value="merge" :label="t('admin.shippingCustomers.import.actions.merge')" />
|
||||||
|
<ElOption value="skip" :label="t('admin.shippingCustomers.import.actions.skip')" />
|
||||||
|
</ElSelect>
|
||||||
|
<ElSelect
|
||||||
|
v-if="(row as ShippingCustomerImportRow).row_type === 'customer' && ['update','merge'].includes(rowActions[(row as ShippingCustomerImportRow).id] || '')"
|
||||||
|
class="customers-import-select"
|
||||||
|
:model-value="rowTargets[(row as ShippingCustomerImportRow).id]"
|
||||||
|
clearable
|
||||||
|
:placeholder="t('admin.shippingCustomers.import.target')"
|
||||||
|
@update:model-value="onRowTarget((row as ShippingCustomerImportRow).id, $event)"
|
||||||
|
>
|
||||||
|
<ElOption
|
||||||
|
v-for="customer in customers"
|
||||||
|
:key="customer.id"
|
||||||
|
:value="customer.id"
|
||||||
|
:label="`${customer.standard_name} (${customer.short_code})`"
|
||||||
|
/>
|
||||||
|
</ElSelect>
|
||||||
|
<ElButton @click="saveDecision(row as ShippingCustomerImportRow)">{{ t('admin.save') }}</ElButton>
|
||||||
|
</div>
|
||||||
|
<span v-else>{{ (row as ShippingCustomerImportRow).decision_action || (row as ShippingCustomerImportRow).result_message || (row as ShippingCustomerImportRow).suggested_action || '-' }}</span>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
</ElTable>
|
||||||
|
<div class="customers-import-actions">
|
||||||
|
<ElButton @click="emit('reconciliation')">{{ t('admin.shippingCustomers.import.downloadReconciliation') }}</ElButton>
|
||||||
|
<ElButton type="primary" :loading="isImporting" :disabled="!canPublish" @click="emit('publish')">
|
||||||
|
{{ batch.status === 'published' ? t('admin.shippingCustomers.import.alreadyPublished') : t('admin.shippingCustomers.import.publish') }}
|
||||||
|
</ElButton>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template #footer>
|
||||||
|
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
|
||||||
|
</template>
|
||||||
|
</ElDialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.customers-import-actions,
|
||||||
|
.customers-import-decision {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
align-items: center;
|
||||||
|
margin-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customers-import-stats {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(6rem, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customers-import-select {
|
||||||
|
width: 11rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
+45
-36
@@ -1,12 +1,13 @@
|
|||||||
<!--
|
<!--
|
||||||
features/shipping-notice/customers/components/CustomerLifecyclePanel.vue
|
features/shipping-notice/customers/components/CustomerLifecyclePanel.vue
|
||||||
用途:展示单个货代客户不可变的生命周期治理审计。
|
用途:展示单个货代客户不可变的生命周期治理审计。
|
||||||
依赖:customer-master.types、vue-i18n。
|
依赖:customer-master.types、element-plus、vue-i18n。
|
||||||
逻辑:由客户主数据页拉取时间线后传入;仅渲染快照,不触发任何客户写操作。
|
逻辑:由客户主数据页拉取时间线后传入;仅渲染快照,不触发任何客户写操作。样式由客户页引入。
|
||||||
-->
|
-->
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import type { ShippingCustomerLifecycleTimeline, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
|
import { ElButton, ElDialog, ElTable, ElTableColumn } from 'element-plus';
|
||||||
|
import type { ShippingCustomerLifecycleEvent, ShippingCustomerLifecycleTimeline, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
|
||||||
|
|
||||||
defineProps<{ visible: boolean; customer: ShippingCustomerRow | null; timeline: ShippingCustomerLifecycleTimeline | null }>();
|
defineProps<{ visible: boolean; customer: ShippingCustomerRow | null; timeline: ShippingCustomerLifecycleTimeline | null }>();
|
||||||
const emit = defineEmits<{ close: [] }>();
|
const emit = defineEmits<{ close: [] }>();
|
||||||
@@ -20,40 +21,48 @@ const changeSummary = (detail: Record<string, unknown>): string => {
|
|||||||
.map(([key, value]) => `${key}: ${String(value.before ?? '-')} → ${String(value.after ?? '-')}`)
|
.map(([key, value]) => `${key}: ${String(value.before ?? '-')} → ${String(value.after ?? '-')}`)
|
||||||
.join(';');
|
.join(';');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 时间线行的变更摘要。表格插槽行收成审计事件。
|
||||||
|
* @param row - 当前事件
|
||||||
|
*/
|
||||||
|
function eventChange(row: ShippingCustomerLifecycleEvent): string {
|
||||||
|
return changeSummary(row.detail);
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="visible && customer" class="admin-modal-overlay animate-fade-in items-center">
|
<ElDialog
|
||||||
<div class="admin-modal-panel max-w-5xl max-h-[92vh] scale-100">
|
:model-value="visible && Boolean(customer)"
|
||||||
<div class="px-6 py-5 border-b border-subtle flex items-start justify-between gap-4">
|
:title="customer ? `${t('admin.shippingCustomers.lifecycle.title')} · ${customer.standard_name} · ${customer.short_code}` : t('admin.shippingCustomers.lifecycle.title')"
|
||||||
<div>
|
width="680px"
|
||||||
<h3 class="section-title">{{ t('admin.shippingCustomers.lifecycle.title') }}</h3>
|
align-center
|
||||||
<p class="section-desc mt-1">{{ customer.standard_name }} · {{ customer.short_code }}</p>
|
append-to-body
|
||||||
</div>
|
:close-on-click-modal="false"
|
||||||
<button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.close') }}</button>
|
@update:model-value="(open) => { if (!open) emit('close'); }"
|
||||||
</div>
|
>
|
||||||
<div class="px-6 py-5 overflow-y-auto">
|
<div v-if="!timeline">{{ t('admin.shippingCustomers.lifecycle.loading') }}</div>
|
||||||
<div v-if="!timeline" class="py-12 text-center text-sm text-muted">{{ t('admin.shippingCustomers.lifecycle.loading') }}</div>
|
<ElTable
|
||||||
<div v-else class="overflow-x-auto rounded-xl border border-default">
|
v-else
|
||||||
<table class="admin-table min-w-[760px]">
|
:data="timeline.items"
|
||||||
<thead><tr>
|
row-key="id"
|
||||||
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.time') }}</th>
|
:empty-text="t('admin.shippingCustomers.lifecycle.empty')"
|
||||||
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.event') }}</th>
|
>
|
||||||
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.reason') }}</th>
|
<ElTableColumn :label="t('admin.shippingCustomers.lifecycle.time')" min-width="160">
|
||||||
<th class="px-4 py-3 text-left">{{ t('admin.shippingCustomers.lifecycle.change') }}</th>
|
<template #default="{ row }">{{ (row as ShippingCustomerLifecycleEvent).created_at || '-' }}</template>
|
||||||
</tr></thead>
|
</ElTableColumn>
|
||||||
<tbody>
|
<ElTableColumn :label="t('admin.shippingCustomers.lifecycle.event')" min-width="140">
|
||||||
<tr v-if="!timeline.items.length"><td colspan="4" class="admin-table-empty px-4">{{ t('admin.shippingCustomers.lifecycle.empty') }}</td></tr>
|
<template #default="{ row }">{{ t(`admin.shippingCustomers.lifecycle.events.${(row as ShippingCustomerLifecycleEvent).event_type}`) }}</template>
|
||||||
<tr v-for="event in timeline.items" :key="event.id">
|
</ElTableColumn>
|
||||||
<td class="px-4 py-3 text-sm text-muted">{{ event.created_at || '-' }}</td>
|
<ElTableColumn :label="t('admin.shippingCustomers.lifecycle.reason')" min-width="140">
|
||||||
<td class="px-4 py-3 text-sm">{{ t(`admin.shippingCustomers.lifecycle.events.${event.event_type}`) }}</td>
|
<template #default="{ row }">{{ (row as ShippingCustomerLifecycleEvent).reason || '-' }}</template>
|
||||||
<td class="px-4 py-3 text-sm">{{ event.reason || '-' }}</td>
|
</ElTableColumn>
|
||||||
<td class="px-4 py-3 text-sm break-all">{{ changeSummary(event.detail) }}</td>
|
<ElTableColumn :label="t('admin.shippingCustomers.lifecycle.change')" min-width="220">
|
||||||
</tr>
|
<template #default="{ row }">{{ eventChange(row as ShippingCustomerLifecycleEvent) }}</template>
|
||||||
</tbody>
|
</ElTableColumn>
|
||||||
</table>
|
</ElTable>
|
||||||
</div>
|
<template #footer>
|
||||||
</div>
|
<ElButton @click="emit('close')">{{ t('admin.close') }}</ElButton>
|
||||||
</div>
|
</template>
|
||||||
</div>
|
</ElDialog>
|
||||||
</template>
|
</template>
|
||||||
+90
-21
@@ -1,12 +1,22 @@
|
|||||||
<!--
|
<!--
|
||||||
features/shipping-notice/customers/components/CustomerMergeDialog.vue
|
features/shipping-notice/customers/components/CustomerMergeDialog.vue
|
||||||
用途:预览并确认将重复客户归并到启用目标客户。
|
用途:预览并确认将重复客户归并到启用目标客户。
|
||||||
依赖:customer-master.types、vue-i18n。
|
依赖:customer-master.types、element-plus、vue-i18n。
|
||||||
逻辑:展示历史保留与未来配置迁移边界;提交必须输入源客户简码和合并原因。
|
逻辑:展示历史保留与未来配置迁移边界;提交必须输入源客户简码和合并原因。样式由客户页引入。
|
||||||
-->
|
-->
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { computed, ref, watch } from 'vue';
|
import { computed, ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import {
|
||||||
|
ElButton,
|
||||||
|
ElDialog,
|
||||||
|
ElForm,
|
||||||
|
ElFormItem,
|
||||||
|
ElInput,
|
||||||
|
ElOption,
|
||||||
|
ElSelect,
|
||||||
|
ElText,
|
||||||
|
} from 'element-plus';
|
||||||
import type { ShippingCustomerMergeImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
|
import type { ShippingCustomerMergeImpact, ShippingCustomerRow } from '@/features/shipping-notice/types/customer-master.types';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -35,32 +45,91 @@ watch(() => props.visible, (visible) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/** 选择目标后再调用服务端预检,阻止在未确认归并边界时提交。 */
|
/**
|
||||||
const preview = (): void => {
|
* 选择目标后再调用服务端预检。清空写回 null,与原下拉空值一致。
|
||||||
|
* @param value - 目标客户 id;清空为 undefined
|
||||||
|
*/
|
||||||
|
function onTargetChange(value: number | undefined): void {
|
||||||
|
targetCustomerId.value = value ?? null;
|
||||||
if (targetCustomerId.value) emit('preview', targetCustomerId.value);
|
if (targetCustomerId.value) emit('preview', targetCustomerId.value);
|
||||||
};
|
}
|
||||||
|
|
||||||
|
/** 目标、简码和原因都齐了才允许提交。 */
|
||||||
const canSubmit = computed(() => Boolean(
|
const canSubmit = computed(() => Boolean(
|
||||||
targetCustomerId.value && props.impact && confirmationShortCode.value.trim() && reason.value.trim() && !props.isSaving,
|
targetCustomerId.value && props.impact && confirmationShortCode.value.trim() && reason.value.trim() && !props.isSaving,
|
||||||
));
|
));
|
||||||
|
|
||||||
|
/** 提交归并。目标在 canSubmit 为真时必有值。 */
|
||||||
|
function submitMerge(): void {
|
||||||
|
if (!targetCustomerId.value || !canSubmit.value) return;
|
||||||
|
emit('confirm', targetCustomerId.value, confirmationShortCode.value, reason.value);
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="visible" class="admin-modal-overlay animate-fade-in items-center">
|
<ElDialog
|
||||||
<div class="admin-modal-panel max-w-xl max-h-[92vh] scale-100">
|
:model-value="visible"
|
||||||
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('admin.shippingCustomers.mergeDialog.title') }}</h3><p class="section-desc mt-1">{{ t('admin.shippingCustomers.mergeDialog.subtitle') }}</p></div>
|
:title="t('admin.shippingCustomers.mergeDialog.title')"
|
||||||
<div class="px-6 py-5 space-y-4 overflow-y-auto">
|
width="680px"
|
||||||
<div v-if="source" class="rounded-lg border border-default bg-surface-secondary p-4 text-sm"><span class="text-muted">{{ t('admin.shippingCustomers.mergeDialog.source') }}</span><div class="font-medium text-primary mt-1">{{ source.standard_name }} <span class="font-mono">({{ source.short_code }})</span></div></div>
|
align-center
|
||||||
<label class="block space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.mergeDialog.target') }}</span><select v-model="targetCustomerId" class="input-field text-sm" @change="preview"><option :value="null">{{ t('admin.shippingCustomers.mergeDialog.chooseTarget') }}</option><option v-for="customer in targetOptions" :key="customer.id" :value="customer.id">{{ customer.standard_name }} ({{ customer.short_code }})</option></select></label>
|
append-to-body
|
||||||
<template v-if="impact">
|
:close-on-click-modal="false"
|
||||||
<div class="rounded-lg border border-default p-4 text-sm"><div class="font-medium text-primary">{{ t('admin.shippingCustomers.mergeDialog.historyTitle') }}</div><p class="mt-1 text-muted">{{ t('admin.shippingCustomers.mergeDialog.historyHint') }}</p><div class="mt-2 text-muted">{{ t('admin.shippingCustomers.mergeDialog.historyCount', { count: Object.values(impact.historical_references).reduce((sum, value) => sum + value, 0) }) }}</div></div>
|
@update:model-value="(open) => { if (!open) emit('close'); }"
|
||||||
<div class="rounded-lg border border-default p-4 text-sm"><div class="font-medium text-primary">{{ t('admin.shippingCustomers.mergeDialog.migrateTitle') }}</div><div class="mt-2 grid grid-cols-3 gap-2 text-center"><div><div class="text-lg font-semibold">{{ impact.migrate.identifiers }}</div><div class="text-xs text-muted">{{ t('admin.shippingCustomers.mergeDialog.identifiers') }}</div></div><div><div class="text-lg font-semibold">{{ impact.migrate.duplicate_identifiers }}</div><div class="text-xs text-muted">{{ t('admin.shippingCustomers.mergeDialog.duplicates') }}</div></div><div><div class="text-lg font-semibold">{{ impact.migrate.external_references }}</div><div class="text-xs text-muted">{{ t('admin.shippingCustomers.mergeDialog.references') }}</div></div></div></div>
|
>
|
||||||
<p class="text-sm text-amber-700">{{ t('admin.shippingCustomers.mergeDialog.warning') }}</p>
|
<ElText type="info">{{ t('admin.shippingCustomers.mergeDialog.subtitle') }}</ElText>
|
||||||
<label class="block space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.mergeDialog.confirmationShortCode', { shortCode: impact.source.short_code }) }}</span><input v-model="confirmationShortCode" class="input-field text-sm uppercase" maxlength="6" /></label>
|
<div v-if="source" class="customers-merge-block">
|
||||||
<label class="block space-y-1.5"><span class="label-field">{{ t('admin.shippingCustomers.mergeDialog.reason') }}</span><textarea v-model="reason" rows="3" class="input-field text-sm resize-y" /></label>
|
<ElText type="info" size="small">{{ t('admin.shippingCustomers.mergeDialog.source') }}</ElText>
|
||||||
</template>
|
<div>{{ source.standard_name }} ({{ source.short_code }})</div>
|
||||||
</div>
|
|
||||||
<div class="admin-modal-footer"><button type="button" class="btn-ghost" @click="emit('close')">{{ t('admin.cancel') }}</button><button type="button" class="btn-primary" :disabled="!canSubmit" @click="targetCustomerId && emit('confirm', targetCustomerId, confirmationShortCode, reason)">{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.mergeDialog.confirm') }}</button></div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<ElForm label-position="top" @submit.prevent>
|
||||||
|
<ElFormItem :label="t('admin.shippingCustomers.mergeDialog.target')">
|
||||||
|
<ElSelect
|
||||||
|
:model-value="targetCustomerId ?? undefined"
|
||||||
|
clearable
|
||||||
|
:placeholder="t('admin.shippingCustomers.mergeDialog.chooseTarget')"
|
||||||
|
@update:model-value="onTargetChange"
|
||||||
|
>
|
||||||
|
<ElOption
|
||||||
|
v-for="customer in targetOptions"
|
||||||
|
:key="customer.id"
|
||||||
|
:value="customer.id"
|
||||||
|
:label="`${customer.standard_name} (${customer.short_code})`"
|
||||||
|
/>
|
||||||
|
</ElSelect>
|
||||||
|
</ElFormItem>
|
||||||
|
<template v-if="impact">
|
||||||
|
<div class="customers-merge-block">
|
||||||
|
<div>{{ t('admin.shippingCustomers.mergeDialog.historyTitle') }}</div>
|
||||||
|
<ElText type="info" size="small">{{ t('admin.shippingCustomers.mergeDialog.historyHint') }}</ElText>
|
||||||
|
<div>{{ t('admin.shippingCustomers.mergeDialog.historyCount', { count: Object.values(impact.historical_references).reduce((sum, value) => sum + value, 0) }) }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="customers-merge-stats">
|
||||||
|
<div>{{ t('admin.shippingCustomers.mergeDialog.migrateTitle') }}</div>
|
||||||
|
<div>{{ impact.migrate.identifiers }} {{ t('admin.shippingCustomers.mergeDialog.identifiers') }}</div>
|
||||||
|
<div>{{ impact.migrate.duplicate_identifiers }} {{ t('admin.shippingCustomers.mergeDialog.duplicates') }}</div>
|
||||||
|
<div>{{ impact.migrate.external_references }} {{ t('admin.shippingCustomers.mergeDialog.references') }}</div>
|
||||||
|
</div>
|
||||||
|
<ElText type="warning">{{ t('admin.shippingCustomers.mergeDialog.warning') }}</ElText>
|
||||||
|
<ElFormItem :label="t('admin.shippingCustomers.mergeDialog.confirmationShortCode', { shortCode: impact.source.short_code })">
|
||||||
|
<ElInput v-model="confirmationShortCode" maxlength="6" />
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem :label="t('admin.shippingCustomers.mergeDialog.reason')">
|
||||||
|
<ElInput v-model="reason" type="textarea" :rows="3" />
|
||||||
|
</ElFormItem>
|
||||||
|
</template>
|
||||||
|
</ElForm>
|
||||||
|
<template #footer>
|
||||||
|
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
|
||||||
|
<ElButton type="primary" :loading="isSaving" :disabled="!canSubmit" @click="submitMerge">
|
||||||
|
{{ isSaving ? t('admin.shippingCustomers.saving') : t('admin.shippingCustomers.mergeDialog.confirm') }}
|
||||||
|
</ElButton>
|
||||||
|
</template>
|
||||||
|
</ElDialog>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.customers-merge-block,
|
||||||
|
.customers-merge-stats {
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
+151
-41
@@ -1,13 +1,23 @@
|
|||||||
<!--
|
<!--
|
||||||
features/shipping-notice/customers/components/CustomerShadowQualityPanel.vue
|
features/shipping-notice/customers/components/CustomerShadowQualityPanel.vue
|
||||||
用途:展示客户影子识别分布、自动确认指标、人工标注准确率和最近样本。
|
用途:展示客户影子识别分布、自动确认指标、人工标注准确率和最近样本。
|
||||||
依赖:customer-master.types、vue-i18n。
|
依赖:customer-master.types、element-plus、vue-i18n。
|
||||||
逻辑:展示质量卡片、客户事件审计与真值标签;不调用客户绑定、编号或任务接口。
|
逻辑:展示质量卡片、客户事件审计与真值标签;不调用客户绑定、编号或任务接口。样式由客户页引入。
|
||||||
-->
|
-->
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, watch } from 'vue';
|
import { ref, watch } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import type { ShippingCustomerRow, ShippingCustomerShadowReport } from '@/features/shipping-notice/types/customer-master.types';
|
import {
|
||||||
|
ElButton,
|
||||||
|
ElOption,
|
||||||
|
ElSelect,
|
||||||
|
ElTable,
|
||||||
|
ElTableColumn,
|
||||||
|
ElText,
|
||||||
|
} from 'element-plus';
|
||||||
|
import type { ShippingCustomerRow, ShippingCustomerShadowItem, ShippingCustomerShadowReport } from '@/features/shipping-notice/types/customer-master.types';
|
||||||
|
|
||||||
|
type ShadowEvent = NonNullable<ShippingCustomerShadowReport['auto_resolution']>['recent_events'][number];
|
||||||
|
|
||||||
const props = defineProps<{ report: ShippingCustomerShadowReport | null; customers: ShippingCustomerRow[]; loading: boolean }>();
|
const props = defineProps<{ report: ShippingCustomerShadowReport | null; customers: ShippingCustomerRow[]; loading: boolean }>();
|
||||||
const emit = defineEmits<{ refresh: []; label: [resolutionId: number, customerId: number] }>();
|
const emit = defineEmits<{ refresh: []; label: [resolutionId: number, customerId: number] }>();
|
||||||
@@ -31,6 +41,15 @@ const submitLabel = (resolutionId: number): void => {
|
|||||||
if (customerId) emit('label', resolutionId, customerId);
|
if (customerId) emit('label', resolutionId, customerId);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写入样本真值客户。清空写回 undefined,与原下拉空值一致。
|
||||||
|
* @param resolutionId - 影子样本 id
|
||||||
|
* @param value - 客户 id;清空为 undefined
|
||||||
|
*/
|
||||||
|
function onLabelChange(resolutionId: number, value: number | undefined): void {
|
||||||
|
labels.value[resolutionId] = value ?? undefined;
|
||||||
|
}
|
||||||
|
|
||||||
/** 从客户事件详情中提取新旧业务号,保持表格简洁且兼容不同事件类型。 */
|
/** 从客户事件详情中提取新旧业务号,保持表格简洁且兼容不同事件类型。 */
|
||||||
const eventBusinessChange = (detail: Record<string, unknown>): string => {
|
const eventBusinessChange = (detail: Record<string, unknown>): string => {
|
||||||
const oldNo = String(detail.old_business_no || '').trim();
|
const oldNo = String(detail.old_business_no || '').trim();
|
||||||
@@ -38,59 +57,150 @@ const eventBusinessChange = (detail: Record<string, unknown>): string => {
|
|||||||
if (oldNo && newNo) return `${oldNo} → ${newNo}`;
|
if (oldNo && newNo) return `${oldNo} → ${newNo}`;
|
||||||
return newNo || oldNo || '-';
|
return newNo || oldNo || '-';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 审计行的业务号变化。表格插槽行收成影子事件。
|
||||||
|
* @param row - 最近审计事件
|
||||||
|
*/
|
||||||
|
function eventBusinessText(row: ShadowEvent): string {
|
||||||
|
return eventBusinessChange(row.detail);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 样本最高候选的展示文案。没有候选时返回短横线。
|
||||||
|
* @param row - 影子识别样本
|
||||||
|
* @returns 客户名、短码和分数
|
||||||
|
*/
|
||||||
|
function topCandidateText(row: ShippingCustomerShadowItem): string {
|
||||||
|
const match = row.matches[0];
|
||||||
|
if (!match) return '-';
|
||||||
|
return `${match.standard_name} (${match.short_code}) · ${match.score}`;
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="rounded-2xl border border-default bg-surface p-5 space-y-4">
|
<div class="customers-shadow">
|
||||||
<div class="flex items-start justify-between gap-3">
|
<div class="customers-shadow-head">
|
||||||
<div><h3 class="font-semibold text-primary">{{ t('admin.shippingCustomers.shadow.title') }}</h3><p class="text-sm text-muted mt-1">{{ t('admin.shippingCustomers.shadow.subtitle') }}</p></div>
|
<div>
|
||||||
<button type="button" class="btn-ghost" :disabled="loading" @click="emit('refresh')">{{ t('admin.shippingCustomers.shadow.refresh') }}</button>
|
<h3>{{ t('admin.shippingCustomers.shadow.title') }}</h3>
|
||||||
|
<ElText type="info">{{ t('admin.shippingCustomers.shadow.subtitle') }}</ElText>
|
||||||
|
</div>
|
||||||
|
<ElButton :loading="loading" @click="emit('refresh')">{{ t('admin.shippingCustomers.shadow.refresh') }}</ElButton>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="report" class="grid grid-cols-2 md:grid-cols-4 xl:grid-cols-8 gap-3">
|
<div v-if="report" class="customers-shadow-cards">
|
||||||
<div v-for="card in [
|
<div v-for="card in [
|
||||||
['total', report.total], ['unique', report.status_counts.unique_candidate || 0], ['ambiguous', report.status_counts.ambiguous || 0],
|
['total', report.total], ['unique', report.status_counts.unique_candidate || 0], ['ambiguous', report.status_counts.ambiguous || 0],
|
||||||
['unmatched', report.status_counts.unmatched || 0], ['accuracy', report.accuracy == null ? '-' : `${(report.accuracy * 100).toFixed(1)}%`],
|
['unmatched', report.status_counts.unmatched || 0], ['accuracy', report.accuracy == null ? '-' : `${(report.accuracy * 100).toFixed(1)}%`],
|
||||||
['autoBound', report.auto_bound_count], ['autoRate', report.auto_resolution?.auto_confirmation_rate == null ? '-' : `${(report.auto_resolution.auto_confirmation_rate * 100).toFixed(1)}%`]
|
['autoBound', report.auto_bound_count], ['autoRate', report.auto_resolution?.auto_confirmation_rate == null ? '-' : `${(report.auto_resolution.auto_confirmation_rate * 100).toFixed(1)}%`]
|
||||||
]" :key="String(card[0])" class="rounded-xl border border-default p-3"><div class="text-xs text-muted">{{ t(`admin.shippingCustomers.shadow.cards.${card[0]}`) }}</div><div class="text-xl font-semibold">{{ card[1] }}</div></div>
|
]" :key="String(card[0])">
|
||||||
|
<ElText type="info" size="small">{{ t(`admin.shippingCustomers.shadow.cards.${card[0]}`) }}</ElText>
|
||||||
|
<div>{{ card[1] }}</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="report?.auto_resolution?.quality_gate" class="rounded-xl border p-4" :class="report.auto_resolution.quality_gate.is_eligible ? 'border-emerald-300 bg-emerald-50/50' : 'border-amber-300 bg-amber-50/50'">
|
<div v-if="report?.auto_resolution?.quality_gate">
|
||||||
<div class="font-semibold text-primary">{{ t('admin.shippingCustomers.shadow.gate.title') }}</div>
|
<div>{{ t('admin.shippingCustomers.shadow.gate.title') }}</div>
|
||||||
<div class="mt-1 text-sm text-secondary">{{ t(`admin.shippingCustomers.shadow.gate.statuses.${report.auto_resolution.quality_gate.status}`) }}</div>
|
<div>{{ t(`admin.shippingCustomers.shadow.gate.statuses.${report.auto_resolution.quality_gate.status}`) }}</div>
|
||||||
<div class="mt-2 text-xs text-muted">
|
<ElText type="info" size="small">
|
||||||
{{ t('admin.shippingCustomers.shadow.gate.metrics', {
|
{{ t('admin.shippingCustomers.shadow.gate.metrics', {
|
||||||
samples: report.auto_resolution.quality_gate.labeled_sample_count,
|
samples: report.auto_resolution.quality_gate.labeled_sample_count,
|
||||||
minSamples: report.auto_resolution.quality_gate.min_labeled_samples,
|
minSamples: report.auto_resolution.quality_gate.min_labeled_samples,
|
||||||
accuracy: report.auto_resolution.quality_gate.accuracy == null ? '-' : `${(report.auto_resolution.quality_gate.accuracy * 100).toFixed(1)}%`,
|
accuracy: report.auto_resolution.quality_gate.accuracy == null ? '-' : `${(report.auto_resolution.quality_gate.accuracy * 100).toFixed(1)}%`,
|
||||||
minAccuracy: `${(report.auto_resolution.quality_gate.min_accuracy * 100).toFixed(1)}%`,
|
minAccuracy: `${(report.auto_resolution.quality_gate.min_accuracy * 100).toFixed(1)}%`,
|
||||||
}) }}
|
}) }}
|
||||||
</div>
|
</ElText>
|
||||||
</div>
|
|
||||||
<div v-if="report" class="overflow-x-auto rounded-xl border border-default">
|
|
||||||
<table class="admin-table min-w-[900px]"><thead><tr>
|
|
||||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.sample') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.status') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.topCandidate') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.manualLabel') }}</th>
|
|
||||||
</tr></thead><tbody>
|
|
||||||
<tr v-if="!report.items.length"><td colspan="4" class="admin-table-empty px-3">{{ t('admin.shippingCustomers.shadow.empty') }}</td></tr>
|
|
||||||
<tr v-for="item in report.items" :key="item.id">
|
|
||||||
<td class="px-3 py-3 text-sm"><div>{{ item.candidate_no || item.candidate_id }}</div><div class="text-xs text-muted">{{ item.intake_no }}</div></td>
|
|
||||||
<td class="px-3 py-3 text-sm">{{ t(`admin.shippingCustomers.shadow.statuses.${item.status}`) }}</td>
|
|
||||||
<td class="px-3 py-3 text-sm"><span v-if="item.matches[0]">{{ item.matches[0].standard_name }} ({{ item.matches[0].short_code }}) · {{ item.matches[0].score }}</span><span v-else>-</span></td>
|
|
||||||
<td class="px-3 py-3"><div class="flex gap-2"><select v-model="labels[item.id]" class="admin-table-filter-input text-xs"><option :value="undefined">{{ t('admin.shippingCustomers.shadow.chooseCustomer') }}</option><option v-for="customer in customers" :key="customer.id" :value="customer.id">{{ customer.standard_name }} ({{ customer.short_code }})</option></select><button type="button" class="btn-ghost text-xs" @click="submitLabel(item.id)">{{ item.manual_customer_id ? t('admin.update') : t('admin.save') }}</button></div></td>
|
|
||||||
</tr>
|
|
||||||
</tbody></table>
|
|
||||||
</div>
|
|
||||||
<div v-if="report?.auto_resolution" class="overflow-x-auto rounded-xl border border-default">
|
|
||||||
<div class="border-b border-default px-3 py-3 text-sm font-semibold text-primary">{{ t('admin.shippingCustomers.shadow.auditTitle') }}</div>
|
|
||||||
<table class="admin-table min-w-[760px]"><thead><tr>
|
|
||||||
<th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditTask') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditEvent') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditBusinessNo') }}</th><th class="px-3 py-3 text-left">{{ t('admin.shippingCustomers.shadow.auditTime') }}</th>
|
|
||||||
</tr></thead><tbody>
|
|
||||||
<tr v-if="!report.auto_resolution.recent_events.length"><td colspan="4" class="admin-table-empty px-3">{{ t('admin.shippingCustomers.shadow.auditEmpty') }}</td></tr>
|
|
||||||
<tr v-for="event in report.auto_resolution.recent_events" :key="event.id">
|
|
||||||
<td class="px-3 py-3 text-sm">{{ event.task_no }}</td>
|
|
||||||
<td class="px-3 py-3 text-sm">{{ t(`admin.shippingCustomers.shadow.events.${event.event_type}`) }}</td>
|
|
||||||
<td class="px-3 py-3 text-sm">{{ eventBusinessChange(event.detail) }}</td>
|
|
||||||
<td class="px-3 py-3 text-sm text-muted">{{ event.created_at || '-' }}</td>
|
|
||||||
</tr>
|
|
||||||
</tbody></table>
|
|
||||||
</div>
|
</div>
|
||||||
|
<ElTable
|
||||||
|
v-if="report"
|
||||||
|
:data="report.items"
|
||||||
|
row-key="id"
|
||||||
|
:empty-text="t('admin.shippingCustomers.shadow.empty')"
|
||||||
|
>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.shadow.sample')" min-width="160">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div>{{ (row as ShippingCustomerShadowItem).candidate_no || (row as ShippingCustomerShadowItem).candidate_id }}</div>
|
||||||
|
<ElText type="info" size="small">{{ (row as ShippingCustomerShadowItem).intake_no }}</ElText>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.shadow.status')" min-width="120">
|
||||||
|
<template #default="{ row }">{{ t(`admin.shippingCustomers.shadow.statuses.${(row as ShippingCustomerShadowItem).status}`) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.shadow.topCandidate')" min-width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ topCandidateText(row as ShippingCustomerShadowItem) }}
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.shadow.manualLabel')" min-width="280">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div class="customers-shadow-label">
|
||||||
|
<ElSelect
|
||||||
|
class="customers-shadow-select"
|
||||||
|
:model-value="labels[(row as ShippingCustomerShadowItem).id]"
|
||||||
|
clearable
|
||||||
|
:placeholder="t('admin.shippingCustomers.shadow.chooseCustomer')"
|
||||||
|
@update:model-value="onLabelChange((row as ShippingCustomerShadowItem).id, $event)"
|
||||||
|
>
|
||||||
|
<ElOption
|
||||||
|
v-for="customer in customers"
|
||||||
|
:key="customer.id"
|
||||||
|
:value="customer.id"
|
||||||
|
:label="`${customer.standard_name} (${customer.short_code})`"
|
||||||
|
/>
|
||||||
|
</ElSelect>
|
||||||
|
<ElButton @click="submitLabel((row as ShippingCustomerShadowItem).id)">
|
||||||
|
{{ (row as ShippingCustomerShadowItem).manual_customer_id ? t('admin.update') : t('admin.save') }}
|
||||||
|
</ElButton>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
</ElTable>
|
||||||
|
<template v-if="report?.auto_resolution">
|
||||||
|
<div>{{ t('admin.shippingCustomers.shadow.auditTitle') }}</div>
|
||||||
|
<ElTable
|
||||||
|
:data="report.auto_resolution.recent_events"
|
||||||
|
row-key="id"
|
||||||
|
:empty-text="t('admin.shippingCustomers.shadow.auditEmpty')"
|
||||||
|
>
|
||||||
|
<ElTableColumn prop="task_no" :label="t('admin.shippingCustomers.shadow.auditTask')" min-width="140" />
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.shadow.auditEvent')" min-width="140">
|
||||||
|
<template #default="{ row }">{{ t(`admin.shippingCustomers.shadow.events.${(row as ShadowEvent).event_type}`) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.shadow.auditBusinessNo')" min-width="180">
|
||||||
|
<template #default="{ row }">{{ eventBusinessText(row as ShadowEvent) }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
<ElTableColumn :label="t('admin.shippingCustomers.shadow.auditTime')" min-width="160">
|
||||||
|
<template #default="{ row }">{{ (row as ShadowEvent).created_at || '-' }}</template>
|
||||||
|
</ElTableColumn>
|
||||||
|
</ElTable>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.customers-shadow {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
margin: 16px 32px 24px;
|
||||||
|
padding: 16px;
|
||||||
|
border: 1px solid var(--el-border-color-lighter);
|
||||||
|
border-radius: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customers-shadow-head,
|
||||||
|
.customers-shadow-label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customers-shadow-cards {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(8rem, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.customers-shadow-select {
|
||||||
|
width: 16rem;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
+66
-24
@@ -1,12 +1,14 @@
|
|||||||
/**
|
/**
|
||||||
* features/shipping-notice/customers/composables/useShippingCustomersAdmin.ts
|
* features/shipping-notice/customers/composables/useShippingCustomersAdmin.ts
|
||||||
* 用途:编排货代客户列表、详情、识别证据、期初导入与发布状态。
|
* 用途:编排货代客户列表、详情、识别证据、期初导入与发布状态。
|
||||||
* 依赖:customer-master.api、customer-master.types、BusinessError、useMessage。
|
* 依赖:customer-master.api、customer-master.types、element-plus(ElMessageBox)、BusinessError、useMessage。
|
||||||
* 逻辑:ShippingCustomersPage 与子组件共享本 composable 暴露的状态和动作。
|
* 逻辑:ShippingCustomersPage 与子组件共享本 composable 暴露的状态和动作。
|
||||||
|
* 停用与证据变更的审计原因经 ElMessageBox.prompt 收集,取消不提交。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { ref } from 'vue';
|
import { ref } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { ElMessageBox } from 'element-plus';
|
||||||
import {
|
import {
|
||||||
createShippingCustomer,
|
createShippingCustomer,
|
||||||
createShippingCustomerExternalRef,
|
createShippingCustomerExternalRef,
|
||||||
@@ -82,7 +84,6 @@ export function useShippingCustomersAdmin() {
|
|||||||
const showDeleteDialog = ref(false);
|
const showDeleteDialog = ref(false);
|
||||||
const showLifecyclePanel = ref(false);
|
const showLifecyclePanel = ref(false);
|
||||||
const showMergeDialog = ref(false);
|
const showMergeDialog = ref(false);
|
||||||
const pendingReasonAction = ref<{ kind: 'deactivate'; customer: ShippingCustomerRow } | { kind: 'update_evidence'; evidenceId: number; payload: Record<string, unknown> } | null>(null);
|
|
||||||
|
|
||||||
/** 分页加载全部客户选项,供导入冲突和影子真值标签共用。 */
|
/** 分页加载全部客户选项,供导入冲突和影子真值标签共用。 */
|
||||||
const loadAllCustomerOptions = async (): Promise<void> => {
|
const loadAllCustomerOptions = async (): Promise<void> => {
|
||||||
@@ -187,9 +188,52 @@ export function useShippingCustomersAdmin() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 打开停用确认;审计原因由平台公共确认组件收集。 */
|
/**
|
||||||
const deactivateCustomer = (customer: ShippingCustomerRow): void => {
|
* 收集治理动作的审计原因。
|
||||||
pendingReasonAction.value = { kind: 'deactivate', customer };
|
* 核心逻辑:原确认框必填原因,ElMessageBox.confirm 无法输入,故用 prompt;取消或关闭返回 null。
|
||||||
|
* @param title - 确认框标题,沿用现有 i18n
|
||||||
|
* @param message - 确认说明
|
||||||
|
* @param placeholder - 原因输入占位,同时作为未填写时的校验文案
|
||||||
|
* @returns 去空白后的原因;用户取消时为 null
|
||||||
|
*/
|
||||||
|
const askAuditReason = async (title: string, message: string, placeholder: string): Promise<string | null> => {
|
||||||
|
try {
|
||||||
|
const result = await ElMessageBox.prompt(message, title, {
|
||||||
|
confirmButtonText: t('common.deleteDialog.confirm'),
|
||||||
|
cancelButtonText: t('common.deleteDialog.cancel'),
|
||||||
|
inputPlaceholder: placeholder,
|
||||||
|
inputType: 'textarea',
|
||||||
|
inputValidator: (value) => Boolean(String(value || '').trim()) || placeholder,
|
||||||
|
closeOnClickModal: false,
|
||||||
|
});
|
||||||
|
const reason = String(result.value || '').trim();
|
||||||
|
return reason || null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 停用启用中的客户。
|
||||||
|
* 核心逻辑:先收集审计原因,取消则不调用停用接口。
|
||||||
|
* @param customer - 当前行客户
|
||||||
|
*/
|
||||||
|
const deactivateCustomer = async (customer: ShippingCustomerRow): Promise<void> => {
|
||||||
|
const reason = await askAuditReason(
|
||||||
|
t('admin.shippingCustomers.deactivate'),
|
||||||
|
t('admin.shippingCustomers.confirmDeactivate', { name: customer.standard_name }),
|
||||||
|
t('admin.shippingCustomers.prompts.deactivateReason'),
|
||||||
|
);
|
||||||
|
if (!reason) return;
|
||||||
|
isSaving.value = true;
|
||||||
|
try {
|
||||||
|
await deactivateShippingCustomer(customer.id, reason);
|
||||||
|
await loadCustomers();
|
||||||
|
} catch (error) {
|
||||||
|
showError(error, 'admin.shippingCustomers.msg.saveFailed');
|
||||||
|
} finally {
|
||||||
|
isSaving.value = false;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 打开客户治理时间线;读取失败时不显示过期的其他客户审计。 */
|
/** 打开客户治理时间线;读取失败时不显示过期的其他客户审计。 */
|
||||||
@@ -352,32 +396,30 @@ export function useShippingCustomersAdmin() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 打开证据变更确认;审计原因由平台公共确认组件收集。 */
|
/**
|
||||||
const updateIdentityEvidence = (evidenceId: number, payload: Record<string, unknown>): void => {
|
* 变更识别证据状态或自动匹配开关。
|
||||||
|
* 核心逻辑:先收集审计原因,取消则不提交;原因并入原 payload。
|
||||||
|
* @param evidenceId - 证据主键
|
||||||
|
* @param payload - 状态或自动匹配字段,不含 reason
|
||||||
|
*/
|
||||||
|
const updateIdentityEvidence = async (evidenceId: number, payload: Record<string, unknown>): Promise<void> => {
|
||||||
if (!selectedCustomer.value) return;
|
if (!selectedCustomer.value) return;
|
||||||
pendingReasonAction.value = { kind: 'update_evidence', evidenceId, payload };
|
const reason = await askAuditReason(
|
||||||
};
|
t('admin.shippingCustomers.identifiers.title'),
|
||||||
/** 确认后提交需要审计原因的治理动作。 */
|
t('admin.shippingCustomers.prompts.identifierChangeReason'),
|
||||||
const confirmReasonAction = async (reason: string): Promise<void> => {
|
t('admin.shippingCustomers.prompts.identifierChangeReason'),
|
||||||
const action = pendingReasonAction.value;
|
);
|
||||||
if (!action || !reason.trim()) return;
|
if (!reason) return;
|
||||||
isSaving.value = true;
|
isSaving.value = true;
|
||||||
try {
|
try {
|
||||||
if (action.kind === 'deactivate') {
|
await updateShippingIdentityEvidence(evidenceId, { ...payload, reason });
|
||||||
await deactivateShippingCustomer(action.customer.id, reason.trim());
|
if (selectedCustomer.value) selectedCustomer.value = await getShippingCustomer(selectedCustomer.value.id);
|
||||||
await loadCustomers();
|
|
||||||
} else {
|
|
||||||
await updateShippingIdentityEvidence(action.evidenceId, { ...action.payload, reason: reason.trim() });
|
|
||||||
if (selectedCustomer.value) selectedCustomer.value = await getShippingCustomer(selectedCustomer.value.id);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showError(error, 'admin.shippingCustomers.msg.saveFailed');
|
showError(error, 'admin.shippingCustomers.msg.saveFailed');
|
||||||
} finally {
|
} finally {
|
||||||
isSaving.value = false;
|
isSaving.value = false;
|
||||||
pendingReasonAction.value = null;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const cancelReasonAction = (): void => { pendingReasonAction.value = null; };
|
|
||||||
|
|
||||||
/** 新增外部系统客户编码,并重新读取客户详情。 */
|
/** 新增外部系统客户编码,并重新读取客户详情。 */
|
||||||
const addExternalRef = async (payload: { source_system: string; customer_code: string }): Promise<void> => {
|
const addExternalRef = async (payload: { source_system: string; customer_code: string }): Promise<void> => {
|
||||||
@@ -518,9 +560,9 @@ export function useShippingCustomersAdmin() {
|
|||||||
customers, importTargetCustomers, selectedCustomer, publishedEvidenceDefinitions, customerForm, importBatch, shadowReport, deleteCustomer, deleteImpact, lifecycleCustomer, lifecycleTimeline, mergeCustomer, mergeImpact,
|
customers, importTargetCustomers, selectedCustomer, publishedEvidenceDefinitions, customerForm, importBatch, shadowReport, deleteCustomer, deleteImpact, lifecycleCustomer, lifecycleTimeline, mergeCustomer, mergeImpact,
|
||||||
searchQuery, statusFilter, page, pageSize, total, pages,
|
searchQuery, statusFilter, page, pageSize, total, pages,
|
||||||
isLoading, isSaving, isImporting, isShadowLoading,
|
isLoading, isSaving, isImporting, isShadowLoading,
|
||||||
showCustomerModal, showIdentifiersPanel, showImportDialog, showDeleteDialog, showLifecyclePanel, showMergeDialog, pendingReasonAction,
|
showCustomerModal, showIdentifiersPanel, showImportDialog, showDeleteDialog, showLifecyclePanel, showMergeDialog,
|
||||||
loadCustomers, searchCustomers, openCreateCustomer, openEditCustomer, closeCustomerModal,
|
loadCustomers, searchCustomers, openCreateCustomer, openEditCustomer, closeCustomerModal,
|
||||||
saveCustomer, deactivateCustomer, confirmReasonAction, cancelReasonAction, openLifecycleTimeline, closeLifecycleTimeline, openDeleteCustomer, closeDeleteCustomer, confirmDeleteCustomer, openMergeCustomer, previewMergeCustomer, closeMergeCustomer, confirmMergeCustomer, openIdentifiers, addIdentityEvidence, updateIdentityEvidence, addExternalRef, addSite,
|
saveCustomer, deactivateCustomer, openLifecycleTimeline, closeLifecycleTimeline, openDeleteCustomer, closeDeleteCustomer, confirmDeleteCustomer, openMergeCustomer, previewMergeCustomer, closeMergeCustomer, confirmMergeCustomer, openIdentifiers, addIdentityEvidence, updateIdentityEvidence, addExternalRef, addSite,
|
||||||
openImport, uploadImport, decideImportRow, publishImport, downloadTemplate, downloadReconciliation,
|
openImport, uploadImport, decideImportRow, publishImport, downloadTemplate, downloadReconciliation,
|
||||||
loadShadowReport, labelShadowResolution,
|
loadShadowReport, labelShadowResolution,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,30 +1,50 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
/**
|
/**
|
||||||
* features/user/views/UserProfilePage.vue
|
* features/user/views/UserProfilePage.vue
|
||||||
* 用途:工作台个人中心,展示与编辑当前用户资料、语言/主题偏好,并提供修改密码入口。
|
* 用途:工作台个人中心,展示与编辑当前用户资料、语言/主题偏好,并提供修改密码入口。
|
||||||
* 依赖:workspace.context(WORKSPACE_KEY)、lucide 图标、vue-i18n、isPlatformAdminUser。
|
* 依赖:workspace.context(WORKSPACE_KEY)、element-plus、element-theme.css、vue-i18n、isPlatformAdminUser、getUserAvatarLabel。
|
||||||
* 逻辑:路由 /workspace/profile 懒加载本页;资料状态由 useWorkspaceProfile 经工作台注入。
|
* 逻辑:路由 /workspace/profile 懒加载本页。资料状态由 useWorkspaceProfile 经工作台注入。
|
||||||
* 角色展示优先用权限组名称;旧会话缺 role_name 时再按 is_platform_admin 回退。
|
* 角色展示优先用权限组名称;旧会话缺 role_name 时再按 is_platform_admin 回退。
|
||||||
|
* 改密弹窗在 WorkspaceModals。头像继续用品牌圆标,不用 ElAvatar。
|
||||||
*/
|
*/
|
||||||
|
<script setup lang="ts">
|
||||||
import { computed, inject } from 'vue';
|
import { computed, inject } from 'vue';
|
||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
|
import { Check, Edit } from '@element-plus/icons-vue';
|
||||||
import {
|
import {
|
||||||
User, Mail, Building, CreditCard, Globe, Save, Palette,
|
ElButton,
|
||||||
} from 'lucide-vue-next';
|
ElCard,
|
||||||
|
ElForm,
|
||||||
|
ElFormItem,
|
||||||
|
ElInput,
|
||||||
|
ElLoading,
|
||||||
|
ElOption,
|
||||||
|
ElRadioButton,
|
||||||
|
ElRadioGroup,
|
||||||
|
ElSelect,
|
||||||
|
ElText,
|
||||||
|
} from 'element-plus';
|
||||||
|
import 'element-plus/dist/index.css';
|
||||||
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
|
import '@/shared/styles/element-theme.css';
|
||||||
import { getUserAvatarLabel } from '@/shared/utils/user-avatar';
|
import { getUserAvatarLabel } from '@/shared/utils/user-avatar';
|
||||||
import { WORKSPACE_KEY } from '@/features/workspace/composables/workspace.context';
|
import { WORKSPACE_KEY } from '@/features/workspace/composables/workspace.context';
|
||||||
import { isPlatformAdminUser } from '@/shared/utils/auth';
|
import { isPlatformAdminUser } from '@/shared/utils/auth';
|
||||||
|
|
||||||
|
const vLoading = ElLoading.directive;
|
||||||
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const userProfile = inject(WORKSPACE_KEY)!;
|
const userProfile = inject(WORKSPACE_KEY)!;
|
||||||
|
|
||||||
/** 只读字段值:与 input-field 同高,正文统一 14px。 */
|
const languageOptions = computed(() => [
|
||||||
const fieldValueClass = 'flex min-h-11 items-center rounded-xl border border-default bg-surface-soft px-4 text-sm font-medium text-secondary';
|
{ value: 'zh-CN', label: t('workspace.lang.zhCN') },
|
||||||
/** 表单标签:与分区标题区分层级,全页统一 14px。 */
|
{ value: 'zh-TW', label: t('workspace.lang.zhTW') },
|
||||||
const fieldLabelClass = 'mb-1.5 flex items-center gap-1.5 text-sm font-medium text-muted';
|
{ value: 'en', label: 'English' },
|
||||||
|
{ value: 'th', label: 'Thai' },
|
||||||
|
]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 身份主标题:优先真实姓名,缺失时回退用户名。
|
* 身份主标题:优先真实姓名,缺失时回退用户名。
|
||||||
|
* @returns 展示姓名
|
||||||
*/
|
*/
|
||||||
const displayName = computed(() => {
|
const displayName = computed(() => {
|
||||||
return userProfile.profileUser.real_name || userProfile.profileUser.username || '-';
|
return userProfile.profileUser.real_name || userProfile.profileUser.username || '-';
|
||||||
@@ -33,6 +53,7 @@ const displayName = computed(() => {
|
|||||||
/**
|
/**
|
||||||
* 个人中心角色标签。
|
* 个人中心角色标签。
|
||||||
* 核心逻辑:有权限组名称就展示名称;否则按 is_platform_admin 回退内置文案。
|
* 核心逻辑:有权限组名称就展示名称;否则按 is_platform_admin 回退内置文案。
|
||||||
|
* @returns 角色文案
|
||||||
*/
|
*/
|
||||||
const profileRoleLabel = computed(() => {
|
const profileRoleLabel = computed(() => {
|
||||||
const user = userProfile.profileUser || {};
|
const user = userProfile.profileUser || {};
|
||||||
@@ -42,6 +63,7 @@ const profileRoleLabel = computed(() => {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 身份副标题:用户名(与主标题不同时)、部门、角色用间隔点拼接,空项省略。
|
* 身份副标题:用户名(与主标题不同时)、部门、角色用间隔点拼接,空项省略。
|
||||||
|
* @returns 副标题;没有可展示项时为空字符串
|
||||||
*/
|
*/
|
||||||
const identityMeta = computed(() => {
|
const identityMeta = computed(() => {
|
||||||
const username = userProfile.profileUser.username;
|
const username = userProfile.profileUser.username;
|
||||||
@@ -50,222 +72,268 @@ const identityMeta = computed(() => {
|
|||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(' · ');
|
.join(' · ');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 只读时用短横线占位,编辑时保留空字符串以便继续输入。
|
||||||
|
* @param value - 资料字段当前值
|
||||||
|
* @returns 输入框展示文字
|
||||||
|
*/
|
||||||
|
function fieldText(value: string | undefined): string {
|
||||||
|
if (userProfile.isProfileEditing) return value || '';
|
||||||
|
return value || '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 编辑态写回资料字段。只读时忽略输入框回写,避免把占位短横线存进去。
|
||||||
|
* @param key - 可编辑的资料字段
|
||||||
|
* @param value - 输入框新值
|
||||||
|
*/
|
||||||
|
function onProfileField(
|
||||||
|
key: 'employee_id' | 'real_name' | 'department' | 'email' | 'phone_number',
|
||||||
|
value: string,
|
||||||
|
): void {
|
||||||
|
if (!userProfile.isProfileEditing) return;
|
||||||
|
userProfile.profileUser[key] = value;
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="userProfile.isProfileLoading" class="flex justify-center py-20">
|
<div v-loading="userProfile.isProfileLoading" class="profile-page">
|
||||||
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
|
<template v-if="!userProfile.isProfileLoading">
|
||||||
</div>
|
<ElCard shadow="never" class="profile-identity">
|
||||||
|
<div class="profile-identity__body">
|
||||||
<div v-else class="space-y-6">
|
<div class="profile-identity__person">
|
||||||
<div class="rounded-3xl border border-default bg-surface px-6 py-6 shadow-sm md:px-8">
|
<div class="profile-avatar" :class="userProfile.isMobile ? 'profile-avatar--compact' : ''">
|
||||||
<div class="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
|
{{ getUserAvatarLabel(userProfile.profileUser) }}
|
||||||
<div class="flex flex-1 flex-col gap-6 sm:flex-row sm:items-center sm:justify-start">
|
</div>
|
||||||
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600" :class="userProfile.isMobile ? 'h-14 w-14 text-2xl' : ''">
|
<div class="profile-identity__text">
|
||||||
{{ getUserAvatarLabel(userProfile.profileUser) }}
|
<div class="section-title">{{ displayName }}</div>
|
||||||
</div>
|
<ElText v-if="identityMeta" type="info">{{ identityMeta }}</ElText>
|
||||||
<div class="min-w-0 space-y-0.5">
|
<ElText v-if="userProfile.profileUser.email" type="info" class="profile-identity__email">
|
||||||
<div class="truncate text-lg font-semibold text-primary">{{ displayName }}</div>
|
{{ userProfile.profileUser.email }}
|
||||||
<div v-if="identityMeta" class="truncate text-sm text-muted">{{ identityMeta }}</div>
|
</ElText>
|
||||||
<div v-if="userProfile.profileUser.email" class="break-all text-sm text-muted">
|
|
||||||
{{ userProfile.profileUser.email }}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div class="profile-identity__actions">
|
||||||
<div v-if="!userProfile.isMobile" class="shrink-0">
|
<ElButton type="primary" @click="userProfile.handleChangePasswordClick">
|
||||||
<button type="button" class="btn-primary btn-sm" @click="userProfile.handleChangePasswordClick">
|
{{ t('profile.changePassword') }}
|
||||||
{{ $t('profile.changePassword') }}
|
</ElButton>
|
||||||
</button>
|
<ElButton v-if="userProfile.isMobile" type="danger" plain @click="userProfile.handleLogout">
|
||||||
</div>
|
{{ t('workspace.nav.logout') }}
|
||||||
</div>
|
</ElButton>
|
||||||
<div v-if="userProfile.isMobile" class="mt-4 flex items-center gap-3">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn-primary btn-sm flex-1"
|
|
||||||
@click="userProfile.handleChangePasswordClick"
|
|
||||||
>
|
|
||||||
{{ $t('profile.changePassword') }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="btn-secondary btn-sm flex-1 text-red-600 hover:bg-red-50"
|
|
||||||
@click="userProfile.handleLogout"
|
|
||||||
>
|
|
||||||
{{ $t('workspace.nav.logout') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="space-y-6">
|
|
||||||
<div class="rounded-2xl border border-default bg-surface p-5 shadow-sm md:p-6">
|
|
||||||
<div class="mb-5 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
|
||||||
<div class="flex items-center gap-2" :class="userProfile.isMobile ? 'w-full justify-between' : ''">
|
|
||||||
<h3 class="section-title flex items-center gap-2">
|
|
||||||
<User class="h-5 w-5 text-brand-500" />
|
|
||||||
{{ $t('profile.basicInfo') }}
|
|
||||||
</h3>
|
|
||||||
<button
|
|
||||||
v-if="userProfile.isMobile && !userProfile.isProfileEditing"
|
|
||||||
type="button"
|
|
||||||
class="btn-secondary btn-sm"
|
|
||||||
@click="userProfile.startProfileEditing"
|
|
||||||
>
|
|
||||||
{{ $t('profile.edit') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
<p v-if="!userProfile.isMobile" class="section-desc">
|
</div>
|
||||||
{{ userProfile.isProfileEditing ? $t('profile.directEditHint') : $t('profile.switchEditHint') }}
|
</ElCard>
|
||||||
</p>
|
|
||||||
<div v-if="!userProfile.isMobile" class="flex items-center gap-2">
|
<ElCard shadow="never">
|
||||||
<button
|
<template #header>
|
||||||
v-if="!userProfile.isProfileEditing"
|
<div class="profile-card-head">
|
||||||
type="button"
|
<div>
|
||||||
class="btn-secondary btn-sm"
|
<h3 class="section-title">{{ t('profile.basicInfo') }}</h3>
|
||||||
@click="userProfile.startProfileEditing"
|
<p v-if="!userProfile.isMobile" class="section-desc">
|
||||||
>
|
{{ userProfile.isProfileEditing ? t('profile.directEditHint') : t('profile.switchEditHint') }}
|
||||||
{{ $t('profile.edit') }}
|
</p>
|
||||||
</button>
|
</div>
|
||||||
<template v-else>
|
<div class="profile-card-head__actions">
|
||||||
<button type="button" class="btn-secondary btn-sm" @click="userProfile.cancelProfileEditing">
|
<ElButton
|
||||||
{{ $t('profile.cancel') }}
|
v-if="!userProfile.isProfileEditing"
|
||||||
</button>
|
:icon="Edit"
|
||||||
<button
|
@click="userProfile.startProfileEditing"
|
||||||
type="button"
|
|
||||||
class="btn-primary btn-sm disabled:cursor-not-allowed disabled:opacity-50"
|
|
||||||
:disabled="userProfile.isProfileSaving || !userProfile.hasProfileUnsavedChanges"
|
|
||||||
@click="userProfile.saveProfile"
|
|
||||||
>
|
>
|
||||||
<Save class="h-4 w-4" />
|
{{ t('profile.edit') }}
|
||||||
<span>{{ userProfile.isProfileSaving ? $t('profile.saving') : $t('workspace.save') }}</span>
|
</ElButton>
|
||||||
</button>
|
<template v-else>
|
||||||
</template>
|
<ElButton @click="userProfile.cancelProfileEditing">{{ t('profile.cancel') }}</ElButton>
|
||||||
</div>
|
<ElButton
|
||||||
</div>
|
type="primary"
|
||||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
:icon="Check"
|
||||||
<div>
|
:loading="userProfile.isProfileSaving"
|
||||||
<label :class="fieldLabelClass">
|
:disabled="!userProfile.hasProfileUnsavedChanges"
|
||||||
<User class="h-4 w-4" /> {{ $t('profile.username') }}
|
@click="userProfile.saveProfile"
|
||||||
</label>
|
>
|
||||||
<div :class="fieldValueClass">
|
{{ userProfile.isProfileSaving ? t('profile.saving') : t('workspace.save') }}
|
||||||
{{ userProfile.profileUser.username || '-' }}
|
</ElButton>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
</template>
|
||||||
<label :class="fieldLabelClass">
|
<ElForm label-position="top" class="profile-form">
|
||||||
<CreditCard class="h-4 w-4" /> {{ $t('profile.employeeId') }}
|
<div class="profile-form__grid">
|
||||||
</label>
|
<ElFormItem :label="t('profile.username')">
|
||||||
<input
|
<ElInput :model-value="userProfile.profileUser.username || '-'" disabled />
|
||||||
v-if="userProfile.isProfileEditing"
|
</ElFormItem>
|
||||||
v-model="userProfile.profileUser.employee_id"
|
<ElFormItem :label="t('profile.employeeId')">
|
||||||
type="text"
|
<ElInput
|
||||||
class="input-field text-sm"
|
:model-value="fieldText(userProfile.profileUser.employee_id)"
|
||||||
>
|
|
||||||
<div v-else :class="fieldValueClass">
|
|
||||||
{{ userProfile.profileUser.employee_id || '-' }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label :class="fieldLabelClass">
|
|
||||||
<User class="h-4 w-4" /> {{ $t('profile.realName') }}
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
v-if="userProfile.isProfileEditing"
|
|
||||||
v-model="userProfile.profileUser.real_name"
|
|
||||||
type="text"
|
|
||||||
class="input-field text-sm"
|
|
||||||
>
|
|
||||||
<div v-else :class="fieldValueClass">
|
|
||||||
{{ userProfile.profileUser.real_name || '-' }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label :class="fieldLabelClass">
|
|
||||||
<Building class="h-4 w-4" /> {{ $t('profile.department') }}
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
v-if="userProfile.isProfileEditing"
|
|
||||||
v-model="userProfile.profileUser.department"
|
|
||||||
type="text"
|
|
||||||
class="input-field text-sm"
|
|
||||||
>
|
|
||||||
<div v-else :class="fieldValueClass">
|
|
||||||
{{ userProfile.profileUser.department || '-' }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label :class="fieldLabelClass">
|
|
||||||
<Mail class="h-4 w-4" /> {{ $t('profile.email') }}
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
v-if="userProfile.isProfileEditing"
|
|
||||||
v-model="userProfile.profileUser.email"
|
|
||||||
type="email"
|
|
||||||
class="input-field text-sm"
|
|
||||||
>
|
|
||||||
<div v-else :class="fieldValueClass">
|
|
||||||
{{ userProfile.profileUser.email || '-' }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label :class="fieldLabelClass">
|
|
||||||
<Globe class="h-4 w-4" /> {{ $t('profile.phoneNumber') }}
|
|
||||||
</label>
|
|
||||||
<input
|
|
||||||
v-if="userProfile.isProfileEditing"
|
|
||||||
v-model="userProfile.profileUser.phone_number"
|
|
||||||
type="text"
|
|
||||||
class="input-field text-sm"
|
|
||||||
>
|
|
||||||
<div v-else :class="fieldValueClass">
|
|
||||||
{{ userProfile.profileUser.phone_number || '-' }}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="rounded-2xl border border-default bg-surface p-5 shadow-sm md:p-6">
|
|
||||||
<h3 class="section-title mb-5 flex items-center gap-2">
|
|
||||||
<Palette class="h-5 w-5 text-brand-500" />
|
|
||||||
{{ $t('profile.preferences') }}
|
|
||||||
</h3>
|
|
||||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
|
|
||||||
<div>
|
|
||||||
<label class="mb-1.5 block text-sm font-medium text-muted">{{ $t('workspace.languageLabel') }}</label>
|
|
||||||
<select
|
|
||||||
v-model="userProfile.profileUser.language"
|
|
||||||
class="select-field text-sm"
|
|
||||||
:disabled="!userProfile.isProfileEditing"
|
|
||||||
>
|
|
||||||
<option value="en">English</option>
|
|
||||||
<option value="zh-CN">{{ $t('workspace.lang.zhCN') }}</option>
|
|
||||||
<option value="zh-TW">{{ $t('workspace.lang.zhTW') }}</option>
|
|
||||||
<option value="th">Thai</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label class="mb-1.5 block text-sm font-medium text-muted">{{ $t('profile.theme') }}</label>
|
|
||||||
<div
|
|
||||||
class="segment-control segment-control--cols-3 segment-control--md"
|
|
||||||
role="radiogroup"
|
|
||||||
:aria-label="$t('profile.theme')"
|
|
||||||
>
|
|
||||||
<button
|
|
||||||
v-for="item in userProfile.themeOptions"
|
|
||||||
:key="item.value"
|
|
||||||
type="button"
|
|
||||||
role="radio"
|
|
||||||
class="segment-item"
|
|
||||||
:aria-checked="userProfile.profileUser.theme_preference === item.value"
|
|
||||||
:disabled="!userProfile.isProfileEditing"
|
:disabled="!userProfile.isProfileEditing"
|
||||||
:class="userProfile.profileUser.theme_preference === item.value ? 'segment-item--active' : ''"
|
@update:model-value="onProfileField('employee_id', $event)"
|
||||||
@click="userProfile.profileUser.theme_preference = item.value"
|
/>
|
||||||
>
|
</ElFormItem>
|
||||||
{{ item.label() }}
|
<ElFormItem :label="t('profile.realName')">
|
||||||
</button>
|
<ElInput
|
||||||
</div>
|
:model-value="fieldText(userProfile.profileUser.real_name)"
|
||||||
|
:disabled="!userProfile.isProfileEditing"
|
||||||
|
@update:model-value="onProfileField('real_name', $event)"
|
||||||
|
/>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem :label="t('profile.department')">
|
||||||
|
<ElInput
|
||||||
|
:model-value="fieldText(userProfile.profileUser.department)"
|
||||||
|
:disabled="!userProfile.isProfileEditing"
|
||||||
|
@update:model-value="onProfileField('department', $event)"
|
||||||
|
/>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem :label="t('profile.email')">
|
||||||
|
<ElInput
|
||||||
|
:model-value="fieldText(userProfile.profileUser.email)"
|
||||||
|
:disabled="!userProfile.isProfileEditing"
|
||||||
|
@update:model-value="onProfileField('email', $event)"
|
||||||
|
/>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem :label="t('profile.phoneNumber')">
|
||||||
|
<ElInput
|
||||||
|
:model-value="fieldText(userProfile.profileUser.phone_number)"
|
||||||
|
:disabled="!userProfile.isProfileEditing"
|
||||||
|
@update:model-value="onProfileField('phone_number', $event)"
|
||||||
|
/>
|
||||||
|
</ElFormItem>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</ElForm>
|
||||||
</div>
|
</ElCard>
|
||||||
</div>
|
|
||||||
|
<ElCard shadow="never">
|
||||||
|
<template #header>
|
||||||
|
<h3 class="section-title">{{ t('profile.preferences') }}</h3>
|
||||||
|
</template>
|
||||||
|
<ElForm label-position="top" class="profile-form">
|
||||||
|
<div class="profile-form__grid">
|
||||||
|
<ElFormItem :label="t('workspace.languageLabel')">
|
||||||
|
<ElSelect
|
||||||
|
v-model="userProfile.profileUser.language"
|
||||||
|
class="profile-control"
|
||||||
|
:disabled="!userProfile.isProfileEditing"
|
||||||
|
>
|
||||||
|
<ElOption
|
||||||
|
v-for="item in languageOptions"
|
||||||
|
:key="item.value"
|
||||||
|
:label="item.label"
|
||||||
|
:value="item.value"
|
||||||
|
/>
|
||||||
|
</ElSelect>
|
||||||
|
</ElFormItem>
|
||||||
|
<ElFormItem :label="t('profile.theme')">
|
||||||
|
<ElRadioGroup
|
||||||
|
v-model="userProfile.profileUser.theme_preference"
|
||||||
|
:disabled="!userProfile.isProfileEditing"
|
||||||
|
>
|
||||||
|
<ElRadioButton
|
||||||
|
v-for="item in userProfile.themeOptions"
|
||||||
|
:key="item.value"
|
||||||
|
:value="item.value"
|
||||||
|
>
|
||||||
|
{{ item.label() }}
|
||||||
|
</ElRadioButton>
|
||||||
|
</ElRadioGroup>
|
||||||
|
</ElFormItem>
|
||||||
|
</div>
|
||||||
|
</ElForm>
|
||||||
|
</ElCard>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.profile-page {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
min-height: 16rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-identity__body,
|
||||||
|
.profile-card-head,
|
||||||
|
.profile-identity__person,
|
||||||
|
.profile-identity__actions,
|
||||||
|
.profile-card-head__actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-identity__body,
|
||||||
|
.profile-card-head {
|
||||||
|
justify-content: space-between;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-identity__person {
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-identity__text {
|
||||||
|
display: flex;
|
||||||
|
min-width: 0;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-identity__email {
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-avatar {
|
||||||
|
display: flex;
|
||||||
|
width: 72px;
|
||||||
|
height: 72px;
|
||||||
|
flex: none;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: var(--el-color-primary-light-9);
|
||||||
|
color: var(--el-color-primary);
|
||||||
|
font-size: var(--el-font-size-extra-large);
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-avatar--compact {
|
||||||
|
width: 48px;
|
||||||
|
height: 48px;
|
||||||
|
font-size: var(--el-font-size-large);
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-identity__actions,
|
||||||
|
.profile-card-head__actions {
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-form__grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
gap: 0 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-control {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
.profile-form__grid {
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.profile-identity__body,
|
||||||
|
.profile-card-head {
|
||||||
|
align-items: stretch;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-identity__actions {
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-identity__actions :deep(.el-button) {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,116 +1,100 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
/**
|
/**
|
||||||
* features/workspace/components/WorkspaceModals.vue
|
* features/workspace/components/WorkspaceModals.vue
|
||||||
* 工作台弹窗:公告详情、修改密码、快捷问题删除、意见反馈。
|
* 用途:工作台共用弹窗。公告详情、修改密码、快捷问题删除、意见反馈。
|
||||||
|
* 依赖:workspace.context、DeleteConfirmDialog、GeneralFeedbackDialog、element-plus。
|
||||||
|
* 逻辑:WorkspaceLayout 挂载本组件。修改密码和公告详情用 Element 对话框。
|
||||||
|
* 快捷问题删除仍走原有确认弹窗,意见反馈走 GeneralFeedbackDialog。
|
||||||
*/
|
*/
|
||||||
import { inject } from 'vue';
|
import { inject } from 'vue';
|
||||||
import { X } from 'lucide-vue-next';
|
import { ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElTag } from 'element-plus';
|
||||||
|
import 'element-plus/dist/index.css';
|
||||||
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
|
import '@/shared/styles/element-theme.css';
|
||||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||||
import GeneralFeedbackDialog from '@/shared/components/GeneralFeedbackDialog.vue';
|
import GeneralFeedbackDialog from '@/shared/components/GeneralFeedbackDialog.vue';
|
||||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
|
||||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||||
|
|
||||||
const ws = inject(WORKSPACE_KEY)! as any;
|
const ws = inject(WORKSPACE_KEY)! as any;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 提交修改密码。三个密码都填写后才请求,取消和空表单不提交。
|
||||||
|
*/
|
||||||
|
function submitPassword(): void {
|
||||||
|
const form = ws.passwordForm;
|
||||||
|
if (!String(form.current || '').trim() || !String(form.new || '').trim() || !String(form.confirm || '').trim()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
void ws.handleChangePassword();
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div>
|
<div>
|
||||||
<div
|
<ElDialog
|
||||||
v-if="ws.showAnnouncementModal && ws.selectedAnnouncement"
|
:model-value="Boolean(ws.showAnnouncementModal && ws.selectedAnnouncement)"
|
||||||
class="dialog-overlay z-50 items-center animate-fade-in"
|
:title="ws.selectedAnnouncement?.title || ''"
|
||||||
@click.self="ws.showAnnouncementModal = false"
|
width="680px"
|
||||||
|
align-center
|
||||||
|
append-to-body
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
@update:model-value="ws.showAnnouncementModal = $event"
|
||||||
>
|
>
|
||||||
<div class="dialog-panel max-w-2xl max-h-[85vh] animate-slide-up">
|
<ElTag v-if="ws.selectedAnnouncement" effect="light">
|
||||||
<div class="dialog-header">
|
{{ new Date(ws.selectedAnnouncement.created_at).toLocaleDateString() }}
|
||||||
<div class="min-w-0">
|
</ElTag>
|
||||||
<span class="inline-flex rounded-full bg-brand-50 px-2 py-1 text-xs font-bold text-brand-600">{{ new Date(ws.selectedAnnouncement.created_at).toLocaleDateString() }}</span>
|
<p class="workspace-announcement">{{ ws.selectedAnnouncement?.content }}</p>
|
||||||
<h3 class="mt-2 text-2xl font-bold text-primary">{{ ws.selectedAnnouncement.title }}</h3>
|
<template #footer>
|
||||||
</div>
|
<ElButton type="primary" @click="ws.showAnnouncementModal = false">{{ $t('admin.close') }}</ElButton>
|
||||||
<button type="button" class="btn-icon-ds shrink-0" :aria-label="$t('admin.close')" @click="ws.showAnnouncementModal = false">
|
</template>
|
||||||
<X class="w-5 h-5" />
|
</ElDialog>
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="dialog-body">
|
|
||||||
<p class="whitespace-pre-wrap leading-relaxed text-secondary">{{ ws.selectedAnnouncement.content }}</p>
|
|
||||||
</div>
|
|
||||||
<div class="dialog-footer">
|
|
||||||
<button type="button" @click="ws.showAnnouncementModal = false" class="btn-primary">
|
|
||||||
{{ $t('admin.close') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div
|
<ElDialog
|
||||||
v-if="ws.CHANGE_PASSWORD_ENABLED && ws.showPasswordModal"
|
v-if="ws.CHANGE_PASSWORD_ENABLED"
|
||||||
class="dialog-overlay z-50 items-center"
|
v-model="ws.showPasswordModal"
|
||||||
|
:title="$t('profile.changePassword')"
|
||||||
|
width="480px"
|
||||||
|
align-center
|
||||||
|
append-to-body
|
||||||
|
:close-on-click-modal="false"
|
||||||
|
:close-on-press-escape="!ws.isChangingPassword"
|
||||||
|
:show-close="!ws.isChangingPassword"
|
||||||
>
|
>
|
||||||
<div class="dialog-panel max-w-md">
|
<ElForm label-position="top" @submit.prevent="submitPassword">
|
||||||
<div class="dialog-header">
|
<ElFormItem :label="$t('profile.currentPassword')">
|
||||||
<h3 class="section-title">{{ $t('profile.changePassword') || 'Change Password' }}</h3>
|
<ElInput
|
||||||
<button
|
v-model="ws.passwordForm.current"
|
||||||
type="button"
|
type="password"
|
||||||
class="btn-icon-ds"
|
show-password
|
||||||
:aria-label="$t('admin.close')"
|
|
||||||
:disabled="ws.isChangingPassword"
|
:disabled="ws.isChangingPassword"
|
||||||
@click="ws.showPasswordModal = false"
|
/>
|
||||||
>
|
</ElFormItem>
|
||||||
<X class="w-5 h-5" />
|
<ElFormItem :label="$t('profile.newPassword')">
|
||||||
</button>
|
<ElInput
|
||||||
</div>
|
v-model="ws.passwordForm.new"
|
||||||
<form @submit.prevent="ws.handleChangePassword">
|
type="password"
|
||||||
<div class="dialog-body">
|
show-password
|
||||||
<div>
|
:disabled="ws.isChangingPassword"
|
||||||
<label class="label-field">{{ $t('profile.currentPassword') || 'Current Password' }}</label>
|
/>
|
||||||
<input
|
</ElFormItem>
|
||||||
v-model="ws.passwordForm.current"
|
<ElFormItem :label="$t('profile.confirmPassword')">
|
||||||
type="password"
|
<ElInput
|
||||||
class="input-field mt-1"
|
v-model="ws.passwordForm.confirm"
|
||||||
:disabled="ws.isChangingPassword"
|
type="password"
|
||||||
required
|
show-password
|
||||||
/>
|
:disabled="ws.isChangingPassword"
|
||||||
</div>
|
/>
|
||||||
<div>
|
</ElFormItem>
|
||||||
<label class="label-field">{{ $t('profile.newPassword') || 'New Password' }}</label>
|
</ElForm>
|
||||||
<input
|
<template #footer>
|
||||||
v-model="ws.passwordForm.new"
|
<ElButton :disabled="ws.isChangingPassword" @click="ws.showPasswordModal = false">
|
||||||
type="password"
|
{{ $t('profile.cancel') }}
|
||||||
class="input-field mt-1"
|
</ElButton>
|
||||||
:disabled="ws.isChangingPassword"
|
<ElButton type="primary" :loading="ws.isChangingPassword" @click="submitPassword">
|
||||||
required
|
{{ ws.isChangingPassword ? $t('profile.changingPassword') : $t('profile.changePassword') }}
|
||||||
/>
|
</ElButton>
|
||||||
</div>
|
</template>
|
||||||
<div>
|
</ElDialog>
|
||||||
<label class="label-field">{{ $t('profile.confirmPassword') || 'Confirm Password' }}</label>
|
|
||||||
<input
|
|
||||||
v-model="ws.passwordForm.confirm"
|
|
||||||
type="password"
|
|
||||||
class="input-field mt-1"
|
|
||||||
:disabled="ws.isChangingPassword"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="dialog-footer">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
:disabled="ws.isChangingPassword"
|
|
||||||
@click="ws.showPasswordModal = false"
|
|
||||||
class="btn-secondary flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
>
|
|
||||||
{{ $t('profile.cancel') || 'Cancel' }}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
:disabled="ws.isChangingPassword"
|
|
||||||
class="btn-primary flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
|
|
||||||
>
|
|
||||||
{{ ws.isChangingPassword ? $t('profile.changingPassword') : ($t('profile.changePassword') || 'Update') }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<DeleteConfirmDialog
|
<DeleteConfirmDialog
|
||||||
v-model="ws.showDeleteQuickQuestionDialog"
|
v-model="ws.showDeleteQuickQuestionDialog"
|
||||||
@@ -121,9 +105,17 @@ const ws = inject(WORKSPACE_KEY)! as any;
|
|||||||
/>
|
/>
|
||||||
<GeneralFeedbackDialog
|
<GeneralFeedbackDialog
|
||||||
v-model="ws.showGeneralFeedbackDialog"
|
v-model="ws.showGeneralFeedbackDialog"
|
||||||
:auth-headers="getAuthHeaders()"
|
|
||||||
source-page="workspace"
|
source-page="workspace"
|
||||||
@submitted="ws.msg.success('反馈提交成功')"
|
@submitted="ws.msg.success('反馈提交成功')"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.workspace-announcement {
|
||||||
|
margin: 12px 0 0;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
line-height: 1.7;
|
||||||
|
color: var(--el-text-color-regular);
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -1,12 +1,16 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
/**
|
/**
|
||||||
* features/workspace/pages/FeedbackPage.vue
|
* features/workspace/pages/FeedbackPage.vue
|
||||||
* 意见反馈占位页;进入路由时由编排层打开 GeneralFeedbackDialog。
|
* 用途:意见反馈占位页。真正的表单由编排层打开 GeneralFeedbackDialog。
|
||||||
|
* 依赖:element-plus、element-theme.css。
|
||||||
|
* 逻辑:进入路由时工作台打开反馈弹窗,本页只保留空状态。
|
||||||
*/
|
*/
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ElEmpty } from 'element-plus';
|
||||||
|
import 'element-plus/dist/index.css';
|
||||||
|
import 'element-plus/theme-chalk/dark/css-vars.css';
|
||||||
|
import '@/shared/styles/element-theme.css';
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col items-center justify-center py-20 text-muted">
|
<ElEmpty :description="$t('workspace.nav.feedback')" />
|
||||||
<p class="text-sm">{{ $t('workspace.nav.feedback') }}</p>
|
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user