Merge branch 'dev' into picture-feedback
This commit is contained in:
commit
34ad40778b
180 files changed
+13262
-5333
No files matched your search
@@ -18,4 +18,4 @@ globs: frontend/src/features/admin/**/*.vue,frontend/src/features/kb/components/
|
||||
- 按钮、输入、下拉、表格、弹窗、分页用 Element Plus,不要新写 `<button>`、`<input>`、`<select>`、`<textarea>`。
|
||||
- 不要新写 `btn-primary`、`btn-secondary`、`btn-ghost`、`btn-danger`、`input-field`、`select-field`。
|
||||
- 图标用 `@element-plus/icons-vue`,不要新加 `lucide-vue-next`。
|
||||
- 字号和颜色用 `element-trial.css` 里的 Element 变量,不要在单元格上写 `text-sm`、`text-xs`、`text-muted`。
|
||||
- 字号和颜色用 `shared/styles/element-theme.css` 里的 Element 变量,不要在单元格上写 `text-sm`、`text-xs`、`text-muted`。
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
这次改动如果碰到管理控制台、知识库配置,或已经换成 Element Plus 的页面,按 `docs/ui/ELEMENT_MIGRATION.md` §6 核对。没改界面就删掉下面的清单。
|
||||
|
||||
- [ ] 只在该页入口引入 Element 样式和 `element-trial.css`,并用 `ElConfigProvider` 包住。
|
||||
- [ ] 只在该页入口引入 Element 样式。全站皮肤用 `element-theme.css`;管理列表用 `element-trial.css`(已包含全站皮肤)。不要再包 `ElConfigProvider`。
|
||||
- [ ] 列表骨架符合规范 §3,左右 32px 对齐,只有一层卡片。
|
||||
- [ ] 按钮符合规范 §4.1,没有 `size="small"` 和默认按钮混在一行。
|
||||
- [ ] 表格状态是 `ElTag`,单元格没有 `text-xs` / `text-sm` / `text-muted`。
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.2 MiB |
@@ -0,0 +1,90 @@
|
||||
[
|
||||
{
|
||||
"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.
|
After Width: | Height: | Size: 1.8 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 275 KiB |
@@ -0,0 +1,533 @@
|
||||
<!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>
|
||||
@@ -43,7 +43,7 @@ def _ok(data, *, status: int = 200):
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_rpa_profiles():
|
||||
"""列出脱敏后的 RPA Profile 配置。"""
|
||||
"""列出 RPA Profile;响应含用户名明文,不含密码与密文。"""
|
||||
return _ok(freight_rpa_source_admin_service.list_profiles())
|
||||
|
||||
|
||||
@@ -57,7 +57,7 @@ def create_shipping_rpa_profile():
|
||||
@admin_bp.route('/freight-rpa/rpa-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_rpa_profile(profile_id: int):
|
||||
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
|
||||
"""更新 RPA Profile;用户名与已存明文相同、或密码留空时不重写对应密文。"""
|
||||
return _ok(freight_rpa_source_admin_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
|
||||
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ backend/app/api/contract_payment/__init__.py
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要、四张汇总卡和周汇总批次;失败批次返回可展示原因。同步和预警操作入队,避免请求线程执行外部系统和企微调用;发送后可按 Job 查询是否真正完成。
|
||||
下载和单合同重解析走 read_contract_attachment_bytes:原文还在则直接读,被临时清理删掉则按附件 ID 从 OA/DMS 重新下载。
|
||||
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。未付的预付款、出货款可手动标为已付。
|
||||
待确认合同的人工复核走 apply_manual_review:比例合计 100% 后改为已解析并进入台账。四个付款阶段未付时都可手动标为已付。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍;同时返回 OA 公司及对应 ERP 账套。
|
||||
鉴权:查询接口要求平台管理员(is_platform_admin)或持有 `agent_code=contract_payment` 的 Agent 授权;
|
||||
同步/扫描/周汇总发送仅平台管理员。权限组启用后,普通用户通过角色包获得该 Agent,不再按人授权。
|
||||
@@ -641,9 +641,9 @@ def manual_review_contract(contract_id: int):
|
||||
@contract_payment_bp.route("/contracts/<int:contract_id>/nodes/<int:node_id>/mark-paid", methods=["POST"])
|
||||
def mark_contract_node_paid(contract_id: int, node_id: int):
|
||||
"""
|
||||
把未付的预付款或出货款手动标为已付。
|
||||
把未付的付款阶段手动标为已付。
|
||||
|
||||
核心逻辑:与人工复核一样,持有合同付款 Agent 的用户即可提交。只改这一阶段,并关闭尚未发送的预警。
|
||||
核心逻辑:与人工复核一样,持有合同付款 Agent 的用户即可提交。四个阶段都可以标记,只改这一阶段,并关闭尚未发送的预警。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
|
||||
@@ -110,7 +110,7 @@ def sync_equipment_acceptance():
|
||||
|
||||
@equipment_acceptance_bp.route("/orders", methods=["GET"])
|
||||
def list_equipment_acceptance_orders():
|
||||
"""分页查看已同步的验收单。focus 按原型分组过滤,summary 始终统计全部单据。"""
|
||||
"""分页查看已同步的验收单。focus 按状态分组,keyword 查三种单号,applicant 查申请人。"""
|
||||
_require_equipment_acceptance_access()
|
||||
page = _int_arg("page", 1)
|
||||
page_size = _int_arg("page_size", 20)
|
||||
@@ -119,6 +119,8 @@ def list_equipment_acceptance_orders():
|
||||
focus=request.args.get("focus"),
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
keyword=request.args.get("keyword"),
|
||||
applicant=request.args.get("applicant"),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ backend/app/api/freight_rpa.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.tool_auth import require_tool_auth
|
||||
@@ -65,6 +65,12 @@ def heartbeat():
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc))
|
||||
# 心跳存储不可用(ServiceUnavailableError)原样上抛,由全局 AppError handler 出标准错误 envelope。
|
||||
# 到期的 Crane 定时回查跟着心跳落成 trigger;写失败不让心跳本身失败。
|
||||
try:
|
||||
from app.services.freight_rpa.upload.crane_recheck import materialize_due_crane_rechecks
|
||||
materialize_due_crane_rechecks()
|
||||
except Exception:
|
||||
current_app.logger.exception('crane recheck materialize failed')
|
||||
return jsonify({'status': 'ok', 'message': 'heartbeat recorded', 'data': worker})
|
||||
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
unconfigured 后再各写最多一个 batch;
|
||||
证据下载(POST /sources/inbound-files)按同一函数打包各来源最新可用
|
||||
入站/出站文件;当天清单(GET /sources/<code>/evidence-files)复用可用
|
||||
条件返回当天全部文件,并分别签发预览地址与带保存名的下载地址;
|
||||
条件返回当天全部文件;单文件下载(GET .../evidence-files/<file_id>)
|
||||
由当前站点回传字节,不把 HTTP MinIO 地址交给 HTTPS 页面;
|
||||
匹配创建(POST /matchings)与进度恢复(GET /matchings/{id});执行为 D8
|
||||
异步契约(POST /items/execute → 202 queued + run_no,单在提交时组建);
|
||||
result_unknown 单人工重新触发(POST /runs/{run_no}/documents/{doc_no}/
|
||||
@@ -369,9 +370,9 @@ def list_source_evidence_files_api(source_code: str):
|
||||
查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。
|
||||
可用条件与证据压缩包相同,但返回当天全部可用文件,不只最新一份。
|
||||
每项含 file_id、original_filename、created_at、sha256、file_size、
|
||||
presigned_url、download_url。不解析 Excel,不含行数。预览与下载各签一次
|
||||
presigned_get_url(storage_key, expires_seconds=300);下载地址额外带
|
||||
download_name(库存源_东八区年月日_时分.扩展名),避免浏览器用对象键哈希当保存名。
|
||||
presigned_url、download_url。不解析 Excel,不含行数。预览仍打开
|
||||
presigned_url。单文件下载不使用 download_url,改走
|
||||
GET evidence-files/<file_id>,由当前站点回传。
|
||||
签发时写 TRANSFER_INBOUND_FILES_DOWNLOADED,aggregate_id 为 source_code。
|
||||
"""
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
@@ -401,6 +402,47 @@ def list_source_evidence_files_api(source_code: str):
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/<source_code>/evidence-files/<int:file_id>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def download_source_evidence_file_api(source_code: str, file_id: int):
|
||||
"""把一份仍可用的证据文件经当前站点返回给浏览器。
|
||||
|
||||
查询参数 record_kind 缺省 inbound,只接受 inbound 或 outbound。
|
||||
只接受该来源、该记录类型下仍在可用窗口内的归档。保存名用
|
||||
evidence_download_filename。页面是 HTTPS,MinIO 公网地址是 HTTP,
|
||||
直接打开预签名链接会被浏览器当成不安全下载拦掉。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
file_id: 归档文件主键。
|
||||
|
||||
Returns:
|
||||
附件响应。找不到或已不可用时 404,错误码 SHIPPING.INBOUND_FILE_NOT_FOUND。
|
||||
"""
|
||||
import io
|
||||
import mimetypes
|
||||
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
kind = str(request.args.get("record_kind") or "inbound").strip()
|
||||
if kind not in {"inbound", "outbound"}:
|
||||
raise ValidationError("record_kind must be inbound or outbound")
|
||||
code = str(source_code or "").strip()
|
||||
report = next((item for item in _usable_archive_files(code, kind) if item.id == file_id), None)
|
||||
if report is None:
|
||||
raise NotFoundError("evidence file is not available", code="SHIPPING.INBOUND_FILE_NOT_FOUND")
|
||||
data = file_asset_storage.get_bytes(report.storage_key)
|
||||
download_name = evidence_download_filename(code, report.created_at, report.original_filename)
|
||||
_record_evidence_download_audit(aggregate_id=code)
|
||||
mime = mimetypes.guess_type(download_name)[0] or "application/octet-stream"
|
||||
return send_file(
|
||||
io.BytesIO(data),
|
||||
mimetype=mime,
|
||||
as_attachment=True,
|
||||
download_name=download_name,
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def get_run_api(run_no: str):
|
||||
@@ -1436,6 +1478,7 @@ def _serialize_backlog_item(item) -> dict[str, Any]:
|
||||
'item_id': item.item_id,
|
||||
'source_code': item.source_code,
|
||||
'invoice_no': item.invoice_no,
|
||||
'external_doc_no': item.external_doc_no,
|
||||
'material_no': item.material_no,
|
||||
'status': item.status,
|
||||
'reason': item.reason,
|
||||
|
||||
@@ -1102,6 +1102,47 @@ def workspace_confirm_shipping_notice_uploaded(business_no: str):
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/refresh-crane-upload', methods=['POST'])
|
||||
def workspace_refresh_crane_upload_status(business_no: str):
|
||||
"""手动刷新一张仍在分配中的 Crane 发货单。
|
||||
|
||||
核心逻辑:校验当前用户可见的通知单,读取最近一次上传尝试,写入一条只查状态的 trigger。
|
||||
不改 10 分钟定时回查的到期时间,也不重新上传 Excel。
|
||||
|
||||
Args:
|
||||
business_no: 对外发货通知单号,同时是 Crane 的 Pull Request #。
|
||||
|
||||
Returns:
|
||||
JSON: business_no 与 trigger_queued。
|
||||
|
||||
Raises:
|
||||
ValidationError: 没有可刷新的上传尝试或来源连接。
|
||||
ConflictError: 当前不是分配中,或上一次手动刷新还在排队。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
|
||||
from app.services.freight_rpa.upload.crane_recheck import request_manual_crane_refresh
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
|
||||
|
||||
attempt = latest_upload_attempt(task)
|
||||
from app.models import ShippingExportArtifact
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id) if attempt is not None else None
|
||||
snapshot = task_rpa_inventory_source(task) or {}
|
||||
upload_source = get_rpa_trigger_inventory_source(str(snapshot.get('source_code') or '')) if snapshot.get('source_code') else None
|
||||
if attempt is None or artifact is None or not isinstance(upload_source, dict):
|
||||
raise ValidationError('Crane upload status cannot be refreshed', code='SHIPPING.UPLOAD_CRANE_ALLOCATING')
|
||||
trigger_path = request_manual_crane_refresh(
|
||||
attempt,
|
||||
upload_source,
|
||||
task_no=str(task.task_no),
|
||||
export_file_path=str(artifact.file_path or ''),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'business_no': str(task.business_no), 'trigger_queued': bool(trigger_path)})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
|
||||
def workspace_start_shipping_notice_rpa_upload(business_no: str):
|
||||
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
|
||||
|
||||
@@ -4,17 +4,20 @@ backend/app/api/workspace/voucher_check.py
|
||||
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
|
||||
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
|
||||
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
|
||||
批次明细可按 result 与 invoice_no 筛选。企微记录里的 Excel 走本模块下载,不走排程通知人权限。
|
||||
查询要求 is_platform_admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅平台管理员。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, request
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, request, send_file
|
||||
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import Agent
|
||||
from app.models import Agent, ScheduleRun, VoucherCheckRun
|
||||
from app.services.voucher_check import notify_config_service, query_service
|
||||
|
||||
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
|
||||
@@ -149,12 +152,13 @@ def workspace_voucher_latest_run():
|
||||
def workspace_voucher_run_items(run_id: int):
|
||||
"""
|
||||
分页查看批次明细。
|
||||
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
|
||||
核心逻辑:委托 query_service.list_run_items,可按 result 与 invoice_no 过滤,并返回 by_file_type。
|
||||
"""
|
||||
_require_voucher_check_access()
|
||||
data = query_service.list_run_items(
|
||||
run_id=run_id,
|
||||
result=request.args.get("result"),
|
||||
invoice_no=request.args.get("invoice_no"),
|
||||
page=request.args.get("page", default=1, type=int) or 1,
|
||||
page_size=request.args.get("page_size", default=50, type=int) or 50,
|
||||
)
|
||||
@@ -177,6 +181,33 @@ def workspace_voucher_notifications():
|
||||
return ok(data)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route(
|
||||
"/accounting-voucher-check/schedule-runs/<int:schedule_run_id>/excel",
|
||||
methods=["GET"],
|
||||
)
|
||||
def workspace_voucher_schedule_excel(schedule_run_id: int):
|
||||
"""
|
||||
下载企微发送记录对应的检核结果 Excel。
|
||||
核心逻辑:能看发送记录的人即可下载。只放行已挂到立账凭证批次上的 ScheduleRun,不按排程负责人或通知人拦截。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 该排程记录不是立账凭证批次,或还没有生成 Excel。
|
||||
"""
|
||||
_require_voucher_check_access()
|
||||
engine = VoucherCheckRun.query.filter_by(schedule_run_id=schedule_run_id).first()
|
||||
if engine is None:
|
||||
raise NotFoundError("立账凭证检核批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
||||
run = ScheduleRun.query.get(schedule_run_id)
|
||||
if run is None or not run.excel_file_data:
|
||||
raise NotFoundError("检核结果 Excel 不存在", code="VOUCHER_CHECK.EXCEL_NOT_FOUND")
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or "voucher_check.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
|
||||
|
||||
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
|
||||
def workspace_voucher_notify_config_get():
|
||||
"""
|
||||
|
||||
@@ -3,11 +3,11 @@ backend/app/models/equipment_acceptance.py
|
||||
|
||||
用途:设备验收预警的本地同步快照和可改配置。
|
||||
依赖:models.base.Base、users。
|
||||
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
||||
逻辑:同步服务按来源 oa_system 加流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
|
||||
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
|
||||
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
|
||||
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
|
||||
不保存流程编号、第二合同编号、验收日期和 isremark。
|
||||
保存流程编号和标题。不保存第二合同编号、验收日期和 isremark。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,18 +22,34 @@ from app.models.base import Base
|
||||
|
||||
|
||||
class EquipmentAcceptanceOrder(Base):
|
||||
"""一张验收单的最近一次同步结果。流程实例 request_id 唯一。"""
|
||||
"""一张验收单的最近一次同步结果。同一来源里 request_id 唯一。"""
|
||||
|
||||
__tablename__ = "equipment_acceptance_orders"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("request_id", name="uq_equipment_acceptance_orders_request_id"),
|
||||
UniqueConstraint("oa_system", "request_id", name="uq_equipment_acceptance_orders_oa_request"),
|
||||
Index("ix_equipment_acceptance_orders_status", "monitor_status"),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
oa_system: Mapped[str] = mapped_column(String(8), nullable=False, default="e10")
|
||||
acceptance_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
purchase_order_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
contract_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
flow_no: Mapped[Optional[str]] = mapped_column(
|
||||
String(1000),
|
||||
nullable=True,
|
||||
comment="流程编号。E10 取 wfc_requestbase.requestmark,E8 取 formtable_main_324.lcbh。",
|
||||
)
|
||||
request_title: Mapped[Optional[str]] = mapped_column(
|
||||
String(1000),
|
||||
nullable=True,
|
||||
comment="流程标题。两边都取流程表 requestname。E10 这一列是流程默认标题。",
|
||||
)
|
||||
request_created_at: Mapped[Optional[datetime]] = mapped_column(
|
||||
DateTime,
|
||||
nullable=True,
|
||||
comment="流程创建时间。E10 取 wfc_requestbase.createdatetime。E8 取 createdate 加 createtime。不用 E10 的 create_time。",
|
||||
)
|
||||
timer_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
dwell_days: Mapped[Optional[int]] = mapped_column(nullable=True)
|
||||
can_accept: Mapped[Optional[int]] = mapped_column(
|
||||
|
||||
@@ -69,11 +69,9 @@ class FreightRpaProfile(Base):
|
||||
login_config_json: Mapped[dict[str, Any]] = mapped_column(
|
||||
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
|
||||
)
|
||||
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页;
|
||||
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅
|
||||
# enabled / entry_url / file_input_selector / submit_mode / submit_selector /
|
||||
# result_mode / result_selector / success_texts / timeout_seconds。
|
||||
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
|
||||
# 连接级“发货 Excel 自动上传”开关。只保存 {enabled}。
|
||||
# 上传页、文件控件、提交和成功判断在连接器代码里,由 login_url 的主机拼出入口。
|
||||
# 该配置变更不递增 config_version(见 admin 服务)。
|
||||
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
|
||||
@@ -7,6 +7,7 @@ services/admin/freight_rpa_source_admin_service.py
|
||||
freight_rpa_form_utils、credential_crypto、parsing_profile、upload_config_validation、
|
||||
onhand_source_repository.validate_source_profile、audit_service。
|
||||
逻辑:admin_freight_rpa 蓝图的 rpa-profiles / sources / bind-parsing / activate 委托本服务;
|
||||
Profile 列表与保存回执返回用户名明文,密码与密文不返回;
|
||||
在手快照/路由规则/外部映射仍见 shipping_onhand_admin_service。
|
||||
"""
|
||||
|
||||
@@ -15,7 +16,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FreightRpaOnhandExternalMapping,
|
||||
@@ -38,7 +39,7 @@ from app.services.admin.freight_rpa_form_utils import (
|
||||
validate_report_path as _validate_report_path,
|
||||
)
|
||||
from app.services.freight_rpa import parsing_profile as onhand_parsing_profile
|
||||
from app.services.freight_rpa.common.credential_crypto import encrypt_credential
|
||||
from app.services.freight_rpa.common.credential_crypto import decrypt_credential, encrypt_credential
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.onhand_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.upload_config_validation import validate_upload_config
|
||||
@@ -77,27 +78,50 @@ def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
|
||||
|
||||
|
||||
|
||||
def _stored_username(profile: FreightRpaProfile) -> str | None:
|
||||
"""解密已保存的用户名,供管理端辨认账号。
|
||||
|
||||
核心逻辑:用户名是账号标识,库内仍只存密文;解密失败时返回 None,避免坏密文拖垮连接列表。
|
||||
密码不走本函数。
|
||||
|
||||
Args:
|
||||
profile: 已持久化的货代登录连接。
|
||||
|
||||
Returns:
|
||||
str | None: 用户名明文;未配置或无法解密时为 None。
|
||||
"""
|
||||
if not profile.username_ciphertext:
|
||||
return None
|
||||
try:
|
||||
return decrypt_credential(profile.username_ciphertext)
|
||||
except (ServiceUnavailableError, ValidationError):
|
||||
return None
|
||||
|
||||
|
||||
def _profile_payload(profile: FreightRpaProfile) -> dict[str, Any]:
|
||||
"""序列化系统连接。用户名明文回传,密码与密文不出现在响应中。"""
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'connector_type': profile.connector_type, 'login_url': profile.login_url,
|
||||
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
|
||||
'upload_config_json': profile.upload_config_json,
|
||||
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
|
||||
'config_version': profile.config_version,
|
||||
'username': _stored_username(profile),
|
||||
'username_masked': _mask(profile.username_ciphertext),
|
||||
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
|
||||
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _mask(ciphertext: str | None) -> str | None:
|
||||
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
|
||||
"""密码等不可回显凭据只报告是否已配置。"""
|
||||
return 'configured' if ciphertext else None
|
||||
|
||||
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出 Profile 元数据,不返回可恢复的凭据。"""
|
||||
"""列出 Profile。响应含用户名明文,不含密码与密文。"""
|
||||
return [_profile_payload(item) for item in FreightRpaProfile.query.order_by(FreightRpaProfile.profile_code).all()]
|
||||
|
||||
|
||||
@@ -113,7 +137,11 @@ def delete_profile(profile_id: int) -> None:
|
||||
|
||||
|
||||
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
|
||||
"""创建或更新货代登录连接。
|
||||
|
||||
核心逻辑:用户名留空,或与已存明文相同,不重写用户名密文;密码留空则保留既有密码密文。
|
||||
只有用户名实际变更或提交了新密码时才刷新 credential_updated_at。
|
||||
"""
|
||||
profile = db.session.get(FreightRpaProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
@@ -138,11 +166,14 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
|
||||
)
|
||||
username = _text(data, 'username')
|
||||
password = _text(data, 'password')
|
||||
if username is not None:
|
||||
# [STEP] 管理端回显的用户名会随保存再次提交;与库内明文相同则不轮换 Fernet 密文。
|
||||
username_changed = False
|
||||
if username is not None and _stored_username(profile) != username:
|
||||
profile.username_ciphertext = encrypt_credential(username)
|
||||
username_changed = True
|
||||
if password is not None:
|
||||
profile.password_ciphertext = encrypt_credential(password)
|
||||
if username is not None or password is not None:
|
||||
if username_changed or password is not None:
|
||||
profile.credential_updated_at = datetime.utcnow()
|
||||
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
|
||||
if 'upload_config_json' in data:
|
||||
|
||||
@@ -3,7 +3,7 @@ services/contract_payment/alert_service.py
|
||||
|
||||
用途:按付款阶段生成待发送预警,在每周五按收件人汇总发送企业微信和 Excel 明细,并提供工作台待发送摘要。
|
||||
依赖:合同付款模型、用户目录、openpyxl、企业微信通知服务、OA 上级矩阵、排程时区工具。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款可手动标为已付,并关闭该节点尚未发送的预警。
|
||||
逻辑:每日任务只写入 pending 审计;周汇总任务锁定本周收件人批次,发送一条汇总卡片和一份逐笔 Excel;发送失败时把原因写入批次审计。摘要接口与周五发送使用同一 pending 口径。预付款、出货款、验收款、质保款都可手动标为已付,并关闭该节点尚未发送的预警。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
||||
第一轮按台账申请人 `real_name` 唯一匹配系统用户;第二、三轮查 OA HrmResource + Matrixtable_3,用 zz/jfl 作为企微 userid,不向第一轮兜底。
|
||||
"""
|
||||
|
||||
@@ -40,6 +40,7 @@ from app.services.contract_payment.erp_payment_service import (
|
||||
normalize_purchase_order_no,
|
||||
resolve_paid_node_dates,
|
||||
)
|
||||
from app.services.contract_payment.ledger_focus import stage_has_nothing_to_pay
|
||||
from app.services.contract_payment.supervisor_oa_service import SupervisorMatrixCache
|
||||
from app.services.schedule.timezone_util import compute_next_run_at
|
||||
|
||||
@@ -52,6 +53,7 @@ class _AlertRecipient:
|
||||
oa_wecom_userid: str | None = None
|
||||
|
||||
|
||||
_ERP_PAID_STAGE_TYPES = {"prepayment", "shipment", "acceptance", "warranty"}
|
||||
_ALERT_RULES: dict[str, tuple[tuple[int, str], ...]] = {
|
||||
"prepayment": ((7, "owner"), (14, "department_head"), (21, "procurement_leader")),
|
||||
"shipment": ((-7, "owner"), (0, "department_head"), (14, "procurement_leader")),
|
||||
@@ -65,7 +67,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
|
||||
AI 触发时机:每日排程或管理员手动执行扫描时调用。
|
||||
核心逻辑:按阶段计算已到期的三轮提醒,按节点、轮次、收件人幂等;第二、三轮收件人来自 OA 部门矩阵;
|
||||
ERP `apa_file` 的合格付款记录只停止尚未发送的后续轮次。
|
||||
ERP `apa_file` 的合格付款记录按金额匹配四个阶段,并停止已付款阶段尚未发送的后续轮次。金额和比例都为 0 的阶段关闭未发送预警,不再新建。
|
||||
Args:
|
||||
today: 业务日期,未传时使用服务器日期。
|
||||
send: 保留旧调用兼容参数;最新方案下始终不发送消息。
|
||||
@@ -85,14 +87,20 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
payable_orders = [
|
||||
(normalize_purchase_order_no(contract.purchase_order_no), contract.company_name)
|
||||
for node, contract in rows
|
||||
if node.node_type in {"prepayment", "shipment"} and normalize_purchase_order_no(contract.purchase_order_no)
|
||||
if node.node_type in _ERP_PAID_STAGE_TYPES
|
||||
and normalize_purchase_order_no(contract.purchase_order_no)
|
||||
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
|
||||
]
|
||||
paid_records = fetch_paid_records(payable_orders)
|
||||
paid_node_dates: dict[int, str | None] = {}
|
||||
nodes_by_ledger: dict[tuple[str, str], list[ContractPaymentNode]] = defaultdict(list)
|
||||
for node, contract in rows:
|
||||
purchase_order_no = normalize_purchase_order_no(contract.purchase_order_no)
|
||||
if node.node_type in {"prepayment", "shipment"} and purchase_order_no:
|
||||
if (
|
||||
node.node_type in _ERP_PAID_STAGE_TYPES
|
||||
and purchase_order_no
|
||||
and not stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount)
|
||||
):
|
||||
nodes_by_ledger[(erp_schema_for_company(contract.company_name), purchase_order_no)].append(node)
|
||||
for ledger_key, payment_nodes in nodes_by_ledger.items():
|
||||
paid_node_dates.update(resolve_paid_node_dates(
|
||||
@@ -100,6 +108,11 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
paid_records.get(ledger_key, []),
|
||||
))
|
||||
for node, contract in rows:
|
||||
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
|
||||
# 金额和比例都为 0 时没有应付金额,关掉尚未发送的预警,不再按日期升级。
|
||||
resolved += _resolve_pending_alerts(node_id=node.id, reason="nothing_to_pay")
|
||||
skipped += 1
|
||||
continue
|
||||
anchor = _anchor_date(contract=contract, node=node)
|
||||
if anchor is None:
|
||||
skipped += 1
|
||||
@@ -113,7 +126,7 @@ def generate_alerts(*, today: date | None = None, send: bool = False) -> dict[st
|
||||
scheduled_date = anchor + timedelta(days=offset_days)
|
||||
if today < scheduled_date:
|
||||
continue
|
||||
# ERP 合格付款先按金额匹配阶段;同金额时预付款优先于出货款。
|
||||
# ERP 合格付款按金额匹配四个阶段;同金额时按预付款、出货款、验收款、质保款的顺序占用。
|
||||
# 节点被匹配为已付款后,保留历史 sent,仅关闭尚未发送轮次。
|
||||
if erp_paid:
|
||||
resolved += _resolve_pending_alerts(node_id=node.id)
|
||||
@@ -160,10 +173,10 @@ def _resolve_pending_alerts(*, node_id: int, reason: str = "erp_paid") -> int:
|
||||
|
||||
def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, operator_id: int | None = None) -> ContractPaymentContract:
|
||||
"""
|
||||
把一个未付的预付款或出货款手动标为已付。
|
||||
把一个未付阶段手动标为已付。
|
||||
|
||||
核心逻辑:只改这一阶段。写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
||||
验收款、质保款和已经付款的阶段不能标记。
|
||||
核心逻辑:预付款、出货款、验收款、质保款都可以标记。只改这一阶段,写入付款日期和手动来源,并关闭该节点尚未发送的预警;已发送记录保留。
|
||||
金额和比例都为 0、已经付款、或不是进行中的阶段不能标记。
|
||||
|
||||
Args:
|
||||
contract_id: 合同台账主键。
|
||||
@@ -186,8 +199,10 @@ def mark_payment_node_paid(contract_id: int, node_id: int, payload: dict, *, ope
|
||||
node = db.session.get(ContractPaymentNode, node_id)
|
||||
if node is None or node.contract_id != contract.id:
|
||||
raise NotFoundError("付款节点不存在")
|
||||
if node.node_type not in {"prepayment", "shipment"}:
|
||||
raise ValidationError("只有预付款和出货款可以手动标为已付")
|
||||
if node.node_type not in _ERP_PAID_STAGE_TYPES:
|
||||
raise ValidationError("该阶段不能标为已付")
|
||||
if stage_has_nothing_to_pay(status=node.status, percentage=node.percentage, amount=node.amount):
|
||||
raise ValidationError("该阶段没有应付金额,不能标为已付")
|
||||
if node.status == "paid":
|
||||
raise ValidationError("该阶段已是已付")
|
||||
if node.status != "active":
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/erp_payment_service.py
|
||||
|
||||
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款和出货款的付款完成事实来源。
|
||||
用途:从 ERP Oracle `apa_file` 读取采购单付款记录,作为预付款、出货款、验收款和质保款的付款完成事实来源。
|
||||
依赖:oracledb、Text2SQLService 的 Oracle 客户端初始化能力及 Flask 配置。
|
||||
逻辑:按 OA「公司」选择账套后只读查询 `{账套}.apa_file`;只接受 `apa00='15'`(厂商预付款作业)且 `apa41='Y'`、`apa63=1` 的记录,并按采购单收集 `apa34f` 供明细和阶段匹配使用。
|
||||
"""
|
||||
@@ -17,7 +17,7 @@ from typing import Iterable
|
||||
from flask import current_app
|
||||
|
||||
|
||||
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2}
|
||||
_PAYMENT_STAGE_ORDER = {"prepayment": 1, "shipment": 2, "acceptance": 3, "warranty": 4}
|
||||
# OA 合同申请单「公司」到 ERP 账套。未列出的公司默认 HXJM。标识符只允许来自这个白名单。
|
||||
_SCHEMA_BY_COMPANY = {
|
||||
"无锡和宏智散热科技有限公司": "WZHHZ",
|
||||
@@ -100,7 +100,7 @@ def fetch_paid_records(orders: Iterable[tuple[str, str | None]]) -> dict[tuple[s
|
||||
"""
|
||||
按公司对应的 ERP 账套查询采购单已完成付款记录(含付款日期)。
|
||||
|
||||
AI 触发时机:合同付款预警每日扫描前,需要判断预付款/出货款是否已经完成付款。
|
||||
AI 触发时机:合同付款预警每日扫描前,需要判断预付款、出货款、验收款、质保款是否已经完成付款。
|
||||
核心逻辑:公司映射到 HXJM / WZHHZ / HTT 后,分别查询该账套的 `apa_file`;
|
||||
先按 `apa00='15'` 限定为「厂商预付款作业」,再过滤 `apa41='Y'` 和 `apa63=1`,按 `apaud03` 收集 `apa34f` 与 `apa02`。
|
||||
某一账套查询失败只影响该账套,其它账套继续。
|
||||
@@ -234,14 +234,13 @@ def resolve_paid_node_dates(
|
||||
paid_rows: Iterable[ErpPaidRow],
|
||||
) -> dict[int, str | None]:
|
||||
"""
|
||||
将同一采购单的 ERP 付款记录匹配到预付款、出货款节点,并返回节点 ID 到付款日期的映射。
|
||||
将同一采购单的 ERP 付款记录匹配到预付款、出货款、验收款、质保款节点,并返回节点 ID 到付款日期的映射。
|
||||
|
||||
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按金额与节点匹配;
|
||||
金额相同则按预付款、出货款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
|
||||
「预付款+出货款」金额之和与该笔付款一致,说明预付款与出货款在同一笔请款中一并请款,
|
||||
则把两者同时标记为已付款,并携带该笔付款日期。
|
||||
金额相同则按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;若单节点无匹配但
|
||||
若干阶段金额之和与该笔付款一致,则把这些阶段同时标记为已付款,并携带该笔付款日期。
|
||||
Args:
|
||||
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
||||
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
|
||||
paid_rows: 该采购单的合格 ERP 付款记录。
|
||||
Returns:
|
||||
已匹配节点的付款日期映射(节点 ID -> 付款日期,日期可能为空)。
|
||||
@@ -268,14 +267,13 @@ def resolve_paid_node_ids(
|
||||
paid_amounts: Iterable[Decimal],
|
||||
) -> set[int]:
|
||||
"""
|
||||
将同一采购单的 ERP 付款金额匹配到预付款、出货款节点。
|
||||
将同一采购单的 ERP 付款金额匹配到预付款、出货款、验收款、质保款节点。
|
||||
|
||||
核心逻辑:`apa00='15'`、`apa41='Y'` 且 `apa63=1` 的每笔 ERP 付款按 `apa34f` 与节点金额匹配;
|
||||
金额不同则自然对应相应节点,金额相同时按预付款、出货款的业务顺序匹配最前面仍未付款的节点;
|
||||
若单节点无匹配但「预付款+出货款」金额之和与该笔付款一致,则一并标记两者为已付款
|
||||
(预付款、出货款在同一笔请款中一并请款的场景)。
|
||||
金额不同则自然对应相应节点,金额相同时按预付款、出货款、验收款、质保款的业务顺序匹配最前面仍未付款的节点;
|
||||
若单节点无匹配但若干阶段金额之和与该笔付款一致,则一并标记这些阶段为已付款。
|
||||
Args:
|
||||
nodes: 同一采购单的 `(node_id, node_type, amount)` 节点;只传预付款、出货款的 active 节点。
|
||||
nodes: 同一采购单仍需付款的 `(node_id, node_type, amount)` 节点;金额为 0 的阶段不要传入。
|
||||
paid_amounts: 该采购单的合格 ERP 每笔付款金额。
|
||||
Returns:
|
||||
已付款节点 ID 集合。
|
||||
|
||||
@@ -4,11 +4,13 @@ backend/app/services/contract_payment/ledger_focus.py
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、未到期(7日外)、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;即将到期/逾期/未到期互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
|
||||
金额和比例都为 0 的阶段不参与逾期、即将到期和本月应付。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterable
|
||||
from zoneinfo import ZoneInfo
|
||||
@@ -58,6 +60,37 @@ def node_due_reference(due_date: date | None, anchor_date: date | None) -> date
|
||||
return due_date or anchor_date
|
||||
|
||||
|
||||
def stage_has_nothing_to_pay(*, status: str | None, percentage: object, amount: object) -> bool:
|
||||
"""
|
||||
判断付款阶段是否没有应付金额。
|
||||
|
||||
核心逻辑:无此阶段,或比例与金额都是 0(空值按 0)。已付阶段不按 0 处理。
|
||||
与前台 isNothingToPay 一致,避免 0 元验收款、质保款把合同标成已逾期。
|
||||
Args:
|
||||
status: 节点状态。
|
||||
percentage: 付款比例,可为 Decimal、数字或字符串。
|
||||
amount: 应付金额,空值视为 0。
|
||||
Returns:
|
||||
无需付款时为 True。
|
||||
"""
|
||||
normalized = str(status or "").strip().lower()
|
||||
if normalized == "not_applicable":
|
||||
return True
|
||||
if normalized == "paid":
|
||||
return False
|
||||
return _is_zero(percentage) and _is_zero(amount)
|
||||
|
||||
|
||||
def _is_zero(value: object) -> bool:
|
||||
"""空值和 0 都视为没有金额或比例;无法解析的值不当成 0。"""
|
||||
if value is None or value == "":
|
||||
return True
|
||||
try:
|
||||
return Decimal(str(value)) == 0
|
||||
except (InvalidOperation, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def classify_ledger_status(
|
||||
*,
|
||||
contract_status: str | None,
|
||||
@@ -69,11 +102,11 @@ def classify_ledger_status(
|
||||
按合同聚合出台账状态,与列表「状态」列一致。
|
||||
|
||||
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
|
||||
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
金额和比例都为 0 的阶段不参与判断。其余进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
Args:
|
||||
contract_status: 合同主状态。
|
||||
parse_status: 解析状态。
|
||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
|
||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at / percentage / amount。
|
||||
today: 业务日。
|
||||
Returns:
|
||||
overdue / due / active / completed / needs_completion。
|
||||
@@ -83,7 +116,14 @@ def classify_ledger_status(
|
||||
return "needs_completion"
|
||||
if not node_list:
|
||||
return "needs_completion"
|
||||
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
|
||||
active = [
|
||||
node for node in node_list
|
||||
if str(node.get("status") or "").strip().lower() == "active" and not stage_has_nothing_to_pay(
|
||||
status=node.get("status"),
|
||||
percentage=node.get("percentage"),
|
||||
amount=node.get("amount"),
|
||||
)
|
||||
]
|
||||
if not active:
|
||||
has_paid = any(
|
||||
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
|
||||
@@ -106,7 +146,7 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
|
||||
"""
|
||||
合同是否有未付节点的到期日落在本自然月。
|
||||
|
||||
核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||
核心逻辑:只看 status=active 且仍有应付金额的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||
Args:
|
||||
nodes: 轻量节点 dict。
|
||||
today: 业务日,用于确定自然月。
|
||||
@@ -118,6 +158,8 @@ def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> b
|
||||
for node in nodes:
|
||||
if str(node.get("status") or "").strip().lower() != "active":
|
||||
continue
|
||||
if stage_has_nothing_to_pay(status=node.get("status"), percentage=node.get("percentage"), amount=node.get("amount")):
|
||||
continue
|
||||
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
|
||||
if ref and month_start <= ref < month_end:
|
||||
return True
|
||||
@@ -131,6 +173,8 @@ def _node_payload(node: ContractPaymentNode) -> dict[str, Any]:
|
||||
"due_date": node.due_date,
|
||||
"anchor_date": node.anchor_date,
|
||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||
"percentage": node.percentage,
|
||||
"amount": node.amount,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -136,6 +136,47 @@ def resolve_account(
|
||||
)
|
||||
|
||||
|
||||
def resolve_direct_wecom(
|
||||
*,
|
||||
slot: str,
|
||||
label: str,
|
||||
name: str | None,
|
||||
wecom_userid: str | None,
|
||||
user: Any = None,
|
||||
oa_employee_id: int | None = None,
|
||||
missing_error: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
把已经是企业微信 userid 的人员收成收件人。
|
||||
|
||||
核心逻辑:E8 矩阵的 zz、jfl 本身就是企微 userid,不再用工号对用户。
|
||||
系统里能对上这个 userid 时带上用户主键。对不上仍按该 userid 发送。
|
||||
Args:
|
||||
slot: to 或 cc。
|
||||
label: 直接主管或经副理。
|
||||
name: 展示姓名。
|
||||
wecom_userid: 企业微信 userid。
|
||||
user: 已按 wecom_userid 找到的系统用户。可空。
|
||||
oa_employee_id: HrmResource.id。
|
||||
missing_error: 没有 userid 时的失败原因。
|
||||
Returns:
|
||||
一名收件人。
|
||||
"""
|
||||
wecom = str(wecom_userid or "").strip()
|
||||
if not wecom:
|
||||
return make_person(slot=slot, label=label, name=name, oa_employee_id=oa_employee_id, error=missing_error)
|
||||
display = _user_name(user) or name
|
||||
bound = str(getattr(user, "wecom_userid", None) or "").strip() if user is not None else ""
|
||||
return make_person(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=display,
|
||||
user_id=getattr(user, "id", None) if user is not None else None,
|
||||
wecom_userid=bound or wecom,
|
||||
oa_employee_id=oa_employee_id,
|
||||
)
|
||||
|
||||
|
||||
def resolve_configured_user(*, slot: str, label: str, user: Any, missing_error: str) -> dict[str, Any]:
|
||||
"""
|
||||
把预警配置里的固定岗位收成收件人。
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/equipment_acceptance/alert_service.py
|
||||
|
||||
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
|
||||
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||
依赖:同步服务、E10 人员目录、E8 人员矩阵、alert_plan、alert_notice、发送记录模型、企微通知。
|
||||
逻辑:扫描先同步 E10 和 E8,再按停留天数跨档。第 1 档主送使用部门担当,不按当前未办人。
|
||||
第 4 轮关闭时不生成、也不发送总经理那一轮。
|
||||
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
|
||||
"""
|
||||
|
||||
@@ -35,6 +36,7 @@ from app.services.equipment_acceptance.alert_plan import (
|
||||
make_person,
|
||||
resolve_account,
|
||||
resolve_configured_user,
|
||||
resolve_direct_wecom,
|
||||
)
|
||||
from app.services.equipment_acceptance.config_service import is_round_4_enabled, reminder_days
|
||||
from app.services.equipment_acceptance.snapshot_rules import WATCHING
|
||||
@@ -47,9 +49,9 @@ _UNSENT = ("pending", "failed")
|
||||
|
||||
def generate_alerts() -> dict[str, Any]:
|
||||
"""
|
||||
同步 E10 后生成或更新待发送记录。
|
||||
同步两个来源后生成或更新待发送记录。
|
||||
|
||||
核心逻辑:先拉最新节点和停表状态,再按当前处理人解析收件人。本函数不发企业微信。
|
||||
核心逻辑:先拉最新快照,再按使用部门担当解析收件人。本函数不发企业微信。
|
||||
Returns:
|
||||
sync 摘要,以及 created、updated、cancelled 条数。
|
||||
"""
|
||||
@@ -78,9 +80,9 @@ def refresh_pending_alerts(
|
||||
created、updated、cancelled。
|
||||
"""
|
||||
orders = db.session.query(EquipmentAcceptanceOrder).all()
|
||||
operators = _operators_by_order([order.id for order in orders])
|
||||
people, deputies = directory if directory is not None else _load_directory(orders, operators)
|
||||
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
|
||||
e10_people, e10_deputies, e8_people, e8_matrix, e8_ok = _directories(orders, directory)
|
||||
users_by_job = _users_by_job(_job_numbers(orders, e10_people, e10_deputies, e8_people))
|
||||
users_by_wecom = _users_by_wecom(_wecom_ids(e8_matrix))
|
||||
roles = _configured_users()
|
||||
thresholds = reminder_days()
|
||||
max_tier = 4 if is_round_4_enabled() else 3
|
||||
@@ -96,12 +98,16 @@ def refresh_pending_alerts(
|
||||
if order.monitor_status != WATCHING:
|
||||
cancelled += cancel_unsent(order.id)
|
||||
continue
|
||||
if (order.oa_system or "e10") == "e8" and not e8_ok:
|
||||
continue
|
||||
for draft in _drafts(
|
||||
order,
|
||||
operators.get(order.id, []),
|
||||
people,
|
||||
deputies,
|
||||
e10_people,
|
||||
e10_deputies,
|
||||
e8_people,
|
||||
e8_matrix,
|
||||
users_by_job,
|
||||
users_by_wecom,
|
||||
roles,
|
||||
thresholds,
|
||||
max_tier=max_tier,
|
||||
@@ -282,82 +288,31 @@ def send_pending_alerts() -> dict[str, Any]:
|
||||
|
||||
def _drafts(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
operators: list[EquipmentAcceptanceOperator],
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
e10_people: dict[int, dict[str, Any]],
|
||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||
e8_people: dict[int, dict[str, Any]],
|
||||
e8_matrix: dict[str, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
users_by_wecom: dict[str, User],
|
||||
roles: dict[str, User | None],
|
||||
thresholds: tuple[int, int, int, int],
|
||||
*,
|
||||
max_tier: int = 4,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
||||
"""按使用部门担当展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
|
||||
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
|
||||
if not due:
|
||||
return []
|
||||
handlers: list[dict[str, Any]] = []
|
||||
supervisors: list[dict[str, Any]] = []
|
||||
deputy_people: list[dict[str, Any]] = []
|
||||
if not operators:
|
||||
handlers.append(make_person(slot="to", label="当前处理人", error="没有当前处理人"))
|
||||
deputy_people.append(make_person(slot="to", label="经副理", error="没有当前处理人,查不到经副理"))
|
||||
for operator in operators:
|
||||
fact = people.get(operator.user_id) or {}
|
||||
name = fact.get("name") or operator.handler_name
|
||||
job_num = fact.get("job_num") or operator.handler_job_num
|
||||
shown = name or "处理人"
|
||||
handlers.append(resolve_account(
|
||||
slot="to",
|
||||
label="当前处理人",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=operator.user_id,
|
||||
))
|
||||
superior_id = fact.get("superior_id")
|
||||
if superior_id is None:
|
||||
supervisors.append(make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管"))
|
||||
else:
|
||||
supervisors.append(resolve_account(
|
||||
slot="cc",
|
||||
label="直接主管",
|
||||
name=fact.get("superior_name"),
|
||||
job_num=fact.get("superior_job_num"),
|
||||
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
|
||||
missing_job_error=f"{shown}的直接主管没有工号",
|
||||
oa_employee_id=superior_id,
|
||||
))
|
||||
found = deputies.get(str(fact.get("department_id") or ""), [])
|
||||
if not found:
|
||||
deputy_people.append(make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理"))
|
||||
else:
|
||||
for item in found:
|
||||
deputy_people.append(resolve_account(
|
||||
slot="to",
|
||||
label="经副理",
|
||||
name=item.get("name"),
|
||||
job_num=item.get("job_num"),
|
||||
user=users_by_job.get(str(item.get("job_num") or "")),
|
||||
missing_job_error=f"{shown}的经副理没有工号",
|
||||
oa_employee_id=item.get("oa_id"),
|
||||
))
|
||||
applicant_fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||
applicant = resolve_account(
|
||||
slot="cc",
|
||||
label="采购担当",
|
||||
name=(applicant_fact or {}).get("name") or order.applicant_name,
|
||||
job_num=(applicant_fact or {}).get("job_num") or order.applicant_job_num,
|
||||
user=users_by_job.get(str(((applicant_fact or {}).get("job_num") or order.applicant_job_num) or "")),
|
||||
missing_job_error="没有申请人工号",
|
||||
oa_employee_id=order.applicant_oa_id,
|
||||
owner, supervisors, deputy_people = _owner_seats(
|
||||
order, e10_people, e10_deputies, e8_people, e8_matrix, users_by_job, users_by_wecom
|
||||
)
|
||||
applicant = _applicant(order, e10_people if (order.oa_system or "e10") != "e8" else e8_people, users_by_job)
|
||||
drafts: list[dict[str, Any]] = []
|
||||
if 1 in due:
|
||||
drafts.append(assemble_tier(
|
||||
tier=1,
|
||||
threshold_days=thresholds[0],
|
||||
to_people=handlers,
|
||||
to_people=[owner],
|
||||
cc_people=[*supervisors, applicant],
|
||||
))
|
||||
if 2 in due:
|
||||
@@ -390,6 +345,159 @@ def _drafts(
|
||||
return drafts
|
||||
|
||||
|
||||
def _owner_seats(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
e10_people: dict[int, dict[str, Any]],
|
||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||
e8_people: dict[int, dict[str, Any]],
|
||||
e8_matrix: dict[str, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
users_by_wecom: dict[str, User],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""第 1 档主送和其上级。E8 的上级来自部门矩阵,E10 来自 employee 和审批矩阵。"""
|
||||
if (order.oa_system or "e10") == "e8":
|
||||
return _e8_owner_seats(order, e8_people, e8_matrix, users_by_job, users_by_wecom)
|
||||
return _e10_owner_seats(order, e10_people, e10_deputies, users_by_job)
|
||||
|
||||
|
||||
def _e10_owner_seats(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
users_by_job: dict[str, User],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""E10 只取 sybmdd 这一名使用部门担当,不展开当前节点上的其他人。"""
|
||||
if not order.owner_oa_id:
|
||||
return (
|
||||
make_person(slot="to", label="使用部门担当", error="没有使用部门担当"),
|
||||
[make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")],
|
||||
[make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")],
|
||||
)
|
||||
fact = people.get(order.owner_oa_id) or {}
|
||||
name = fact.get("name") or order.owner_name
|
||||
job_num = fact.get("job_num") or order.owner_job_num
|
||||
shown = name or "使用部门担当"
|
||||
owner = resolve_account(
|
||||
slot="to",
|
||||
label="使用部门担当",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=order.owner_oa_id,
|
||||
)
|
||||
superior_id = fact.get("superior_id")
|
||||
if superior_id is None:
|
||||
supervisors = [make_person(slot="cc", label="直接主管", name=name, error=f"{shown}没有直接主管")]
|
||||
else:
|
||||
supervisors = [resolve_account(
|
||||
slot="cc",
|
||||
label="直接主管",
|
||||
name=fact.get("superior_name"),
|
||||
job_num=fact.get("superior_job_num"),
|
||||
user=users_by_job.get(str(fact.get("superior_job_num") or "")),
|
||||
missing_job_error=f"{shown}的直接主管没有工号",
|
||||
oa_employee_id=superior_id,
|
||||
)]
|
||||
found = deputies.get(str(fact.get("department_id") or ""), [])
|
||||
if not found:
|
||||
deputy_people = [make_person(slot="to", label="经副理", name=name, error=f"{shown}没有经副理")]
|
||||
else:
|
||||
deputy_people = [
|
||||
resolve_account(
|
||||
slot="to",
|
||||
label="经副理",
|
||||
name=item.get("name"),
|
||||
job_num=item.get("job_num"),
|
||||
user=users_by_job.get(str(item.get("job_num") or "")),
|
||||
missing_job_error=f"{shown}的经副理没有工号",
|
||||
oa_employee_id=item.get("oa_id"),
|
||||
)
|
||||
for item in found
|
||||
]
|
||||
return owner, supervisors, deputy_people
|
||||
|
||||
|
||||
def _e8_owner_seats(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
people: dict[int, dict[str, Any]],
|
||||
matrix: dict[str, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
users_by_wecom: dict[str, User],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""E8 的直接主管是矩阵 zz,经副理是 jfl。不是一行就不发这两个席位。"""
|
||||
if not order.owner_oa_id:
|
||||
return (
|
||||
make_person(slot="to", label="使用部门担当", error="没有使用部门担当"),
|
||||
[make_person(slot="cc", label="直接主管", error="没有使用部门担当,查不到直接主管")],
|
||||
[make_person(slot="to", label="经副理", error="没有使用部门担当,查不到经副理")],
|
||||
)
|
||||
fact = people.get(order.owner_oa_id) or {}
|
||||
name = fact.get("name") or order.owner_name
|
||||
job_num = fact.get("job_num") or order.owner_job_num
|
||||
shown = name or "使用部门担当"
|
||||
owner = resolve_account(
|
||||
slot="to",
|
||||
label="使用部门担当",
|
||||
name=name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error=f"{shown}没有工号",
|
||||
oa_employee_id=order.owner_oa_id,
|
||||
)
|
||||
seat = matrix.get(str(fact.get("department_id") or ""))
|
||||
if not seat or not seat.get("ok"):
|
||||
return (
|
||||
owner,
|
||||
[make_person(slot="cc", label="直接主管", name=name, error=f"{shown}的部门矩阵不是一行")],
|
||||
[make_person(slot="to", label="经副理", name=name, error=f"{shown}的部门矩阵不是一行")],
|
||||
)
|
||||
return owner, [_matrix_seat(seat.get("zz"), "cc", "直接主管", shown, users_by_wecom)], [
|
||||
_matrix_seat(seat.get("jfl"), "to", "经副理", shown, users_by_wecom)
|
||||
]
|
||||
|
||||
|
||||
def _matrix_seat(
|
||||
seat: dict[str, Any] | None,
|
||||
slot: str,
|
||||
label: str,
|
||||
owner_name: str,
|
||||
users_by_wecom: dict[str, User],
|
||||
) -> dict[str, Any]:
|
||||
"""矩阵人员按企微 userid 发送。空席位记失败。"""
|
||||
if not seat:
|
||||
return make_person(slot=slot, label=label, name=owner_name, error=f"{owner_name}没有{label}")
|
||||
wecom = str(seat.get("wecom_userid") or "")
|
||||
return resolve_direct_wecom(
|
||||
slot=slot,
|
||||
label=label,
|
||||
name=seat.get("name"),
|
||||
wecom_userid=wecom,
|
||||
user=users_by_wecom.get(wecom),
|
||||
oa_employee_id=seat.get("oa_id"),
|
||||
missing_error=f"{owner_name}没有{label}",
|
||||
)
|
||||
|
||||
|
||||
def _applicant(
|
||||
order: EquipmentAcceptanceOrder,
|
||||
people: dict[int, dict[str, Any]],
|
||||
users_by_job: dict[str, User],
|
||||
) -> dict[str, Any]:
|
||||
"""采购担当是申请人。E8 用工号 workcode,E10 用工号 JOB_NUM,都对系统用户。"""
|
||||
fact = people.get(order.applicant_oa_id) if order.applicant_oa_id else None
|
||||
job_num = (fact or {}).get("job_num") or order.applicant_job_num
|
||||
return resolve_account(
|
||||
slot="cc",
|
||||
label="采购担当",
|
||||
name=(fact or {}).get("name") or order.applicant_name,
|
||||
job_num=job_num,
|
||||
user=users_by_job.get(str(job_num or "")),
|
||||
missing_job_error="没有申请人工号",
|
||||
oa_employee_id=order.applicant_oa_id,
|
||||
)
|
||||
|
||||
|
||||
def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceOrder, draft: dict[str, Any]) -> None:
|
||||
"""把草稿写进未发送的记录。不改创建时间,也不填发送时间。"""
|
||||
row.acceptance_no = order.acceptance_no
|
||||
@@ -402,51 +510,103 @@ def _apply_draft(row: EquipmentAcceptanceSendRecord, order: EquipmentAcceptanceO
|
||||
row.error_message = draft["error_message"]
|
||||
|
||||
|
||||
def _load_directory(
|
||||
def _directories(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
directory: tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]] | None,
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]], dict[int, dict[str, Any]], dict[str, dict[str, Any]], bool]:
|
||||
"""分开取 E10 和 E8 的人员。E8 查询失败时本轮不改写 E8 待发送。"""
|
||||
if directory is not None:
|
||||
return directory[0], directory[1], {}, {}, True
|
||||
e10_people, e10_deputies = _load_e10_directory(orders)
|
||||
try:
|
||||
e8_people, e8_matrix = _load_e8_directory(orders)
|
||||
return e10_people, e10_deputies, e8_people, e8_matrix, True
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 directory skipped error=%s", type(exc).__name__)
|
||||
return e10_people, e10_deputies, {}, {}, False
|
||||
|
||||
|
||||
def _load_e10_directory(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||
"""向 E10 要当前处理人和申请人的主管、部门、经副理。"""
|
||||
"""向 E10 要使用部门担当和申请人的主管、部门、经副理。不传入 E8 人员 ID。"""
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_alert_directory
|
||||
|
||||
ids: set[int] = set()
|
||||
for group in operators.values():
|
||||
for operator in group:
|
||||
if operator.user_id:
|
||||
ids.add(operator.user_id)
|
||||
for order in orders:
|
||||
if order.monitor_status == WATCHING and order.applicant_oa_id:
|
||||
if (order.oa_system or "e10") == "e8" or order.monitor_status != WATCHING:
|
||||
continue
|
||||
if order.owner_oa_id:
|
||||
ids.add(order.owner_oa_id)
|
||||
if order.applicant_oa_id:
|
||||
ids.add(order.applicant_oa_id)
|
||||
return fetch_alert_directory(sorted(ids))
|
||||
|
||||
|
||||
def _load_e8_directory(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||
"""向 E8 要使用部门担当和申请人。人员 ID 只进 HrmResource。"""
|
||||
from app.services.equipment_acceptance.e8_repository import fetch_e8_alert_directory
|
||||
|
||||
ids: set[int] = set()
|
||||
for order in orders:
|
||||
if (order.oa_system or "e10") != "e8" or order.monitor_status != WATCHING:
|
||||
continue
|
||||
if order.owner_oa_id:
|
||||
ids.add(order.owner_oa_id)
|
||||
if order.applicant_oa_id:
|
||||
ids.add(order.applicant_oa_id)
|
||||
return fetch_e8_alert_directory(sorted(ids))
|
||||
|
||||
|
||||
def _job_numbers(
|
||||
orders: list[EquipmentAcceptanceOrder],
|
||||
operators: dict[int, list[EquipmentAcceptanceOperator]],
|
||||
people: dict[int, dict[str, Any]],
|
||||
deputies: dict[str, list[dict[str, Any]]],
|
||||
e10_people: dict[int, dict[str, Any]],
|
||||
e10_deputies: dict[str, list[dict[str, Any]]],
|
||||
e8_people: dict[int, dict[str, Any]],
|
||||
) -> set[str]:
|
||||
"""收集要对系统用户的工号。"""
|
||||
"""收集要对系统用户的工号。E8 矩阵人员不走工号。"""
|
||||
found: set[str] = set()
|
||||
for order in orders:
|
||||
if order.owner_job_num:
|
||||
found.add(order.owner_job_num)
|
||||
if order.applicant_job_num:
|
||||
found.add(order.applicant_job_num)
|
||||
for group in operators.values():
|
||||
for operator in group:
|
||||
if operator.handler_job_num:
|
||||
found.add(operator.handler_job_num)
|
||||
for fact in people.values():
|
||||
for fact in (*e10_people.values(), *e8_people.values()):
|
||||
if fact.get("job_num"):
|
||||
found.add(str(fact["job_num"]))
|
||||
if fact.get("superior_job_num"):
|
||||
found.add(str(fact["superior_job_num"]))
|
||||
for group in deputies.values():
|
||||
for group in e10_deputies.values():
|
||||
for item in group:
|
||||
if item.get("job_num"):
|
||||
found.add(str(item["job_num"]))
|
||||
return found
|
||||
|
||||
|
||||
def _wecom_ids(matrix: dict[str, dict[str, Any]]) -> set[str]:
|
||||
"""收集 E8 矩阵上的企业微信 userid,用来补系统用户主键。"""
|
||||
found: set[str] = set()
|
||||
for item in matrix.values():
|
||||
if not item.get("ok"):
|
||||
continue
|
||||
for key in ("zz", "jfl"):
|
||||
seat = item.get(key) or {}
|
||||
wecom = str(seat.get("wecom_userid") or "").strip()
|
||||
if wecom:
|
||||
found.add(wecom)
|
||||
return found
|
||||
|
||||
|
||||
def _users_by_wecom(wecom_ids: set[str]) -> dict[str, User]:
|
||||
"""按企业微信 userid 索引系统用户。"""
|
||||
if not wecom_ids:
|
||||
return {}
|
||||
rows = db.session.query(User).filter(User.wecom_userid.in_(wecom_ids)).all()
|
||||
return {str(row.wecom_userid): row for row in rows if row.wecom_userid}
|
||||
|
||||
|
||||
def _users_by_job(job_nums: set[str]) -> dict[str, User]:
|
||||
"""用工号索引系统用户。"""
|
||||
if not job_nums:
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_group.py
|
||||
|
||||
用途:把 E8 验收单联表行收成与 E10 相同的快照草稿。
|
||||
依赖:e8_status、snapshot_rules、source_group。
|
||||
逻辑:同步服务在写库前调用。流程状态先翻译。人员 ID 仍是 E8 的 HrmResource.id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.services.equipment_acceptance.e8_status import e8_flow_status
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
as_datetime,
|
||||
as_int,
|
||||
can_accept_from_oa,
|
||||
is_returned_from_oa,
|
||||
)
|
||||
from app.services.equipment_acceptance.source_group import (
|
||||
AcceptanceDraft,
|
||||
NodeDraft,
|
||||
OperatorDraft,
|
||||
)
|
||||
|
||||
_TERMINAL_FLOW = {3, 7}
|
||||
|
||||
|
||||
def group_e8_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDraft], int]:
|
||||
"""
|
||||
按 requestid 合并 E8 联表行。
|
||||
|
||||
核心逻辑:没有 requestid 的行跳过。同一请求的未办人收成一张单。
|
||||
计时起点读 syddjssj。可以验收读 sfkys。来源标记为 e8。
|
||||
Args:
|
||||
rows: 查询别名组成的字典行。
|
||||
Returns:
|
||||
(草稿列表, 因缺少 requestid 而跳过的行数)。
|
||||
"""
|
||||
skipped = 0
|
||||
buckets: dict[int, list[dict[str, Any]]] = {}
|
||||
for row in rows:
|
||||
request_id = as_int(row.get("requestid"))
|
||||
if request_id is None:
|
||||
skipped += 1
|
||||
continue
|
||||
buckets.setdefault(request_id, []).append(row)
|
||||
return [_draft_from_rows(request_id, items) for request_id, items in buckets.items()], skipped
|
||||
|
||||
|
||||
def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> AcceptanceDraft:
|
||||
"""同一流程的多行收成一条 E8 草稿。"""
|
||||
header = items[0]
|
||||
flow_status = e8_flow_status(header.get("currentnodetype"), header.get("currentstatus"))
|
||||
return AcceptanceDraft(
|
||||
oa_system="e8",
|
||||
request_id=request_id,
|
||||
acceptance_no=_text(header.get("ysddh")),
|
||||
purchase_order_no=_text(header.get("cgdh")),
|
||||
contract_no=_text(header.get("htbh")),
|
||||
flow_no=_text(header.get("flow_no")),
|
||||
request_title=_text(header.get("request_title")),
|
||||
request_created_at=_e8_created_at(header),
|
||||
timer_started_at=as_datetime(header.get("syddjssj")),
|
||||
can_accept=can_accept_from_oa(as_int(header.get("sfkys"))),
|
||||
cannot_accept_note=_text(header.get("ycsm")),
|
||||
is_returned=is_returned_from_oa(as_int(header.get("sfzfth"))),
|
||||
flow_status_raw=flow_status,
|
||||
finished_at=_finished_at(header, flow_status),
|
||||
request_match_count=1,
|
||||
nodes=_nodes(items),
|
||||
operators=_operators(items),
|
||||
owner_oa_id=as_int(header.get("sybmdd")),
|
||||
owner_name=_text(header.get("owner_name")),
|
||||
owner_job_num=_text(header.get("owner_job_num")),
|
||||
equip_oa_id=None,
|
||||
equip_name=None,
|
||||
equip_job_num=None,
|
||||
applicant_oa_id=as_int(header.get("creater")),
|
||||
applicant_name=_text(header.get("applicant_name")),
|
||||
applicant_job_num=_text(header.get("applicant_job_num")),
|
||||
)
|
||||
|
||||
|
||||
def _e8_created_at(header: dict[str, Any]) -> datetime | None:
|
||||
"""
|
||||
拼出 E8 流程创建时间。
|
||||
|
||||
核心逻辑:createdate 是日期,createtime 是时分秒,两边分开存。
|
||||
只有日期时按当天 0 点。都空则没有创建时间。
|
||||
"""
|
||||
day = _text(header.get("createdate"))
|
||||
clock = _text(header.get("createtime"))
|
||||
if day is None:
|
||||
return None
|
||||
if clock is None:
|
||||
return as_datetime(day)
|
||||
return as_datetime(f"{day} {clock}")
|
||||
|
||||
|
||||
def _finished_at(header: dict[str, Any], flow_status: int | None) -> datetime | None:
|
||||
"""归档或撤销时,用最后操作时间作为结束时间。进行中不写。"""
|
||||
if flow_status not in _TERMINAL_FLOW:
|
||||
return None
|
||||
parsed = as_datetime(header.get("lastoperatedate"))
|
||||
if parsed is not None:
|
||||
return parsed
|
||||
return None
|
||||
|
||||
|
||||
def _nodes(rows: list[dict[str, Any]]) -> list[NodeDraft]:
|
||||
"""当前节点只取 currentnodeid。没有节点 ID 时不造一行。"""
|
||||
found: dict[int, NodeDraft] = {}
|
||||
for row in rows:
|
||||
node_id = as_int(row.get("currentnodeid"))
|
||||
if node_id is None or node_id in found:
|
||||
continue
|
||||
found[node_id] = NodeDraft(
|
||||
node_id=node_id,
|
||||
node_name=_text(row.get("nodename")),
|
||||
node_type=None,
|
||||
)
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _operators(rows: list[dict[str, Any]]) -> list[OperatorDraft]:
|
||||
"""当前未办人。查询已限定 isremark=0,这里只按人和节点去重。"""
|
||||
found: dict[tuple[int, int], OperatorDraft] = {}
|
||||
for row in rows:
|
||||
node_id = as_int(row.get("currentnodeid"))
|
||||
user_id = as_int(row.get("userid"))
|
||||
if node_id is None or user_id is None:
|
||||
continue
|
||||
key = (node_id, user_id)
|
||||
if key in found:
|
||||
continue
|
||||
found[key] = OperatorDraft(
|
||||
node_id=node_id,
|
||||
user_id=user_id,
|
||||
handler_name=_text(row.get("handler_name")),
|
||||
handler_job_num=_text(row.get("handler_job_num")),
|
||||
)
|
||||
return list(found.values())
|
||||
|
||||
|
||||
def _text(value: Any) -> str | None:
|
||||
"""去空白;空串视为没有值。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_query.py
|
||||
|
||||
用途:组装 E8 验收单只读 SQL。
|
||||
依赖:无。不连接数据库。
|
||||
逻辑:e8_repository 执行本文件的语句。表名固定,不拼接外部字符串。
|
||||
不复用合同付款只取归档日的查询。不取 currentnodetype=3 的归档单,空节点类型仍取。
|
||||
流程编号取 lcbh,标题取 requestname。创建时间取 createdate 加 createtime。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def build_e8_acceptance_sql() -> str:
|
||||
"""
|
||||
组装未归档的 E8 验收单查询。
|
||||
|
||||
核心逻辑:formtable_main_324.requestId 对 workflow_requestbase.requestid。
|
||||
当前节点用 currentnodeid,不用 lastnodeid。当前未办人是 isremark=0。
|
||||
currentnodetype=3 的归档单不取,空值仍取。申请人读 creater,不是 creator。
|
||||
流程编号读 lcbh,标题读 requestname。创建时间由 createdate 与 createtime 拼成。
|
||||
Returns:
|
||||
一条 SELECT。
|
||||
"""
|
||||
return """
|
||||
SELECT
|
||||
f.ysddh AS ysddh,
|
||||
f.cgdh AS cgdh,
|
||||
f.htbh AS htbh,
|
||||
f.lcbh AS flow_no,
|
||||
f.syddjssj AS syddjssj,
|
||||
f.sfzfth AS sfzfth,
|
||||
f.sfkys AS sfkys,
|
||||
f.ycsm AS ycsm,
|
||||
f.sybmdd AS sybmdd,
|
||||
w.requestid AS requestid,
|
||||
w.requestname AS request_title,
|
||||
w.createdate AS createdate,
|
||||
w.createtime AS createtime,
|
||||
LTRIM(RTRIM(CAST(w.currentnodetype AS nvarchar(10)))) AS currentnodetype,
|
||||
w.currentstatus AS currentstatus,
|
||||
w.currentnodeid AS currentnodeid,
|
||||
w.creater AS creater,
|
||||
w.lastoperatedate AS lastoperatedate,
|
||||
w.lastoperatetime AS lastoperatetime,
|
||||
n.nodename AS nodename,
|
||||
op.userid AS userid,
|
||||
owner.lastname AS owner_name,
|
||||
owner.workcode AS owner_job_num,
|
||||
applicant.lastname AS applicant_name,
|
||||
applicant.workcode AS applicant_job_num,
|
||||
handler.lastname AS handler_name,
|
||||
handler.workcode AS handler_job_num
|
||||
FROM formtable_main_324 AS f
|
||||
INNER JOIN workflow_requestbase AS w
|
||||
ON w.requestid = f.requestId
|
||||
LEFT JOIN workflow_nodebase AS n
|
||||
ON n.id = w.currentnodeid
|
||||
LEFT JOIN workflow_currentoperator AS op
|
||||
ON op.requestid = w.requestid
|
||||
AND op.nodeid = w.currentnodeid
|
||||
AND LTRIM(RTRIM(CAST(op.isremark AS nvarchar(10)))) = N'0'
|
||||
LEFT JOIN HrmResource AS owner
|
||||
ON owner.id = f.sybmdd
|
||||
LEFT JOIN HrmResource AS applicant
|
||||
ON applicant.id = w.creater
|
||||
LEFT JOIN HrmResource AS handler
|
||||
ON handler.id = op.userid
|
||||
WHERE w.currentnodetype IS NULL
|
||||
OR LTRIM(RTRIM(CAST(w.currentnodetype AS nvarchar(10)))) <> N'3'
|
||||
""".strip()
|
||||
@@ -0,0 +1,213 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_repository.py
|
||||
|
||||
用途:只读拉取 E8 验收单,以及使用部门担当的直接主管和经副理。
|
||||
依赖:OASQLServerService、e8_query。不连接 E10,不把人员 ID 送进 eteams。
|
||||
逻辑:验收单一次联表。收件人再按 HrmResource.id 查部门和 Matrixtable_3。
|
||||
zz、jfl 就是企业微信 userid。矩阵不是一行时该部门失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
from app.services.equipment_acceptance.e8_query import build_e8_acceptance_sql
|
||||
from app.services.equipment_acceptance.snapshot_rules import as_int
|
||||
from app.services.integrations.oa.sqlserver import OASQLServerService
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def fetch_e8_acceptance_rows() -> list[dict[str, Any]]:
|
||||
"""
|
||||
从 E8 拉验收单联表结果。
|
||||
|
||||
核心逻辑:复用 OA_SQLSERVER_* 只读连接。失败不改走 E10。
|
||||
Returns:
|
||||
字段名为小写别名的字典行。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 连接或查询失败。
|
||||
"""
|
||||
connection = _open()
|
||||
try:
|
||||
cursor = connection.cursor()
|
||||
cursor.execute(build_e8_acceptance_sql())
|
||||
columns = [str(col[0]).lower() for col in cursor.description]
|
||||
return [
|
||||
{columns[index]: raw[index] for index in range(len(columns))}
|
||||
for raw in cursor.fetchall()
|
||||
]
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 sql failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"查询 E8 设备验收数据失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def fetch_e8_alert_directory(
|
||||
person_ids: list[int],
|
||||
) -> tuple[dict[int, dict[str, Any]], dict[str, dict[str, Any]]]:
|
||||
"""
|
||||
按使用部门担当和申请人的 HrmResource.id 取工号,并按部门取直接主管、经副理。
|
||||
|
||||
核心逻辑:工号是 workcode。Matrixtable_3.bm 必须只命中一行,zz 是直接主管,jfl 是经副理。
|
||||
这两个 ID 同时是企业微信 userid。没有人员时不连库。
|
||||
Args:
|
||||
person_ids: HrmResource.id。禁止传入 E10 的 employee.ID。
|
||||
Returns:
|
||||
(人员字典, 部门 ID 到矩阵结果)。矩阵结果含 ok、zz、jfl。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 连接或查询失败。
|
||||
"""
|
||||
ids = sorted({int(item) for item in person_ids if item is not None})
|
||||
if not ids:
|
||||
return {}, {}
|
||||
connection = _open()
|
||||
try:
|
||||
cursor = connection.cursor()
|
||||
people = _load_people(cursor, ids)
|
||||
departments = sorted({item["department_id"] for item in people.values() if item.get("department_id")})
|
||||
matrix = _load_matrix(cursor, departments)
|
||||
_fill_matrix_names(cursor, matrix)
|
||||
return people, matrix
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 directory failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"查询 E8 直接主管和经副理失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def _open():
|
||||
"""打开 E8 ecology 连接。异常收成业务错误,不把连接串写进日志。"""
|
||||
try:
|
||||
return OASQLServerService._connect()
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance e8 connect failed error=%s", type(exc).__name__)
|
||||
raise ServiceUnavailableError(
|
||||
"连接 E8 SQL Server 失败",
|
||||
code="EQUIPMENT_ACCEPTANCE.OA_SQL_FAILED",
|
||||
) from exc
|
||||
|
||||
|
||||
def _load_people(cursor: Any, person_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||||
"""取出姓名、工号和部门。"""
|
||||
found: dict[int, dict[str, Any]] = {}
|
||||
for chunk in _chunks(person_ids):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
cursor.execute(
|
||||
f"""
|
||||
SELECT id, lastname, workcode, departmentid
|
||||
FROM HrmResource
|
||||
WHERE id IN ({marks})
|
||||
""",
|
||||
chunk,
|
||||
)
|
||||
for raw in cursor.fetchall():
|
||||
person_id = as_int(raw[0])
|
||||
if person_id is None:
|
||||
continue
|
||||
found[person_id] = {
|
||||
"oa_id": person_id,
|
||||
"name": _clean(raw[1]),
|
||||
"job_num": _clean(raw[2]),
|
||||
"department_id": _clean(raw[3]),
|
||||
}
|
||||
return found
|
||||
|
||||
|
||||
def _load_matrix(cursor: Any, department_ids: list[str]) -> dict[str, dict[str, Any]]:
|
||||
"""按部门取矩阵。不是正好一行就记失败,不挑其中一行。"""
|
||||
grouped: dict[str, list[tuple[Any, Any]]] = {}
|
||||
if not department_ids:
|
||||
return {}
|
||||
for chunk in _chunks(department_ids):
|
||||
marks = ",".join("?" for _ in chunk)
|
||||
params = [int(item) if str(item).isdigit() else item for item in chunk]
|
||||
cursor.execute(
|
||||
f"""
|
||||
SELECT bm, zz, jfl
|
||||
FROM Matrixtable_3
|
||||
WHERE bm IN ({marks})
|
||||
""",
|
||||
params,
|
||||
)
|
||||
for raw in cursor.fetchall():
|
||||
department_id = _clean(raw[0])
|
||||
if not department_id:
|
||||
continue
|
||||
grouped.setdefault(department_id, []).append((raw[1], raw[2]))
|
||||
found: dict[str, dict[str, Any]] = {}
|
||||
for department_id, rows in grouped.items():
|
||||
if len(rows) != 1:
|
||||
found[department_id] = {"ok": False, "zz": None, "jfl": None}
|
||||
continue
|
||||
zz_id = as_int(rows[0][0])
|
||||
jfl_id = as_int(rows[0][1])
|
||||
found[department_id] = {
|
||||
"ok": True,
|
||||
"zz": _seat(zz_id),
|
||||
"jfl": _seat(jfl_id),
|
||||
}
|
||||
return found
|
||||
|
||||
|
||||
def _fill_matrix_names(cursor: Any, matrix: dict[str, dict[str, Any]]) -> None:
|
||||
"""给直接主管和经副理补姓名。查不到姓名仍保留企微 userid。"""
|
||||
ids = sorted({
|
||||
seat["oa_id"]
|
||||
for item in matrix.values()
|
||||
if item.get("ok")
|
||||
for seat in (item.get("zz"), item.get("jfl"))
|
||||
if seat and seat.get("oa_id") is not None
|
||||
})
|
||||
if not ids:
|
||||
return
|
||||
names = _load_people(cursor, ids)
|
||||
for item in matrix.values():
|
||||
if not item.get("ok"):
|
||||
continue
|
||||
for key in ("zz", "jfl"):
|
||||
seat = item.get(key)
|
||||
if not seat:
|
||||
continue
|
||||
fact = names.get(seat["oa_id"]) or {}
|
||||
if fact.get("name"):
|
||||
seat["name"] = fact["name"]
|
||||
|
||||
|
||||
def _seat(person_id: int | None) -> dict[str, Any] | None:
|
||||
"""矩阵里的人员 ID 直接作为企业微信 userid。"""
|
||||
if person_id is None:
|
||||
return None
|
||||
return {
|
||||
"oa_id": person_id,
|
||||
"name": None,
|
||||
"wecom_userid": str(person_id),
|
||||
}
|
||||
|
||||
|
||||
def _chunks(values: list[Any], size: int = 400) -> list[list[Any]]:
|
||||
"""把 IN 列表拆开。"""
|
||||
return [values[index:index + size] for index in range(0, len(values), size)]
|
||||
|
||||
|
||||
def _clean(value: Any) -> str | None:
|
||||
"""去掉空白。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/e8_status.py
|
||||
|
||||
用途:把 E8 流程状态收成与 E10 相同的 flow_status_raw。
|
||||
依赖:无。不读数据库。
|
||||
逻辑:同步分组在落库前调用。currentstatus 优先于 currentnodetype。
|
||||
E8 没有作废和强制结束,不写成 5 或 4。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# 与 E10 的审批中、归档、撤销对齐。暂停按 E10 的 flowstatus=7,同样停表。
|
||||
_APPROVING = 1
|
||||
_ARCHIVED = 3
|
||||
_REVOKED = 7
|
||||
_APPROVING_NODE_TYPES = {"0", "1", "2"}
|
||||
_PAUSE_OR_REVOKE = {0, 1}
|
||||
|
||||
|
||||
def e8_flow_status(currentnodetype: Any, currentstatus: Any) -> int | None:
|
||||
"""
|
||||
把 E8 的节点类型和暂停/撤销收成本地流程状态。
|
||||
|
||||
核心逻辑:currentstatus 为空才看 currentnodetype。0 暂停、1 撤销都写成 7。
|
||||
空、0、1 以外不写成审批中,返回空,调用方不把这张单放进进行中。
|
||||
Args:
|
||||
currentnodetype: workflow_requestbase.currentnodetype。0/1/2 审批中,3 归档。
|
||||
currentstatus: workflow_requestbase.currentstatus。空是正常,0 暂停,1 撤销。
|
||||
Returns:
|
||||
1、3 或 7。无法识别时为 None。
|
||||
"""
|
||||
status = _blank_to_none(currentstatus)
|
||||
if status is not None:
|
||||
code = _as_int(status)
|
||||
if code in _PAUSE_OR_REVOKE:
|
||||
return _REVOKED
|
||||
return None
|
||||
node_type = _blank_to_none(currentnodetype)
|
||||
if node_type in _APPROVING_NODE_TYPES:
|
||||
return _APPROVING
|
||||
if node_type == "3":
|
||||
return _ARCHIVED
|
||||
return None
|
||||
|
||||
|
||||
def _blank_to_none(value: Any) -> str | None:
|
||||
"""空白当成没有值。数字也收成去掉空白的文本。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _as_int(value: str) -> int | None:
|
||||
"""整数字符串收成 int。带小数或字母的不猜。"""
|
||||
try:
|
||||
if "." in value:
|
||||
return None
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -126,12 +126,12 @@ def _open_connection(settings: EquipmentAcceptanceSqlSettings):
|
||||
|
||||
def fetch_alert_directory(employee_ids: list[int]) -> tuple[dict[int, dict[str, Any]], dict[str, list[dict[str, Any]]]]:
|
||||
"""
|
||||
读取处理人的直接主管,并按部门查出经副理。
|
||||
读取使用部门担当的直接主管,并按部门查出经副理。
|
||||
|
||||
核心逻辑:主管在 employee.SUPERIOR。经副理不在这一列,按部门 ID 走 eteams 矩阵条件表。
|
||||
人员 ID 必须是整数。没有人员时不连库。
|
||||
人员 ID 必须是 E10 的 employee.ID。没有人员时不连库。
|
||||
Args:
|
||||
employee_ids: 当前处理人和申请人的 employee.ID。
|
||||
employee_ids: 使用部门担当和申请人的 employee.ID。禁止传入 E8 的 HrmResource.id。
|
||||
Returns:
|
||||
(人员字典, 部门 ID 到经副理列表)。人员字典的键是 employee.ID。
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ backend/app/services/equipment_acceptance/query_sql.py
|
||||
用途:决定 E10 各表所在库,并组装只读联表 SQL。
|
||||
依赖:无 Flask。库名只允许字母、数字和下划线。
|
||||
逻辑:同步仓库调用。验收单用 FORM_DATA_ID 经 wfc_form_data 挂到流程实例。
|
||||
不读流程编号、第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||
不取 flowstatus=3 的归档单。flowstatus 为空仍取。
|
||||
流程编号读 requestmark,标题读 requestname,创建时间读 createdatetime。不读第二合同编号、验收日期、optgroupid、batch_number、operate_log_id、isremark。无法验收说明读取 ycsm。字典库看不到时,流程表回退到 ecology10。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -68,8 +69,8 @@ def build_acceptance_sql(catalogs: AcceptanceCatalogs) -> str:
|
||||
组装验收单、人员、流程实例、当前节点、节点定义、操作人的只读 SQL。
|
||||
|
||||
核心逻辑:用 FORM_DATA_ID 对齐 wfc_form_data.dataid,再按 requestid 挂到流程实例。
|
||||
不查询流程编号、第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||
delete_type 只取 0。当前处理人就是这些 userid。
|
||||
流程编号取 requestmark,标题取 requestname,创建时间取 createdatetime。不查询第二合同编号、验收日期和 isremark。当前节点和操作人按 requestid + nodeid 对齐,
|
||||
delete_type 只取 0。当前处理人就是这些 userid。归档(flowstatus=3)不取,空状态仍取。
|
||||
Args:
|
||||
catalogs: 已解析的库名。
|
||||
Returns:
|
||||
@@ -104,6 +105,9 @@ SELECT
|
||||
applicant.USERNAME AS applicant_name,
|
||||
applicant.JOB_NUM AS applicant_job_num,
|
||||
r.requestid,
|
||||
r.requestmark AS flow_no,
|
||||
r.requestname AS request_title,
|
||||
r.createdatetime,
|
||||
r.flowstatus,
|
||||
r.finishdatetime,
|
||||
c.nodeid,
|
||||
@@ -135,6 +139,7 @@ LEFT JOIN {operate} AS op
|
||||
LEFT JOIN {employee} AS handler ON handler.ID = op.userid
|
||||
WHERE ISNULL(f.delete_type, 0) = 0
|
||||
AND r.requestid IS NOT NULL
|
||||
AND (r.flowstatus IS NULL OR r.flowstatus <> 3)
|
||||
""".strip()
|
||||
|
||||
|
||||
|
||||
@@ -179,7 +179,7 @@ def classify_monitor_status(
|
||||
按已确认规则给出监控状态。入参已是标准 0=否、1=是。
|
||||
|
||||
核心逻辑:退回、无法验收、作废、归档、强制结束、撤销优先于未开始。
|
||||
审批中、可以验收、未退回、已有计时起点才是计时中。
|
||||
审批中、未退回、已有计时起点,且可以验收不是明确为否时计时。空和是都监控。
|
||||
flowstatus 为 7、8、99、-99 时记为已撤销,有没有计时起点都不再提醒。
|
||||
Args:
|
||||
can_accept: 本地是否可以正常验收。0 否,1 是,空为未标明。
|
||||
@@ -204,8 +204,8 @@ def classify_monitor_status(
|
||||
return STOPPED_REVOKED
|
||||
if not timer_started:
|
||||
return NOT_STARTED
|
||||
# [STEP 2] 只有审批中、可以验收、未退回时继续计时
|
||||
if can_accept == 1 and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||
# [STEP 2] 可以验收只有明确为否才停表,空和是都继续计时。0、1、空以外不猜。
|
||||
if can_accept in (1, None) and flow_status == _FLOW_APPROVING and is_returned == 0:
|
||||
return WATCHING
|
||||
return EXCLUDED
|
||||
|
||||
|
||||
@@ -42,12 +42,16 @@ class NodeDraft:
|
||||
|
||||
@dataclass
|
||||
class AcceptanceDraft:
|
||||
"""一张验收单在一次同步中的快照草稿。不包含流程编号、第二合同编号和验收日期。"""
|
||||
"""一张验收单在一次同步中的快照草稿。含流程编号、标题和创建时间。不含第二合同编号和验收日期。"""
|
||||
|
||||
oa_system: str
|
||||
request_id: int
|
||||
acceptance_no: str | None
|
||||
purchase_order_no: str | None
|
||||
contract_no: str | None
|
||||
flow_no: str | None
|
||||
request_title: str | None
|
||||
request_created_at: datetime | None
|
||||
timer_started_at: datetime | None
|
||||
can_accept: int | None
|
||||
cannot_accept_note: str | None
|
||||
@@ -73,7 +77,7 @@ def group_acceptance_rows(rows: list[dict[str, Any]]) -> tuple[list[AcceptanceDr
|
||||
按流程实例 requestid 合并联表结果。
|
||||
|
||||
核心逻辑:没有 requestid 的行跳过。同一请求上的节点和操作人收成一张单。
|
||||
不读取流程编号、第二合同编号和验收日期。
|
||||
流程编号和标题随行写入。不读取第二合同编号和验收日期。
|
||||
Args:
|
||||
rows: 查询别名组成的字典行。
|
||||
Returns:
|
||||
@@ -94,10 +98,14 @@ def _draft_from_rows(request_id: int, items: list[dict[str, Any]]) -> Acceptance
|
||||
"""同一流程实例的多行收成一条草稿。"""
|
||||
header = items[0]
|
||||
return AcceptanceDraft(
|
||||
oa_system="e10",
|
||||
request_id=request_id,
|
||||
acceptance_no=_text(header.get("ysddh")),
|
||||
purchase_order_no=_text(header.get("cgdh")),
|
||||
contract_no=_text(header.get("htbh")),
|
||||
flow_no=_text(header.get("flow_no")),
|
||||
request_title=_text(header.get("request_title")),
|
||||
request_created_at=as_datetime(header.get("createdatetime")),
|
||||
timer_started_at=as_datetime(header.get("sbsyrjssj")),
|
||||
can_accept=can_accept_from_oa(as_int(header.get("sfkyzcys"))),
|
||||
cannot_accept_note=_text(header.get("ycsm")),
|
||||
|
||||
@@ -1,19 +1,24 @@
|
||||
"""
|
||||
backend/app/services/equipment_acceptance/sync_service.py
|
||||
|
||||
用途:把 E10 验收单快照写入本地表,并提供管理员查询。
|
||||
依赖:extensions.db、equipment_acceptance 模型、snapshot_rules、source_group、oa_repository。
|
||||
逻辑:手动同步 upsert 主表并替换子表。列表按原型分组过滤,并附带全部单据的汇总。
|
||||
停表时取消该单未发送的预警。操作人不保存 isremark。
|
||||
用途:把 E10 和 E8 验收单快照写入本地表,并提供管理员查询。
|
||||
依赖:extensions.db、sqlalchemy.or_、equipment_acceptance 模型、snapshot_rules、source_group、e8_group、oa_repository、e8_repository。
|
||||
逻辑:两个来源分开拉取。一边失败不改另一边的快照,也不把失败来源标成消失。
|
||||
只保留未归档单据。归档单不写入;该来源本次结果里没有的本地单删除,并取消未发送预警。
|
||||
主表按 oa_system + request_id 更新,并写入流程编号和标题。子表整批替换。停表时取消未发送预警。
|
||||
列表查询由 api/equipment_acceptance 调用。单号关键字同时匹配流程编号、验收单号和采购单号,再与申请人取交集。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections import Counter
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.response import utc_iso
|
||||
from app.extensions import db
|
||||
@@ -25,12 +30,15 @@ from app.models.equipment_acceptance import (
|
||||
from app.services.equipment_acceptance.config_service import first_reminder_day
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
MONITOR_STATUSES,
|
||||
STOPPED_ARCHIVED,
|
||||
classify_monitor_status,
|
||||
dwell_days,
|
||||
)
|
||||
from app.services.equipment_acceptance.source_group import AcceptanceDraft, group_acceptance_rows
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
_ARCHIVED_FLOW = 3
|
||||
_LEDGER_FOCUSES = ("watching", "overdue", "stopped", "not_started")
|
||||
_STOPPED_STATUSES = (
|
||||
"stopped_returned",
|
||||
@@ -42,34 +50,107 @@ _STOPPED_STATUSES = (
|
||||
)
|
||||
|
||||
|
||||
def sync_acceptance_snapshots(rows: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||
def sync_acceptance_snapshots(
|
||||
rows: list[dict[str, Any]] | None = None,
|
||||
*,
|
||||
e8_rows: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
同步验收单快照。
|
||||
同步 E10 和 E8 验收单快照。
|
||||
|
||||
核心逻辑:未传入行时自己读 E10。按流程实例 request_id 更新主表,子表整批替换。
|
||||
本次查询里消失的单据保留上次内容,只把 present_in_source 标成否。
|
||||
核心逻辑:未传入行时分别读两个来源。一边查询失败只跳过这一边,不把已有快照标成消失。
|
||||
只保留未归档单据。该来源本次没返回的本地单删掉。只传入 rows 时只同步 E10,方便既有测试注入联表行。
|
||||
Args:
|
||||
rows: 测试或调用方已经取好的联表行。None 时访问 E10。
|
||||
rows: 已取好的 E10 联表行。None 时访问 E10。
|
||||
e8_rows: 已取好的 E8 联表行。与 rows 同时为 None 时才访问 E8。
|
||||
Returns:
|
||||
本次写入条数、跳过条数、停表取消的未发送条数,以及各监控状态计数。
|
||||
两边合计的写入、跳过、消失和取消条数,以及 e10、e8 各自的结果。
|
||||
"""
|
||||
if rows is None:
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||
|
||||
rows = fetch_acceptance_rows()
|
||||
drafts, skipped = group_acceptance_rows(rows)
|
||||
fetch_live = rows is None and e8_rows is None
|
||||
e10_rows, e10_ok, e10_error = _source_rows("e10", rows, fetch_live)
|
||||
e8_input, e8_ok, e8_error = _source_rows("e8", e8_rows, fetch_live)
|
||||
as_of = datetime.now(_SHANGHAI).date()
|
||||
e10_result = _apply_source("e10", e10_rows, e10_ok, e10_error, as_of, group_acceptance_rows)
|
||||
from app.services.equipment_acceptance.e8_group import group_e8_rows
|
||||
|
||||
e8_result = _apply_source("e8", e8_input, e8_ok, e8_error, as_of, group_e8_rows)
|
||||
db.session.commit()
|
||||
cancelled = e10_result["cancelled"] + e8_result["cancelled"]
|
||||
counts: Counter[str] = Counter(e10_result["by_status"])
|
||||
counts.update(e8_result["by_status"])
|
||||
return {
|
||||
"upserted": e10_result["upserted"] + e8_result["upserted"],
|
||||
"skipped_without_request_id": (
|
||||
e10_result["skipped_without_request_id"] + e8_result["skipped_without_request_id"]
|
||||
),
|
||||
"absent": e10_result["absent"] + e8_result["absent"],
|
||||
"cancelled": cancelled,
|
||||
"by_status": dict(counts),
|
||||
"e10": e10_result,
|
||||
"e8": e8_result,
|
||||
}
|
||||
|
||||
|
||||
def _source_rows(
|
||||
source: str,
|
||||
injected: list[dict[str, Any]] | None,
|
||||
fetch_live: bool,
|
||||
) -> tuple[list[dict[str, Any]] | None, bool, str | None]:
|
||||
"""取一个来源的行。注入的行视为成功。实时查询失败时不标消失。"""
|
||||
if injected is not None:
|
||||
return injected, True, None
|
||||
if not fetch_live:
|
||||
return None, False, None
|
||||
try:
|
||||
if source == "e10":
|
||||
from app.services.equipment_acceptance.oa_repository import fetch_acceptance_rows
|
||||
|
||||
return fetch_acceptance_rows(), True, None
|
||||
from app.services.equipment_acceptance.e8_repository import fetch_e8_acceptance_rows
|
||||
|
||||
return fetch_e8_acceptance_rows(), True, None
|
||||
except Exception as exc:
|
||||
_LOGGER.warning("equipment acceptance %s sync skipped error=%s", source, type(exc).__name__)
|
||||
return None, False, type(exc).__name__
|
||||
|
||||
|
||||
def _apply_source(
|
||||
source: str,
|
||||
rows: list[dict[str, Any]] | None,
|
||||
ok: bool,
|
||||
error: str | None,
|
||||
as_of,
|
||||
grouper,
|
||||
) -> dict[str, Any]:
|
||||
"""把一个来源的未归档草稿写入。该来源这次没返回的本地单删除。"""
|
||||
if not ok or rows is None:
|
||||
return {
|
||||
"ok": False,
|
||||
"error": error,
|
||||
"upserted": 0,
|
||||
"skipped_without_request_id": 0,
|
||||
"absent": 0,
|
||||
"cancelled": 0,
|
||||
"by_status": {},
|
||||
}
|
||||
drafts, skipped = grouper(rows)
|
||||
counts: Counter[str] = Counter()
|
||||
request_ids: list[int] = []
|
||||
cancelled = 0
|
||||
for draft in drafts:
|
||||
# [STEP] 归档单不落本地。查询已排除;这里再挡一层,避免注入行把归档单写回来。
|
||||
if draft.flow_status_raw == _ARCHIVED_FLOW:
|
||||
continue
|
||||
draft.oa_system = source
|
||||
order, cancelled_now = _upsert_order(draft, as_of=as_of)
|
||||
request_ids.append(order.request_id)
|
||||
counts[order.monitor_status] += 1
|
||||
cancelled += cancelled_now
|
||||
absent = _mark_absent(request_ids)
|
||||
db.session.commit()
|
||||
absent, cancelled_missing = _drop_missing(request_ids, source)
|
||||
cancelled += cancelled_missing
|
||||
return {
|
||||
"ok": True,
|
||||
"error": None,
|
||||
"upserted": len(drafts),
|
||||
"skipped_without_request_id": skipped,
|
||||
"absent": absent,
|
||||
@@ -84,17 +165,23 @@ def list_acceptance_orders(
|
||||
focus: str | None,
|
||||
page: int,
|
||||
page_size: int,
|
||||
keyword: str | None = None,
|
||||
applicant: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
分页列出本地快照。
|
||||
|
||||
核心逻辑:focus 按原型的全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||
已逾期是计时中且签核天数超过第 1 档。汇总数字始终看全部单据。
|
||||
核心逻辑:focus 按全部、进行中、已逾期、不再提醒、未开始过滤。
|
||||
keyword 在流程编号、验收单号、采购单号里任一包含即命中,再与申请人姓名取交集。
|
||||
已归档不列出。已逾期是计时中且签核天数超过第 1 档。
|
||||
汇总不看当前状态分组,但跟着单号关键字和申请人走,也不计归档。
|
||||
Args:
|
||||
monitor_status: 可选的单个监控状态代码。与 focus 同时传时以 focus 为准。
|
||||
focus: watching、overdue、stopped、not_started 或空。
|
||||
page: 从 1 开始。
|
||||
page_size: 每页条数,上限 100。
|
||||
keyword: 流程编号、验收单号或采购单号的包含匹配。空白表示不筛。
|
||||
applicant: 申请人姓名的包含匹配。空白表示不筛。
|
||||
Returns:
|
||||
items、total、page、page_size、summary。
|
||||
|
||||
@@ -106,7 +193,11 @@ def list_acceptance_orders(
|
||||
reminder_day = first_reminder_day()
|
||||
page = max(1, page)
|
||||
page_size = min(100, max(1, page_size))
|
||||
query = db.session.query(EquipmentAcceptanceOrder)
|
||||
query = _apply_search(
|
||||
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
|
||||
keyword=keyword,
|
||||
applicant=applicant,
|
||||
)
|
||||
if ledger_focus:
|
||||
query = _apply_focus(query, ledger_focus, reminder_day)
|
||||
elif status:
|
||||
@@ -131,7 +222,7 @@ def list_acceptance_orders(
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"pages": pages,
|
||||
"summary": _ledger_summary(reminder_day),
|
||||
"summary": _ledger_summary(reminder_day, keyword=keyword, applicant=applicant),
|
||||
}
|
||||
|
||||
|
||||
@@ -160,20 +251,25 @@ def get_acceptance_order(order_id: int) -> dict[str, Any]:
|
||||
|
||||
def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptanceOrder, int]:
|
||||
"""
|
||||
按流程实例 request_id 更新主表,并替换该单的节点和操作人。
|
||||
按来源和流程实例更新主表,并替换该单的节点和操作人。
|
||||
|
||||
核心逻辑:不再计时的单据顺手取消未发送预警。已发送的记录不动。
|
||||
E10 与 E8 的 request_id 可以相同,必须连 oa_system 一起查。
|
||||
Returns:
|
||||
更新后的验收单,以及本次改成已取消的发送记录条数。
|
||||
"""
|
||||
order = (
|
||||
db.session.query(EquipmentAcceptanceOrder)
|
||||
.filter(EquipmentAcceptanceOrder.request_id == draft.request_id)
|
||||
.filter(
|
||||
EquipmentAcceptanceOrder.oa_system == draft.oa_system,
|
||||
EquipmentAcceptanceOrder.request_id == draft.request_id,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
if order is None:
|
||||
order = EquipmentAcceptanceOrder(
|
||||
oa_system=draft.oa_system,
|
||||
request_id=draft.request_id,
|
||||
monitor_status="excluded",
|
||||
synced_at=now,
|
||||
@@ -185,6 +281,9 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
|
||||
order.acceptance_no = draft.acceptance_no
|
||||
order.purchase_order_no = draft.purchase_order_no
|
||||
order.contract_no = draft.contract_no
|
||||
order.flow_no = draft.flow_no
|
||||
order.request_title = draft.request_title
|
||||
order.request_created_at = draft.request_created_at
|
||||
order.timer_started_at = draft.timer_started_at
|
||||
order.can_accept = draft.can_accept
|
||||
order.cannot_accept_note = draft.cannot_accept_note
|
||||
@@ -254,12 +353,45 @@ def _upsert_order(draft: AcceptanceDraft, *, as_of) -> tuple[EquipmentAcceptance
|
||||
return order, cancelled
|
||||
|
||||
|
||||
def _mark_absent(request_ids: list[int]) -> int:
|
||||
"""把这次没拉到的单据标成源里不存在。"""
|
||||
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.present_in_source.is_(True))
|
||||
def _drop_missing(request_ids: list[int], oa_system: str) -> tuple[int, int]:
|
||||
"""
|
||||
删除这个来源里本次未归档结果没有的本地单。
|
||||
|
||||
核心逻辑:查询已不含归档。本地还在、结果里没有的单,视为已归档或已从 OA 消失。
|
||||
先取消未发送预警,再删主表。节点和操作人随外键级联删除。已发送记录保留,只解开验收单外键。
|
||||
不改另一个来源。查询失败的来源不会进到这里。
|
||||
Returns:
|
||||
删除张数,以及取消的未发送条数。
|
||||
"""
|
||||
query = db.session.query(EquipmentAcceptanceOrder).filter(EquipmentAcceptanceOrder.oa_system == oa_system)
|
||||
if request_ids:
|
||||
query = query.filter(EquipmentAcceptanceOrder.request_id.notin_(request_ids))
|
||||
return query.update({EquipmentAcceptanceOrder.present_in_source: False}, synchronize_session=False)
|
||||
gone = query.all()
|
||||
if not gone:
|
||||
return 0, 0
|
||||
from app.services.equipment_acceptance.alert_service import cancel_unsent
|
||||
|
||||
cancelled = 0
|
||||
for order in gone:
|
||||
cancelled += cancel_unsent(order.id)
|
||||
db.session.delete(order)
|
||||
return len(gone), cancelled
|
||||
|
||||
|
||||
def _without_archived(query):
|
||||
"""
|
||||
列表和汇总都不展示已归档。
|
||||
|
||||
核心逻辑:状态已是归档的不显示。流程原值已是 3 的也不显示,
|
||||
避免退回或无法验收优先落成别的状态后,归档单仍留在列表里。
|
||||
"""
|
||||
return query.filter(
|
||||
EquipmentAcceptanceOrder.monitor_status != STOPPED_ARCHIVED,
|
||||
or_(
|
||||
EquipmentAcceptanceOrder.flow_status_raw.is_(None),
|
||||
EquipmentAcceptanceOrder.flow_status_raw != _ARCHIVED_FLOW,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _clean_focus(focus: str | None) -> str | None:
|
||||
@@ -290,9 +422,65 @@ def _apply_focus(query, focus: str, reminder_day: int):
|
||||
)
|
||||
|
||||
|
||||
def _ledger_summary(reminder_day: int) -> dict[str, int]:
|
||||
"""统计全部单据的进行中、已逾期、不再提醒、未开始,不受当前筛选影响。"""
|
||||
base = db.session.query(EquipmentAcceptanceOrder)
|
||||
def _clean_search(value: str | None) -> str | None:
|
||||
"""去掉首尾空白。空白视为不筛选。过长时只保留前 100 字,避免把整段说明送进 LIKE。"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
return text[:100]
|
||||
|
||||
|
||||
def _contains_pattern(text: str) -> str:
|
||||
"""
|
||||
把用户输入收成包含匹配,并把 LIKE 通配符当成普通字符。
|
||||
|
||||
核心逻辑:% 和 _ 要能搜出单号里的原字符,不能变成任意匹配。
|
||||
|
||||
Args:
|
||||
text: 已经去掉空白的搜索词。
|
||||
|
||||
Returns:
|
||||
带前后百分号、且转义过的模式。
|
||||
"""
|
||||
escaped = text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
return f"%{escaped}%"
|
||||
|
||||
|
||||
def _apply_search(query, *, keyword: str | None, applicant: str | None):
|
||||
"""
|
||||
按单号关键字和申请人收窄查询。
|
||||
|
||||
核心逻辑:关键字在流程编号、验收单号、采购单号三者取并集;申请人再与这个结果取交集。
|
||||
比较不区分大小写。空值不加入条件。
|
||||
"""
|
||||
number = _clean_search(keyword)
|
||||
if number:
|
||||
pattern = _contains_pattern(number)
|
||||
query = query.filter(or_(
|
||||
EquipmentAcceptanceOrder.flow_no.ilike(pattern, escape="\\"),
|
||||
EquipmentAcceptanceOrder.acceptance_no.ilike(pattern, escape="\\"),
|
||||
EquipmentAcceptanceOrder.purchase_order_no.ilike(pattern, escape="\\"),
|
||||
))
|
||||
person = _clean_search(applicant)
|
||||
if person:
|
||||
query = query.filter(
|
||||
EquipmentAcceptanceOrder.applicant_name.ilike(_contains_pattern(person), escape="\\"),
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
def _ledger_summary(
|
||||
reminder_day: int,
|
||||
*,
|
||||
keyword: str | None = None,
|
||||
applicant: str | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""统计未归档单据的进行中、已逾期、不再提醒、未开始。不看状态分组,但跟着单号和申请人走。"""
|
||||
base = _apply_search(
|
||||
_without_archived(db.session.query(EquipmentAcceptanceOrder)),
|
||||
keyword=keyword,
|
||||
applicant=applicant,
|
||||
)
|
||||
return {
|
||||
"watching": base.filter(EquipmentAcceptanceOrder.monitor_status == "watching").count(),
|
||||
"overdue": base.filter(
|
||||
@@ -359,9 +547,13 @@ def _order_payload(
|
||||
"""把快照收成 API 数据。人员主键用字符串,避免长整型在前端丢精度。overdue 只标记计时中且超过第 1 档的单据。"""
|
||||
payload: dict[str, Any] = {
|
||||
"id": order.id,
|
||||
"oa_system": order.oa_system,
|
||||
"acceptance_no": order.acceptance_no,
|
||||
"purchase_order_no": order.purchase_order_no,
|
||||
"contract_no": order.contract_no,
|
||||
"flow_no": order.flow_no,
|
||||
"request_title": order.request_title,
|
||||
"request_created_at": utc_iso(order.request_created_at),
|
||||
"timer_started_at": utc_iso(order.timer_started_at),
|
||||
"dwell_days": order.dwell_days,
|
||||
"can_accept": order.can_accept,
|
||||
|
||||
@@ -4,6 +4,8 @@ backend/app/services/file_assets/storage.py
|
||||
用途:私有 MinIO 业务文件存储适配层(与 agent-guides 公开 bucket 隔离)。
|
||||
依赖:minio、app.core.config.settings、app.core.errors.ServiceUnavailableError。
|
||||
逻辑:由 file_assets.service 与调拨证据清单调用;禁止 public-read policy 与本地静默回退;
|
||||
读写删走 MINIO_ENDPOINT(容器内网)。浏览器预签走 MINIO_PUBLIC_BASE_URL,
|
||||
因为签名包含 Host,不能把 host.docker.internal 交给浏览器后再替换。
|
||||
读写删失败统一抛 503。预签下载可附带 response-content-disposition,避免保存名落成对象键。
|
||||
"""
|
||||
|
||||
@@ -13,6 +15,7 @@ import io
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from typing import BinaryIO
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
@@ -24,16 +27,75 @@ _LOGGER = logging.getLogger(__name__)
|
||||
_cfg = config[ACTIVE_ENV_NAME]
|
||||
|
||||
|
||||
def resolve_presign_endpoint(
|
||||
public_base: str,
|
||||
fallback_endpoint: str,
|
||||
fallback_secure: bool,
|
||||
) -> tuple[str, bool]:
|
||||
"""把浏览器可访问的 MinIO 基址收成预签名客户端的 endpoint 与 secure。
|
||||
|
||||
核心逻辑:SigV4 把 Host 写进签名。正式环境容器用 host.docker.internal:9000
|
||||
读写,浏览器必须打开 MINIO_PUBLIC_BASE_URL(如 http://ai.well-trust.com:9000)。
|
||||
基址为空或解析不出主机时退回内网端点。80/443 省略端口,交给 Minio 客户端按协议补。
|
||||
|
||||
Args:
|
||||
public_base: MINIO_PUBLIC_BASE_URL,可带或不带协议。
|
||||
fallback_endpoint: 容器内访问用的 host:port。
|
||||
fallback_secure: 内网端点是否走 HTTPS。
|
||||
|
||||
Returns:
|
||||
(endpoint, secure)。endpoint 形如 ai.well-trust.com:9000。
|
||||
"""
|
||||
raw = (public_base or "").strip()
|
||||
if not raw:
|
||||
return fallback_endpoint, fallback_secure
|
||||
parsed = urlparse(raw if "://" in raw else f"http://{raw}")
|
||||
host = parsed.hostname
|
||||
if not host:
|
||||
return fallback_endpoint, fallback_secure
|
||||
if ":" in host:
|
||||
host = f"[{host}]"
|
||||
secure = parsed.scheme.lower() == "https"
|
||||
port = parsed.port
|
||||
if port and not ((secure and port == 443) or (not secure and port == 80)):
|
||||
return f"{host}:{port}", secure
|
||||
return host, secure
|
||||
|
||||
|
||||
class FileAssetStorage:
|
||||
"""私有业务文件 MinIO 存储客户端。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""分别建立内网读写客户端与浏览器预签名客户端。
|
||||
|
||||
核心逻辑:两端点主机与协议相同时共用一个客户端。预签名客户端只在
|
||||
生成 URL 时做本地签名,不靠它访问内网 MinIO。
|
||||
"""
|
||||
endpoint = str(_cfg.MINIO_ENDPOINT or "").strip()
|
||||
access_key = _cfg.MINIO_ACCESS_KEY
|
||||
secret_key = _cfg.MINIO_SECRET_KEY
|
||||
secure = bool(_cfg.MINIO_SECURE)
|
||||
self.client = Minio(
|
||||
_cfg.MINIO_ENDPOINT,
|
||||
access_key=_cfg.MINIO_ACCESS_KEY,
|
||||
secret_key=_cfg.MINIO_SECRET_KEY,
|
||||
secure=_cfg.MINIO_SECURE,
|
||||
endpoint,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=secure,
|
||||
)
|
||||
# [STEP 1] 预签名单独用浏览器主机。只改 URL 字符串会使签名失效。
|
||||
presign_endpoint, presign_secure = resolve_presign_endpoint(
|
||||
str(_cfg.MINIO_PUBLIC_BASE_URL or ""),
|
||||
endpoint,
|
||||
secure,
|
||||
)
|
||||
if presign_endpoint == endpoint and presign_secure == secure:
|
||||
self.presign_client = self.client
|
||||
else:
|
||||
self.presign_client = Minio(
|
||||
presign_endpoint,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=presign_secure,
|
||||
)
|
||||
self.bucket_name = str(_cfg.MINIO_FILE_ASSETS_BUCKET or 'hxops-file-assets').strip()
|
||||
|
||||
def _ensure_bucket_exists(self) -> None:
|
||||
@@ -120,6 +182,19 @@ class FileAssetStorage:
|
||||
except S3Error:
|
||||
return False
|
||||
|
||||
def _bind_presign_region(self) -> None:
|
||||
"""把内网客户端已探到的 region 抄给预签名客户端。
|
||||
|
||||
核心逻辑:minio-py 在签名前会请求 GetBucketLocation。若用公网客户端发这次请求,
|
||||
容器里可能访问不到浏览器入口,或每次下载多一次公网探测。
|
||||
bucket 检查已经通过内网客户端写入 _region_map;这里只复用该结果。
|
||||
尚未探测到时用 MinIO 默认 us-east-1。
|
||||
"""
|
||||
if self.presign_client is self.client:
|
||||
return
|
||||
region = self.client._region_map.get(self.bucket_name) or "us-east-1"
|
||||
self.presign_client._region_map[self.bucket_name] = region
|
||||
|
||||
def presigned_get_url(
|
||||
self,
|
||||
storage_key: str,
|
||||
@@ -129,7 +204,9 @@ class FileAssetStorage:
|
||||
) -> str:
|
||||
"""生成短期受控下载 URL。
|
||||
|
||||
核心逻辑:对象键常为内容哈希,浏览器会把它当成保存名。
|
||||
核心逻辑:先把内网探到的 region 绑到 presign_client,再用它签名。
|
||||
主机来自 MINIO_PUBLIC_BASE_URL。签名在本地完成,不再向公网探测 bucket 区域。
|
||||
对象键常为内容哈希,浏览器会把它当成保存名。
|
||||
download_name 非空时把 response-content-disposition 签进 URL,
|
||||
让保存对话框使用业务文件名。预览地址不要传这个参数。
|
||||
|
||||
@@ -139,16 +216,17 @@ class FileAssetStorage:
|
||||
download_name: 附件保存名;只接受调用方已洗净的文件名。
|
||||
|
||||
Returns:
|
||||
带过期签名的 GET URL。
|
||||
带过期签名的 GET URL,主机是浏览器可访问的 MinIO 地址。
|
||||
"""
|
||||
self._ensure_bucket_exists()
|
||||
self._bind_presign_region()
|
||||
response_headers = None
|
||||
if download_name:
|
||||
safe = download_name.replace('"', '').replace('\\', '').replace('\r', '').replace('\n', '')
|
||||
response_headers = {
|
||||
'response-content-disposition': f'attachment; filename="{safe}"',
|
||||
}
|
||||
return self.client.presigned_get_object(
|
||||
return self.presign_client.presigned_get_object(
|
||||
self.bucket_name,
|
||||
storage_key,
|
||||
expires=timedelta(seconds=max(int(expires_seconds or 60), 60)),
|
||||
|
||||
@@ -3,8 +3,9 @@ services/freight_rpa/common/credential_crypto.py
|
||||
|
||||
用途:加密和解密库存 RPA Profile 的登录凭据(委托通用 core 模块,仅固定本域密钥键与错误码)。
|
||||
依赖:app.core.credential_crypto(Fernet 加解密);调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用
|
||||
decrypt_credential。主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;管理端读取 Profile 时只解密用户名用于展示;
|
||||
密码仅在 RPA 执行内存中调用 decrypt_credential。密码与密文不得进入 API 响应或日志。
|
||||
主密钥键 FREIGHT_RPA_CREDENTIAL_KEY(2026-09-18 RPA 命名空间)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -48,7 +49,7 @@ def decrypt_credential(ciphertext: str) -> str:
|
||||
ciphertext: 数据库中保存的 Fernet 密文。
|
||||
|
||||
Returns:
|
||||
str: 仅供 RPA 执行内存使用的明文。
|
||||
str: 明文。密码只留在 RPA 执行内存;用户名可由管理端 Profile 接口返回。禁止写入日志。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||
|
||||
@@ -44,6 +44,7 @@ from app.core.errors import NotFoundError
|
||||
from app.models import (
|
||||
FreightRpaInboundReportConfig,
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
FreightRpaOnhandReportConfig,
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
@@ -659,6 +660,72 @@ def latest_usable_inbound_file(
|
||||
return _inbound_file_view(report)
|
||||
|
||||
|
||||
def latest_usable_inbound_files_by_source(
|
||||
source_ids: list[int],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, InboundFileView]:
|
||||
"""一次取出这批来源各自最新的可用入站归档(来源状态批量投影用)。
|
||||
|
||||
用途:调拨 GET /sources 批量渲染来源卡时按批取文件身份,查询次数不随
|
||||
来源个数增长;口径与 latest_usable_inbound_file 完全一致(同一
|
||||
usable_inbound_file_condition 权威),只是按来源主键集合一次取回。
|
||||
|
||||
Args:
|
||||
source_ids: 来源主键集合(FreightRpaInboundUnitRun.source_id)。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
source_code → InboundFileView;没有可用文件的来源不出现,每个来源
|
||||
只留 created_at/id 最新一条。
|
||||
"""
|
||||
rows = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
.order_by(FreightRpaInboundReportFile.created_at.desc(), FreightRpaInboundReportFile.id.desc())
|
||||
.all()
|
||||
)
|
||||
picked: dict[str, InboundFileView] = {}
|
||||
for report in rows:
|
||||
view = _inbound_file_view(report)
|
||||
if view.source_code not in picked:
|
||||
picked[view.source_code] = view
|
||||
return picked
|
||||
|
||||
|
||||
def expired_inbound_source_codes(
|
||||
source_ids: list[int],
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> set[str]:
|
||||
"""一次找出仍有失效未清理入站归档的来源编码(expired 投影依据,存在性判断)。
|
||||
|
||||
用途:调拨来源状态批量投影判断哪些来源因隔日旧文件/保留期已到提示重抓;
|
||||
口径与 has_expired_inbound_file 同核(expired_inbound_file_condition)。
|
||||
|
||||
Args:
|
||||
source_ids: 来源主键集合。
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
至少有一份失效未清理入站归档的 source_code 集合。
|
||||
"""
|
||||
rows = (
|
||||
FreightRpaInboundReportFile.query
|
||||
.join(FreightRpaInboundReportFile.unit_run)
|
||||
.filter(
|
||||
FreightRpaInboundUnitRun.source_id.in_([int(i) for i in source_ids]),
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
.with_entities(FreightRpaInboundUnitRun.source_code)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return {str(row[0]) for row in rows}
|
||||
|
||||
|
||||
def read_inbound_file_bytes(file_id: int) -> bytes:
|
||||
"""按 file_id 读取入站归档文件的对象字节。
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
"""
|
||||
services/freight_rpa/upload/crane_recheck.py
|
||||
|
||||
用途:Crane 发货单进入分配中之后的状态回查。
|
||||
依赖:ShippingUploadAttempt、freight_rpa.upload.trigger_io、page_contract。
|
||||
逻辑:自动上传只排一次 10 分钟后的回查;手动刷新另写一条 status_check trigger,
|
||||
不顺延、不取消那一次定时。两条回查都只让 Worker 重新登录并按 Pull Request # 看行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingExportArtifact, ShippingNotice, ShippingUploadAttempt
|
||||
from app.services.freight_rpa.upload.page_contract import crane_recheck_due_at
|
||||
from app.services.freight_rpa.upload.trigger_io import write_upload_trigger
|
||||
|
||||
CRANE_ALLOCATING_CODE = 'CRANE_ALLOCATING'
|
||||
|
||||
|
||||
def is_crane_allocating(attempt: ShippingUploadAttempt | None) -> bool:
|
||||
"""当前尝试是否停在 Crane 已接收、尚未分配完成。"""
|
||||
return (
|
||||
attempt is not None
|
||||
and attempt.status == 'running'
|
||||
and attempt.error_code == CRANE_ALLOCATING_CODE
|
||||
)
|
||||
|
||||
|
||||
def _evidence(attempt: ShippingUploadAttempt) -> dict[str, Any]:
|
||||
raw = attempt.success_evidence_json
|
||||
return dict(raw) if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def _recheck(evidence: dict[str, Any]) -> dict[str, Any]:
|
||||
raw = evidence.get('crane_recheck')
|
||||
return dict(raw) if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def remember_crane_allocating(
|
||||
attempt: ShippingUploadAttempt,
|
||||
artifact: ShippingExportArtifact,
|
||||
callback_id: str,
|
||||
*,
|
||||
now: datetime | None = None,
|
||||
) -> ShippingUploadAttempt:
|
||||
"""把尝试标成分配中,并在首次进入时记下唯一一次定时回查。
|
||||
|
||||
核心逻辑:due_at 只在还没有时写入。后续回查回调仍是分配中时,不改到期时间,
|
||||
也不把定时标记成已触发。
|
||||
|
||||
Args:
|
||||
attempt: 本次上传尝试。
|
||||
artifact: 已提交的发货 Excel。
|
||||
callback_id: 本次回调幂等键。重复的同一个键直接返回。
|
||||
now: 测试注入的当前时间。
|
||||
|
||||
Returns:
|
||||
ShippingUploadAttempt: 仍为 running、错误码为 CRANE_ALLOCATING 的尝试。
|
||||
"""
|
||||
evidence = _evidence(attempt)
|
||||
if evidence.get('last_callback_id') == callback_id or attempt.callback_id == callback_id:
|
||||
return attempt
|
||||
recheck = _recheck(evidence)
|
||||
if not recheck.get('due_at'):
|
||||
pull_request_no = str(artifact.file_name or '').rsplit('.', 1)[0] or str(artifact.file_name or '')
|
||||
recheck = {
|
||||
'due_at': crane_recheck_due_at(now).isoformat(timespec='seconds'),
|
||||
'fired': False,
|
||||
'pull_request_no': pull_request_no,
|
||||
}
|
||||
evidence['crane_recheck'] = recheck
|
||||
evidence['last_callback_id'] = callback_id
|
||||
evidence['manual_refresh_inflight'] = False
|
||||
attempt.success_evidence_json = evidence
|
||||
attempt.status = 'running'
|
||||
attempt.error_code = CRANE_ALLOCATING_CODE
|
||||
attempt.error_message = None
|
||||
attempt.finished_at = None
|
||||
if not attempt.callback_id:
|
||||
attempt.callback_id = callback_id
|
||||
artifact.status = 'uploading'
|
||||
db.session.flush()
|
||||
return attempt
|
||||
|
||||
|
||||
def _write_status_check(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
pull_request_no: str,
|
||||
kind: str,
|
||||
) -> str | None:
|
||||
"""写入一条只查状态的上传 trigger。文件复制失败时返回 None。"""
|
||||
# 定时回查的回调键固定,重复心跳不会写成两次有效回调。
|
||||
# 手动刷新每次使用新键,避免上一次「仍在分配」把这一次回调当成重复而跳过。
|
||||
callback_id = f'crane-recheck:{attempt.id}:scheduled'
|
||||
trigger_filename = f'upload_recheck_{task_no}_scheduled.json'
|
||||
if kind == 'manual':
|
||||
callback_id = f'crane-recheck:{attempt.id}:manual:{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||
trigger_filename = f'upload_recheck_{task_no}_manual.json'
|
||||
_queue, trigger_path, _callback = write_upload_trigger(
|
||||
task_no,
|
||||
export_file_path,
|
||||
{'mode': 'status_check', 'recheck_kind': kind, 'pull_request_no': pull_request_no},
|
||||
attempt_id=int(attempt.id),
|
||||
artifact_id=int(attempt.artifact_id),
|
||||
connector_type='crane',
|
||||
upload_config={'enabled': True},
|
||||
login_url=str(upload_source.get('login_url') or '').strip() or None,
|
||||
credential_envelope=upload_source.get('credential_envelope') if isinstance(upload_source.get('credential_envelope'), dict) else None,
|
||||
callback_id=callback_id,
|
||||
business_no=pull_request_no,
|
||||
trigger_filename=trigger_filename,
|
||||
)
|
||||
return trigger_path
|
||||
|
||||
|
||||
def fire_scheduled_crane_recheck(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
now: datetime | None = None,
|
||||
) -> bool:
|
||||
"""到期后写入唯一一次定时回查。未到期、已触发或不是分配中时不写文件。
|
||||
|
||||
Returns:
|
||||
bool: 本次是否新写了 trigger。
|
||||
"""
|
||||
if not is_crane_allocating(attempt):
|
||||
return False
|
||||
evidence = _evidence(attempt)
|
||||
recheck = _recheck(evidence)
|
||||
if recheck.get('fired') or not recheck.get('due_at'):
|
||||
return False
|
||||
due_at = datetime.fromisoformat(str(recheck['due_at']))
|
||||
if due_at > (now or datetime.utcnow()):
|
||||
return False
|
||||
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||
trigger_path = _write_status_check(
|
||||
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||
pull_request_no=pull_request_no, kind='scheduled',
|
||||
)
|
||||
if not trigger_path:
|
||||
return False
|
||||
recheck['fired'] = True
|
||||
evidence['crane_recheck'] = recheck
|
||||
attempt.success_evidence_json = evidence
|
||||
db.session.flush()
|
||||
return True
|
||||
|
||||
|
||||
def request_manual_crane_refresh(
|
||||
attempt: ShippingUploadAttempt,
|
||||
upload_source: dict[str, Any],
|
||||
*,
|
||||
task_no: str,
|
||||
export_file_path: str,
|
||||
) -> str:
|
||||
"""手动刷新:立刻写一条状态回查,不改定时回查的到期时间和已触发标记。
|
||||
|
||||
Raises:
|
||||
ConflictError: 当前不是分配中,或上一次手动刷新还没回调。
|
||||
ValidationError: 共享目录写不出 trigger。
|
||||
"""
|
||||
if not is_crane_allocating(attempt):
|
||||
raise ConflictError(
|
||||
'Crane upload is not waiting for allocation',
|
||||
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
|
||||
)
|
||||
evidence = _evidence(attempt)
|
||||
if evidence.get('manual_refresh_inflight'):
|
||||
raise ConflictError(
|
||||
'A Crane status refresh is already queued',
|
||||
code='SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT',
|
||||
)
|
||||
recheck = _recheck(evidence)
|
||||
pull_request_no = str(recheck.get('pull_request_no') or '').strip()
|
||||
due_at = recheck.get('due_at')
|
||||
fired = bool(recheck.get('fired'))
|
||||
trigger_path = _write_status_check(
|
||||
attempt, upload_source, task_no=task_no, export_file_path=export_file_path,
|
||||
pull_request_no=pull_request_no, kind='manual',
|
||||
)
|
||||
if not trigger_path:
|
||||
raise ValidationError(
|
||||
'Crane status refresh trigger directory is unavailable',
|
||||
code='SHIPPING.UPLOAD_TRIGGER_UNAVAILABLE',
|
||||
)
|
||||
evidence['manual_refresh_inflight'] = True
|
||||
evidence['crane_recheck'] = {**recheck, 'due_at': due_at, 'fired': fired, 'pull_request_no': pull_request_no}
|
||||
attempt.success_evidence_json = evidence
|
||||
db.session.flush()
|
||||
return trigger_path
|
||||
|
||||
|
||||
def materialize_due_crane_rechecks(now: datetime | None = None) -> int:
|
||||
"""心跳时把已到期且尚未触发的 Crane 定时回查写成 trigger。
|
||||
|
||||
Returns:
|
||||
int: 新写入的 trigger 数量。
|
||||
"""
|
||||
from app.services.shipping_notice.onhand_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
moment = now or datetime.utcnow()
|
||||
written = 0
|
||||
attempts = ShippingUploadAttempt.query.filter_by(status='running', error_code=CRANE_ALLOCATING_CODE).all()
|
||||
for attempt in attempts:
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
|
||||
notice = db.session.get(ShippingNotice, artifact.task_id) if artifact is not None else None
|
||||
if artifact is None or notice is None or not artifact.file_path:
|
||||
continue
|
||||
from app.services.shipping_notice.onhand_source_rules import task_rpa_inventory_source
|
||||
|
||||
snapshot = task_rpa_inventory_source(notice) or {}
|
||||
source_code = str(snapshot.get('source_code') or '').strip()
|
||||
upload_source = get_rpa_trigger_inventory_source(source_code) if source_code else None
|
||||
if not isinstance(upload_source, dict) or str(upload_source.get('connector_type') or '').lower() != 'crane':
|
||||
continue
|
||||
if fire_scheduled_crane_recheck(
|
||||
attempt, upload_source, task_no=str(notice.task_no),
|
||||
export_file_path=str(artifact.file_path), now=moment,
|
||||
):
|
||||
written += 1
|
||||
if written:
|
||||
db.session.commit()
|
||||
return written
|
||||
@@ -0,0 +1,68 @@
|
||||
"""
|
||||
services/freight_rpa/upload/page_contract.py
|
||||
|
||||
用途:货代发货 Excel 上传的平台页面契约。入口路径、文件控件和成功条件由代码固定。
|
||||
依赖:标准库 urllib。
|
||||
逻辑:系统连接只保存是否启用自动上传;Worker 用登录地址的主机拼出上传页。
|
||||
DBS 上传后当页即可判定;Crane 先进入分配中,10 分钟后再查一次。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
CRANE_RECHECK_DELAY = timedelta(minutes=10)
|
||||
DBS_UPLOAD_PATH = '/main/portal/frame/WMSUpload2'
|
||||
CRANE_UPLOAD_HASH = '/#/shipping-order-upload'
|
||||
|
||||
|
||||
def build_upload_entry_url(connector_type: str, login_url: str) -> str:
|
||||
"""按平台把登录地址的主机拼成上传页。
|
||||
|
||||
核心逻辑:页面路径属于连接器代码。管理端不再保存上传入口 URL。
|
||||
|
||||
Args:
|
||||
connector_type: dbs 或 crane。
|
||||
login_url: 系统连接上的 HTTPS 登录地址。
|
||||
|
||||
Returns:
|
||||
str: 该平台固定上传页。
|
||||
|
||||
Raises:
|
||||
ValueError: 连接类型或登录地址无法构成上传页。
|
||||
"""
|
||||
kind = str(connector_type or '').strip().lower()
|
||||
parsed = urlsplit(str(login_url or '').strip())
|
||||
host = parsed.netloc.strip()
|
||||
if parsed.scheme.lower() != 'https' or not host or not parsed.hostname:
|
||||
raise ValueError('login_url must be HTTPS with a host')
|
||||
if kind == 'dbs':
|
||||
return f'https://{host}{DBS_UPLOAD_PATH}'
|
||||
if kind == 'crane':
|
||||
return f'https://{host}{CRANE_UPLOAD_HASH}'
|
||||
raise ValueError(f'unsupported connector_type: {connector_type or "<empty>"}')
|
||||
|
||||
|
||||
def classify_crane_order_row(order_status: str, order_status_description: str) -> str:
|
||||
"""判断 Crane 发货单行处于分配中、已分配,还是都不是。
|
||||
|
||||
Args:
|
||||
order_status: Order Status 列文本。
|
||||
order_status_description: Order Status Description 列文本。
|
||||
|
||||
Returns:
|
||||
str: allocated、allocating 或 other。
|
||||
"""
|
||||
status = ' '.join(str(order_status or '').split()).lower()
|
||||
description = ' '.join(str(order_status_description or '').split()).lower()
|
||||
if status == 'processing' and description == 'shipping order allocated':
|
||||
return 'allocated'
|
||||
if status == 'processing' and description == 'allocating the shipping order':
|
||||
return 'allocating'
|
||||
return 'other'
|
||||
|
||||
|
||||
def crane_recheck_due_at(now: datetime | None = None) -> datetime:
|
||||
"""自动上传进入分配中之后,唯一一次定时回查的到期时间。"""
|
||||
return (now or datetime.utcnow()) + CRANE_RECHECK_DELAY
|
||||
@@ -76,6 +76,7 @@ def write_upload_trigger(
|
||||
credential_envelope: dict[str, Any] | None = None,
|
||||
callback_id: str | None = None,
|
||||
business_no: str | None = None,
|
||||
trigger_filename: str | None = None,
|
||||
) -> tuple[str | None, str | None, str | None]:
|
||||
"""
|
||||
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
|
||||
@@ -84,7 +85,7 @@ def write_upload_trigger(
|
||||
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
|
||||
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
|
||||
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
|
||||
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
|
||||
平台页面动作由 Worker 连接器代码固定;upload_config 只携带是否启用自动上传。
|
||||
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
|
||||
|
||||
Args:
|
||||
@@ -100,6 +101,7 @@ def write_upload_trigger(
|
||||
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
|
||||
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
|
||||
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
|
||||
trigger_filename: 触发文件名。状态回查使用独立文件名,避免覆盖正在上传的 trigger。
|
||||
|
||||
Returns:
|
||||
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
|
||||
@@ -113,14 +115,21 @@ def write_upload_trigger(
|
||||
trigger_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
src = Path(export_file_path)
|
||||
if not src.is_file():
|
||||
status_check = str((payload or {}).get('mode') or '') == 'status_check'
|
||||
if not src.is_file() and not status_check:
|
||||
return None, None, None
|
||||
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
|
||||
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
|
||||
emit_no = str(business_no or '').strip() or task_no
|
||||
suffix = str(src.suffix or '.xlsx').lower()
|
||||
dest = queue / f"{emit_no}{suffix}"
|
||||
shutil.copy2(src, dest)
|
||||
if src.is_file():
|
||||
shutil.copy2(src, dest)
|
||||
queued_file = str(dest)
|
||||
elif status_check:
|
||||
queued_file = ''
|
||||
else:
|
||||
return None, None, None
|
||||
|
||||
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
|
||||
body = {
|
||||
@@ -135,10 +144,10 @@ def write_upload_trigger(
|
||||
"upload_config_hash": upload_config_hash,
|
||||
"login_url": login_url,
|
||||
"credential_envelope": credential_envelope,
|
||||
"file_path": str(dest),
|
||||
"file_path": queued_file,
|
||||
"requested_at": datetime.utcnow().isoformat(),
|
||||
**(payload or {}),
|
||||
}
|
||||
trigger_path = trigger_dir / f"upload_{task_no}.json"
|
||||
trigger_path = trigger_dir / (trigger_filename or f"upload_{task_no}.json")
|
||||
_write_trigger_json_atomic(trigger_path, body)
|
||||
return str(dest), str(trigger_path), resolved_callback_id
|
||||
@@ -36,6 +36,7 @@ from app.models import TransferAttempt, TransferInvoiceItem, TransferMovementLed
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
circle_ledger_record_ids_scope_union,
|
||||
pending_ledger_query,
|
||||
ledger_external_doc_no,
|
||||
transfer_type_code_of,
|
||||
)
|
||||
from app.services.in_transit_transfer.status import TransferStatus
|
||||
@@ -100,6 +101,8 @@ class BacklogItemDTO:
|
||||
result_code: Optional[str] = None
|
||||
# 出生匹配快照上的调拨类型 code。空串表示行没有匹配或快照未写类型。
|
||||
transfer_type: str = ""
|
||||
# 档上的外部单号。空串表示这行没有外部单号。
|
||||
external_doc_no: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -207,7 +210,7 @@ def _latest_attempt_times(item_ids: list[int]) -> dict[int, datetime]:
|
||||
def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: str | None = None):
|
||||
"""待处理池基础查询(状态集合 + 可选来源/关键字过滤)。
|
||||
|
||||
keyword 与前端池内筛选同字段集(Invoice/料号/品名/来源,2026-10-16 随
|
||||
keyword 与前端池内筛选同字段集(单号/外部单号/料号/品名/来源,2026-10-16 随
|
||||
服务端分页下推),大小写不敏感子串匹配(ilike)。
|
||||
|
||||
Args:
|
||||
@@ -222,12 +225,19 @@ def _backlog_base_query(statuses, *, source_code: str | None = None, keyword: st
|
||||
query = query.filter_by(source_code=source_code)
|
||||
if keyword:
|
||||
like = f"%{keyword}%"
|
||||
query = query.filter(or_(
|
||||
TransferInvoiceItem.invoice_no.ilike(like),
|
||||
TransferInvoiceItem.material_no.ilike(like),
|
||||
TransferInvoiceItem.material_name.ilike(like),
|
||||
TransferInvoiceItem.source_code.ilike(like),
|
||||
))
|
||||
query = (
|
||||
query.outerjoin(
|
||||
TransferMovementLedger,
|
||||
TransferInvoiceItem.ledger_record_id == TransferMovementLedger.id,
|
||||
)
|
||||
.filter(or_(
|
||||
TransferInvoiceItem.invoice_no.ilike(like),
|
||||
TransferMovementLedger.external_doc_no.ilike(like),
|
||||
TransferInvoiceItem.material_no.ilike(like),
|
||||
TransferInvoiceItem.material_name.ilike(like),
|
||||
TransferInvoiceItem.source_code.ilike(like),
|
||||
))
|
||||
)
|
||||
return query
|
||||
|
||||
|
||||
@@ -266,6 +276,7 @@ def _backlog_dtos(rows: list[TransferInvoiceItem], current: datetime) -> list[Ba
|
||||
item_id=item.id,
|
||||
source_code=item.source_code,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
material_no=item.material_no,
|
||||
status=item.status,
|
||||
reason=item.result_message or item.result_code or "",
|
||||
@@ -303,7 +314,10 @@ def list_backlog(*, now: datetime | None = None, source_code: str | None = None)
|
||||
current = now or datetime.utcnow()
|
||||
rows = (
|
||||
_backlog_base_query(_ALL_BACKLOG_STATUSES, source_code=source_code)
|
||||
.options(joinedload(TransferInvoiceItem.matching))
|
||||
.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.all()
|
||||
)
|
||||
@@ -330,7 +344,7 @@ def list_backlog_page(
|
||||
Args:
|
||||
now: 判定时刻(默认当前时间)。
|
||||
source_code: 可选来源过滤。
|
||||
keyword: 可选关键字(Invoice/料号/品名/来源,子串大小写不敏感)。
|
||||
keyword: 可选关键字(单号/外部单号/料号/品名/来源,子串大小写不敏感)。
|
||||
result_filter: 结果切片(all/recoverable/closed/unknown)。
|
||||
page: 页码(1 起)。
|
||||
page_size: 每页行数(1..100)。
|
||||
@@ -345,7 +359,10 @@ def list_backlog_page(
|
||||
base = _backlog_base_query(statuses, source_code=source_code, keyword=keyword or None)
|
||||
total = base.count()
|
||||
rows = (
|
||||
base.options(joinedload(TransferInvoiceItem.matching))
|
||||
base.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
.order_by(*_BACKLOG_ORDER_BY)
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
|
||||
@@ -124,6 +124,8 @@ class MatchingItemDTO:
|
||||
# 出生匹配快照上的调拨类型 code。可调拨明细跨类型混排时用来展示类别;
|
||||
# 无匹配或快照未写类型时为空串。
|
||||
transfer_type: str = ""
|
||||
# 档上的外部单号(WMS Order #)。空串表示这行没有外部单号。
|
||||
external_doc_no: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
||||
@@ -63,6 +63,7 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
item_external_lot_no,
|
||||
ledger_external_doc_no,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
from app.services.in_transit_transfer.orchestrator import (
|
||||
@@ -805,12 +806,12 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
ERP 行粒度 = 物料+批号:同单同料号同批号跨 Invoice 聚合为一行,数量按
|
||||
Decimal 精确相加后取 6 位小数;客户端行数量为数值型(能力 Schema number,
|
||||
且须可 JSON 序列化进引擎审计),快照文本(6 位小数字符串)随 D14 留档。
|
||||
行内附带 invoice_no 溯源(逗号连接,供测试替身/排障;ERP 契约无此字段,
|
||||
真实绑定未映射即透传为惰性键)。
|
||||
行内附带 invoice_no 与 external_doc_no 溯源(各自逗号连接,供清单展示与排障;
|
||||
ERP 契约无这两字段,真实绑定未映射即透传为惰性键)。
|
||||
|
||||
Returns:
|
||||
行 dict 列表:line_no/material_no/from_warehouse/to_warehouse/lot_no/
|
||||
quantity/unit/invoice_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
||||
quantity/unit/invoice_no/external_doc_no/quantity_text(quantity_text 仅供快照,调用方裁剪)。
|
||||
"""
|
||||
grouped: dict[tuple[str, str, str, str], list[TransferInvoiceItem]] = {}
|
||||
for item in items:
|
||||
@@ -831,6 +832,9 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
quantity = total.quantize(_QUANTITY_QUANT)
|
||||
unit = next((str(item.unit or "").strip() for item in group if str(item.unit or "").strip()), "")
|
||||
invoices = ",".join(sorted({item.invoice_no for item in group}))
|
||||
external_docs = ",".join(sorted({
|
||||
doc for item in group if (doc := ledger_external_doc_no(item))
|
||||
}))
|
||||
lines.append({
|
||||
"line_no": index,
|
||||
"material_no": key[0],
|
||||
@@ -840,6 +844,7 @@ def _build_order_lines(items: list[TransferInvoiceItem]) -> list[dict]:
|
||||
"quantity": float(quantity),
|
||||
"unit": unit,
|
||||
"invoice_no": invoices,
|
||||
"external_doc_no": external_docs,
|
||||
"quantity_text": f"{quantity:.6f}",
|
||||
})
|
||||
return lines
|
||||
@@ -1273,6 +1278,7 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
movement_date=item.movement_date,
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
movement_date 非空)+ 类型快照范围规则(apply_scope_filters 单一编译器)+
|
||||
未被有效 items 占用(D17:ledger_record_id 引用或同匹配 grain
|
||||
(source, invoice/doc_no, material, movement_date) 已被有效 item 占用;
|
||||
取消匹配即释放)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
|
||||
取消匹配即释放;ADR 0007 匹配顶替在圈档前取消被新范围盖住、尚未写 ERP 的旧匹配)。tt14 档自然键扩维后同 grain 可对应多条档(如 carton
|
||||
空→有值的重解析双行);出生前按 grain 择一建 item(不累加数量,防翻倍),
|
||||
占用亦按 grain 互斥。业务字段=档原值;仓库经 resolve_warehouse;库存评估
|
||||
链以 items 为工作单元。create_matching 先落 Run + Matching 再驱动管道。
|
||||
@@ -295,11 +295,12 @@ def _dedupe_ledger_records_for_item_birth(
|
||||
def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
"""构造「未被有效 items 占用」(D17)的 NOT EXISTS 过滤(圈档互斥单一口径)。
|
||||
|
||||
占用定义(规格 §9 + grain 互斥):存在有效 item(所属匹配未取消、行非
|
||||
blocked_file_removed)且满足其一——(a) ledger_record_id 直指本档;
|
||||
(b) 与本档同匹配 grain(source/invoice=doc_no/material/movement_date)。
|
||||
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档,避免待匹配桶与二次
|
||||
匹配仍圈到兄弟档。取消匹配即释放;人工关闭/成功终态不释放。
|
||||
占用定义(规格 §9 + grain 互斥 + ADR 0007):存在已挂上匹配的有效 item
|
||||
(所属匹配未取消,或该行是人工关闭;行非 blocked_file_removed)且满足其一
|
||||
——(a) ledger_record_id 直指本档;(b) 与本档同匹配 grain
|
||||
(source/invoice=doc_no/material/movement_date)。没有挂上匹配的明细不占用。
|
||||
(b) 覆盖 tt14 自然键扩维后同业务 grain 的镜像分叉档。取消匹配即释放,
|
||||
人工关闭除外;成功终态不释放。
|
||||
|
||||
Args:
|
||||
exclude_matching_id: 重查对账场景传入本匹配 id——本匹配自有 items 不构成
|
||||
@@ -308,9 +309,8 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
SQLAlchemy NOT EXISTS 子句(作用于 TransferMovementLedger 查询)。
|
||||
"""
|
||||
# material_code 可空:COALESCE 与出生侧 ``material_code or ""`` 对齐。
|
||||
# grain 互斥只认「已绑定未取消匹配」的行——出生翻转前 matching_id=NULL 的
|
||||
# 历史孤儿行不得按 grain 封死整票待匹配(本地曾因此从 ~2k 掉到 5)。
|
||||
# ledger_record_id 直指占用仍含 NULL 归属行(保持 D17 原口径)。
|
||||
# 【ADR 0007】没有挂上匹配的明细不占货(直指与 grain 都不算)。
|
||||
# 人工关闭在所属匹配被顶替之后仍然占用。
|
||||
grain_match = and_(
|
||||
TransferInvoiceItem.matching_id.isnot(None),
|
||||
TransferInvoiceItem.source_code == TransferMovementLedger.source_code,
|
||||
@@ -328,17 +328,21 @@ def _effective_occupancy_filter(*, exclude_matching_id: int | None = None):
|
||||
TransferInvoiceItem.result_code != RESULT_FILE_REMOVED),
|
||||
]
|
||||
if exclude_matching_id is None:
|
||||
# 匹配创建:任何未取消匹配(含无归属的历史行)的有效引用都算占用。
|
||||
# 匹配创建:必须已挂上匹配。未取消的匹配占用;人工关闭在匹配被顶替后仍占用。
|
||||
item_conditions.append(TransferInvoiceItem.matching_id.isnot(None))
|
||||
item_conditions.append(or_(
|
||||
TransferInvoiceItem.matching_id.is_(None),
|
||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
))
|
||||
else:
|
||||
# 重查对账:仅「其他匹配」的有效引用算占用(本匹配自有 items 允许刷新)。
|
||||
item_conditions.append(and_(
|
||||
TransferInvoiceItem.matching_id.isnot(None),
|
||||
TransferInvoiceItem.matching_id != exclude_matching_id,
|
||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||
or_(
|
||||
TransferMatching.status != _MATCHING_STATUS_CANCELLED,
|
||||
TransferInvoiceItem.status == status_machine.TransferStatus.MANUALLY_CLOSED.value,
|
||||
),
|
||||
))
|
||||
occupancy = (
|
||||
db.session.query(TransferInvoiceItem.id)
|
||||
@@ -611,6 +615,23 @@ def matching_transform_rules(matching: TransferMatching) -> tuple[TransformRule,
|
||||
return parse_transform_rules(scope.get("transform_rules"))
|
||||
|
||||
|
||||
def ledger_external_doc_no(item: TransferInvoiceItem) -> str:
|
||||
"""读取明细行对应异动档上的外部单号。
|
||||
|
||||
核心逻辑:外部单号只在档上(WMS Order #),明细行经 ledger_record_id 指向档。
|
||||
没有档、或档上为空时返回空串,列表显示占位。
|
||||
|
||||
Args:
|
||||
item: 明细行。ledger_record 可已预加载;未预加载时按外键懒加载。
|
||||
Returns:
|
||||
外部单号;没有则空串。
|
||||
"""
|
||||
record = item.ledger_record
|
||||
if record is None:
|
||||
return ""
|
||||
return str(record.external_doc_no or "").strip()
|
||||
|
||||
|
||||
def item_external_lot_no(item: TransferInvoiceItem) -> str:
|
||||
"""行批号的外部形态派生(按行所属匹配快照的转换规则;无规则=恒等)。
|
||||
|
||||
@@ -1242,6 +1263,116 @@ def _item_evaluated_sha(item: TransferInvoiceItem) -> str | None:
|
||||
return lines[0].get("file_sha256")
|
||||
|
||||
|
||||
def _source_set(codes: list[str] | None) -> tuple[str, ...]:
|
||||
"""把来源编码收成可比较的集合。
|
||||
|
||||
核心逻辑:去掉空白后排序,使 [B, A] 与 [A, B] 视为同一组来源。
|
||||
Args:
|
||||
codes: 来源编码列表;None 当空。
|
||||
Returns:
|
||||
排序后的来源编码元组。
|
||||
"""
|
||||
return tuple(sorted(str(code).strip() for code in (codes or []) if str(code).strip()))
|
||||
|
||||
|
||||
def _date_range_covers(new_from: str | None, new_to: str | None, old_from: str | None, old_to: str | None) -> bool:
|
||||
"""新异动日期范围是否把旧范围整个盖住。
|
||||
|
||||
核心逻辑:任一侧缺少起或止,都视为没盖住(无日期范围的旧匹配不被顶替)。
|
||||
日期是 YYYY-MM-DD,字符串序与日历序一致。
|
||||
Args:
|
||||
new_from / new_to: 本次匹配的异动日期起止。
|
||||
old_from / old_to: 旧匹配快照上的异动日期起止。
|
||||
Returns:
|
||||
新范围包含旧范围时为 True。
|
||||
"""
|
||||
if not new_from or not new_to or not old_from or not old_to:
|
||||
return False
|
||||
return str(new_from) <= str(old_from) and str(new_to) >= str(old_to)
|
||||
|
||||
|
||||
def _matching_has_erp_activity(items: list[TransferInvoiceItem]) -> bool:
|
||||
"""匹配是否已经写出单据,或有行正在写、结果未知。
|
||||
|
||||
核心逻辑:有外部单号,或行状态为执行中、结果未知、成功,就不顶替,
|
||||
避免把在途 ERP 写入拆成两张单。
|
||||
Args:
|
||||
items: 该匹配名下的明细。
|
||||
Returns:
|
||||
存在上述活动时为 True。
|
||||
"""
|
||||
active = {
|
||||
status_machine.TransferStatus.EXECUTING.value,
|
||||
status_machine.TransferStatus.RESULT_UNKNOWN.value,
|
||||
status_machine.TransferStatus.SUCCESS.value,
|
||||
status_machine.TransferStatus.DUPLICATE_SUCCESS.value,
|
||||
}
|
||||
return any(
|
||||
(item.external_document_no or "").strip() or item.status in active
|
||||
for item in items
|
||||
)
|
||||
|
||||
|
||||
def _supersede_covered_matchings(
|
||||
*,
|
||||
transfer_type: str,
|
||||
source_codes: list[str],
|
||||
movement_date_from: str | None,
|
||||
movement_date_to: str | None,
|
||||
exclude_matching_id: int,
|
||||
) -> None:
|
||||
"""圈档前顶替被新范围盖住、尚未写 ERP 的旧匹配(ADR 0007)。
|
||||
|
||||
核心逻辑:同一调拨类型、同一组来源、旧日期范围被新范围整个盖住,且名下没有
|
||||
ERP 单据、没有正在写或结果未知的行,则匹配改为 cancelled,名下明细一并取消。
|
||||
盖不住或已在写 ERP 的旧匹配保持原样,清单不列举它们的编号。
|
||||
|
||||
Args:
|
||||
transfer_type: 本次匹配的调拨类型编码。
|
||||
source_codes: 本次来源集合。
|
||||
movement_date_from / movement_date_to: 本次异动日期范围;缺一则不顶替任何人。
|
||||
exclude_matching_id: 刚落库、尚未圈档的本次匹配,不能把自己顶掉。
|
||||
"""
|
||||
new_sources = _source_set(source_codes)
|
||||
if not new_sources:
|
||||
return
|
||||
candidates = (
|
||||
TransferMatching.query
|
||||
.filter(TransferMatching.id != exclude_matching_id)
|
||||
.filter(TransferMatching.status != _MATCHING_STATUS_CANCELLED)
|
||||
.all()
|
||||
)
|
||||
for matching in candidates:
|
||||
scope = matching.scope_json if isinstance(matching.scope_json, dict) else {}
|
||||
if str(scope.get("transfer_type") or "") != transfer_type:
|
||||
continue
|
||||
if _source_set(scope.get("source_codes")) != new_sources:
|
||||
continue
|
||||
items = TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||
covered = _date_range_covers(
|
||||
movement_date_from,
|
||||
movement_date_to,
|
||||
scope.get("movement_date_from"),
|
||||
scope.get("movement_date_to"),
|
||||
)
|
||||
# 匹配状态 success 只表示没有可执行行(全阻断也会落成 success),
|
||||
# 不能当成已经写出 ERP。是否写过只看行上的单据号和执行状态。
|
||||
if (
|
||||
not covered
|
||||
or matching.status == status_machine.TransferStatus.EXECUTING.value
|
||||
or _matching_has_erp_activity(items)
|
||||
):
|
||||
continue
|
||||
matching.status = _MATCHING_STATUS_CANCELLED
|
||||
for item in items:
|
||||
# 人工关闭是仓库人员的裁定,顶替不把它改回可圈状态。
|
||||
if item.status == status_machine.TransferStatus.MANUALLY_CLOSED.value:
|
||||
continue
|
||||
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||
item.result_code = "cancelled"
|
||||
item.result_message = "superseded by a new matching"
|
||||
|
||||
|
||||
def create_matching(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
@@ -1259,6 +1390,7 @@ def create_matching(
|
||||
管道回写 status/counts/estimated/hash 后随主事务统一提交。类型必填且配置
|
||||
驱动(REQUIRED/NOT_CONFIGURED/DISABLED fail-closed,D8)。圈档记录类型由
|
||||
run_matching 对已加载的 scope_rules 调用 record_kinds_of,不再写死入站。
|
||||
【ADR 0007】圈档前顶替被本次日期范围盖住、尚未写 ERP 的同类型同来源旧匹配。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_matching。
|
||||
@@ -1299,6 +1431,14 @@ def create_matching(
|
||||
)
|
||||
db.session.add(matching)
|
||||
db.session.flush()
|
||||
# [ADR 0007] 先释放被盖住的旧匹配,本次圈档才能看到那批货。
|
||||
_supersede_covered_matchings(
|
||||
transfer_type=config.code,
|
||||
source_codes=list(source_codes),
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
exclude_matching_id=matching.id,
|
||||
)
|
||||
|
||||
result = run_matching(
|
||||
source_codes=source_codes,
|
||||
@@ -1404,6 +1544,7 @@ def restore_matching(
|
||||
# 同口径(2026-09-29 统一),同一批行在匹配卡/可调拨明细/待处理池顺序一致。
|
||||
rows_all = (
|
||||
TransferInvoiceItem.query
|
||||
.options(joinedload(TransferInvoiceItem.ledger_record))
|
||||
.filter(TransferInvoiceItem.matching_id == matching.id)
|
||||
.order_by(
|
||||
TransferInvoiceItem.movement_date.asc().nulls_last(),
|
||||
@@ -1531,6 +1672,7 @@ def _item_dto(
|
||||
material_name=item.material_name,
|
||||
specification=item.specification,
|
||||
invoice_no=item.invoice_no,
|
||||
external_doc_no=ledger_external_doc_no(item),
|
||||
movement_date=item.movement_date,
|
||||
lot_no=item.lot_no or "",
|
||||
movement_warehouse_code=item.movement_warehouse_code or "",
|
||||
@@ -1600,7 +1742,10 @@ def list_executable_items(*, deps: TransferDeps | None = None, now: datetime | N
|
||||
# 2026-09-29 与待处理池/匹配卡视图统一为同一口径(用户按同序处理两个池子)。
|
||||
rows = (
|
||||
TransferInvoiceItem.query
|
||||
.options(joinedload(TransferInvoiceItem.matching))
|
||||
.options(
|
||||
joinedload(TransferInvoiceItem.matching),
|
||||
joinedload(TransferInvoiceItem.ledger_record),
|
||||
)
|
||||
# [防御性双保险] 所属匹配已取消的行不入队:取消路径已把匹配名下 ready
|
||||
# 行退役为 cancelled(cancellation.py),此处按匹配状态再拒一次——
|
||||
# 防绕过取消路径的状态组合(如手工改库/历史数据)产生可执行行。
|
||||
|
||||
@@ -12,7 +12,10 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.in_transit_transfer.matching_service import item_external_lot_no
|
||||
from app.services.in_transit_transfer.matching_service import (
|
||||
item_external_lot_no,
|
||||
ledger_external_doc_no,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 单状态 → 展示分组映射(Task 17:首页「已执行」区块统计口径)
|
||||
@@ -71,6 +74,7 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
"material_name": item.material_name,
|
||||
"specification": item.specification,
|
||||
"invoice_no": item.invoice_no,
|
||||
"external_doc_no": getattr(item, "external_doc_no", "") or "",
|
||||
"lot_no": item.lot_no,
|
||||
"movement_date": item.movement_date,
|
||||
"from_warehouse": item.from_warehouse,
|
||||
@@ -177,6 +181,7 @@ def serialize_order(doc, items: list) -> dict[str, Any]:
|
||||
# 行级溯源来源单号(2026-09-29 契约扩充,随 ERP 写入行同款口径
|
||||
# 透传):业务上一行恒对应一张 invoice,前端明细表首列展示。
|
||||
"invoice_no": line["invoice_no"],
|
||||
"external_doc_no": line.get("external_doc_no") or "",
|
||||
"material_no": line["material_no"],
|
||||
"material_name": name_by_key.get(
|
||||
(line["material_no"], line["lot_no"],
|
||||
@@ -222,6 +227,7 @@ def serialize_executed_order(doc, items: list) -> dict[str, Any]:
|
||||
"items": [
|
||||
{
|
||||
"invoice_no": item.invoice_no,
|
||||
"external_doc_no": ledger_external_doc_no(item),
|
||||
"material_no": item.material_no,
|
||||
"material_name": item.material_name,
|
||||
# 批号保持文件证据原形态(raw 原则);展示侧拨出批号由前端
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
按来源实例与记录类型投影"是否有 ready 文件 / 是否抓取中 / 是否失败 /
|
||||
是否解析失败 / 无文件待触发 / 出站未配置",供 /sources 接口与前端门禁使用。
|
||||
调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:freight_rpa.reports.queries(入站最新可用归档 / 失效存在性 /
|
||||
get_outbound_config,以及解析失败标记的只读写入口);入站与出站执行单元行、
|
||||
出站归档文件模型;date_policy.business_date_utc_window(出站文件新鲜度与
|
||||
入站可用条件同口径)。
|
||||
依赖:freight_rpa.reports.queries(入站可用归档批量/单来源读取、失效来源存在性、
|
||||
get_outbound_config、解析失败标记只读写入口;入站归档文件模型不直连——
|
||||
阶段 B Task 4 边界);入站/出站执行单元行与出站归档文件、出站报表配置模型
|
||||
(出站证据轴 2026-10-22 起直连读取,不在边界禁列);
|
||||
date_policy.business_date_utc_window(出站文件新鲜度与入站可用条件同口径)。
|
||||
逻辑:resolve_source_file_status 按 record_kind 分流,缺省 inbound,既有调用方
|
||||
不传记录类型时返回值不变。入站顺序:可用文件 → ready,但 parse_failed_at
|
||||
非空 → parse_failed;进行中单元 → fetching;最新单元空数据 → no_data;
|
||||
@@ -28,10 +29,9 @@ from typing import Any, Callable
|
||||
from sqlalchemy import and_, not_, or_
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.freight_rpa_inbound_report import (
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
)
|
||||
# 入站归档文件模型归 freight_rpa 域读写(阶段 B Task 4 边界),批量/单来源读取
|
||||
# 一律经 queries 只读函数;入站执行单元模型不在禁列(状态投影按 status 消费)。
|
||||
from app.models.freight_rpa_inbound_report import FreightRpaInboundUnitRun
|
||||
from app.models.freight_rpa_outbound_report import (
|
||||
FreightRpaOutboundReportConfig,
|
||||
FreightRpaOutboundReportFile,
|
||||
@@ -39,12 +39,12 @@ from app.models.freight_rpa_outbound_report import (
|
||||
)
|
||||
from app.services.freight_rpa.reports.queries import (
|
||||
clear_inbound_parse_failure as _clear_parse_failure_by_id,
|
||||
expired_inbound_file_condition,
|
||||
expired_inbound_source_codes,
|
||||
get_outbound_config,
|
||||
has_expired_inbound_file,
|
||||
latest_usable_inbound_file,
|
||||
latest_usable_inbound_files_by_source,
|
||||
mark_inbound_parse_failure as _mark_parse_failure_by_id,
|
||||
usable_inbound_file_condition,
|
||||
)
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
@@ -288,13 +288,13 @@ def _project_file_status(
|
||||
|
||||
|
||||
def _latest_files_by_source(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> dict[str, _FileFact]:
|
||||
"""一次取出这批来源各自最新的可用归档。
|
||||
"""一次取出这批来源各自最新的可用出站归档(入站批查已下沉 queries 层)。
|
||||
|
||||
核心逻辑:按来源主键过滤后按创建时间、文件主键倒序,每个来源只留第一条。
|
||||
只取状态判断用到的列,不加载执行单元上的 JSON 快照。
|
||||
|
||||
Args:
|
||||
file_model: 入站或出站归档文件模型。
|
||||
file_model: 出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型,用来按 source_id 过滤。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 可用文件条件(未删除、当天业务日、未过保留期)。
|
||||
@@ -359,13 +359,13 @@ def _units_by_source(unit_model: type, source_ids: list[int]) -> tuple[dict[str,
|
||||
|
||||
|
||||
def _expired_source_codes(file_model: type, unit_model: type, source_ids: list[int], *filters: Any) -> set[str]:
|
||||
"""一次找出仍有失效未清理归档的来源编码。
|
||||
"""一次找出仍有失效未清理出站归档的来源编码(入站批查已下沉 queries 层)。
|
||||
|
||||
核心逻辑:只判断存在性,不取文件内容。失效条件由调用方传入,与单来源
|
||||
has_expired_* 使用同一套未删除且不满足新鲜度/保留期的口径。
|
||||
|
||||
Args:
|
||||
file_model: 入站或出站归档文件模型。
|
||||
file_model: 出站归档文件模型。
|
||||
unit_model: 对应的执行单元模型。
|
||||
source_ids: 要投影的来源主键。
|
||||
filters: 失效文件条件。
|
||||
@@ -412,19 +412,17 @@ def resolve_source_file_statuses(sources: list[Any]) -> dict[str, dict[str, dict
|
||||
.all()
|
||||
)
|
||||
}
|
||||
inbound_files = _latest_files_by_source(
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
source_ids,
|
||||
usable_inbound_file_condition(now=now),
|
||||
)
|
||||
inbound_files = {
|
||||
code: _FileFact(
|
||||
file_id=view.file_id,
|
||||
original_filename=view.original_filename,
|
||||
sha256=view.sha256,
|
||||
parse_failed_at=view.parse_failed_at,
|
||||
)
|
||||
for code, view in latest_usable_inbound_files_by_source(source_ids, now=now).items()
|
||||
}
|
||||
inbound_latest, inbound_active = _units_by_source(FreightRpaInboundUnitRun, source_ids)
|
||||
inbound_expired = _expired_source_codes(
|
||||
FreightRpaInboundReportFile,
|
||||
FreightRpaInboundUnitRun,
|
||||
source_ids,
|
||||
expired_inbound_file_condition(now=now),
|
||||
)
|
||||
inbound_expired = expired_inbound_source_codes(source_ids, now=now)
|
||||
outbound_files = _latest_files_by_source(
|
||||
FreightRpaOutboundReportFile,
|
||||
FreightRpaOutboundUnitRun,
|
||||
|
||||
@@ -4,6 +4,7 @@ backend/app/services/integrations/wecom/notify.py
|
||||
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
|
||||
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
|
||||
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
|
||||
文本卡片标题默认加上「AI智能体」来源;密码重置和权限变更保持原标题。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -24,6 +25,17 @@ _TOKEN_CACHE = {
|
||||
'expires_at': None,
|
||||
}
|
||||
|
||||
# 企微 textcard 没有发送者栏,用来源前缀让收件人看出是 AI 智能体推送。
|
||||
_AGENT_SOURCE_PREFIX = 'AI智能体 · '
|
||||
_TEXT_CARD_TITLE_LIMIT = 120
|
||||
# 账号与权限通知不是智能体推送,标题不加来源。
|
||||
_NO_AGENT_SOURCE_EVENTS = frozenset({
|
||||
'password_reset',
|
||||
'permission_batch_updated',
|
||||
'permission_request_approved',
|
||||
'permission_request_rejected',
|
||||
})
|
||||
|
||||
|
||||
def _get_enabled_events() -> set[str]:
|
||||
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
|
||||
@@ -141,19 +153,54 @@ def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _with_agent_source_title(title: str, *, enabled: bool = True) -> str:
|
||||
"""
|
||||
给企微 textcard 标题加上「AI智能体」来源,并限制在 120 字以内。
|
||||
|
||||
核心逻辑:前缀放在最前,超长时截断业务标题,避免来源被切掉。
|
||||
已带相同前缀时不重复添加。enabled 为 False 时只做长度截断。
|
||||
Args:
|
||||
title: 业务侧传入的卡片标题。
|
||||
enabled: 为 False 时保持原标题,用于密码重置和权限变更。
|
||||
Returns:
|
||||
实际发给企业微信的标题。
|
||||
"""
|
||||
text = (title or '').strip()
|
||||
if not enabled:
|
||||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||
if text.startswith(_AGENT_SOURCE_PREFIX):
|
||||
return text[:_TEXT_CARD_TITLE_LIMIT]
|
||||
return f'{_AGENT_SOURCE_PREFIX}{text}'[:_TEXT_CARD_TITLE_LIMIT]
|
||||
|
||||
|
||||
def send_wecom_textcard_message(
|
||||
wecom_userid: str,
|
||||
title: str,
|
||||
description: str,
|
||||
jump_url: str,
|
||||
*,
|
||||
with_agent_source: bool = True,
|
||||
) -> dict:
|
||||
"""
|
||||
发送企业微信文本卡片。
|
||||
|
||||
核心逻辑:默认在标题前加上「AI智能体」来源。审计记录仍保存调用方传入的业务标题。
|
||||
Args:
|
||||
wecom_userid: 企业微信 userid。
|
||||
title: 业务标题。
|
||||
description: 卡片正文。
|
||||
jump_url: 点击跳转地址。
|
||||
with_agent_source: 为 False 时标题不加来源。
|
||||
Returns:
|
||||
企业微信 message/send 的 JSON 响应。
|
||||
"""
|
||||
token = _get_access_token()
|
||||
payload = {
|
||||
'touser': wecom_userid,
|
||||
'msgtype': 'textcard',
|
||||
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
|
||||
'textcard': {
|
||||
'title': title[:120],
|
||||
'title': _with_agent_source_title(title, enabled=with_agent_source),
|
||||
'description': (description or '')[:1024],
|
||||
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
|
||||
'btntxt': '查看详情',
|
||||
@@ -200,6 +247,7 @@ def send_wecom_event_message(
|
||||
|
||||
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
|
||||
作为 wecom_userid,因为该 id 同时是企业微信 userid。
|
||||
标题在发送时加上「AI智能体」来源;密码重置和权限变更不加。审计 title 保持业务标题。
|
||||
Args:
|
||||
event_type: 通知事件开关名。
|
||||
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
|
||||
@@ -239,7 +287,13 @@ def send_wecom_event_message(
|
||||
else:
|
||||
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
|
||||
audit.jump_url = final_jump_url
|
||||
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
|
||||
data = send_wecom_textcard_message(
|
||||
target_userid,
|
||||
title,
|
||||
content,
|
||||
final_jump_url,
|
||||
with_agent_source=event_type not in _NO_AGENT_SOURCE_EVENTS,
|
||||
)
|
||||
if data.get('errcode') == 0:
|
||||
audit.status = 'sent'
|
||||
return {'ok': True, 'trace_id': trace_id}
|
||||
|
||||
@@ -2,18 +2,24 @@
|
||||
|
||||
用途:自动处理可调拨异动与历史可恢复异常;执行结果通知统一走
|
||||
排程「启用通知」通用企微通知,本任务不自建领域通知。
|
||||
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
|
||||
依赖:auto_transfer、recovery_service、transfer deps、job_registry.ScheduleExecuteResult、
|
||||
inbound_trigger_service.list_inbound_capable_source_codes(缺省来源口径)、
|
||||
transfer_type_config_service.get_enabled(缺省类型口径)、
|
||||
date_policy(业务日与日期解析)。
|
||||
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发入站 RPA),
|
||||
不依赖其他排程成功;来源留空兜底为全部启用入站来源;可选异动日期范围
|
||||
不依赖其他排程成功;来源留空兜底为全部启用入站来源;【调拨类型 2026-10-23】
|
||||
job_params.transfer_types 为 multi_select,留空=全部启用中的类型配置,
|
||||
按类型逐轮 run_auto_transfer(恢复复核与类型无关,循环外只跑一次);
|
||||
类型配置为空/读取失败 fail-closed 硬失败,不静默跳过;可选异动日期范围
|
||||
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层——
|
||||
该偏移参数是自动处理面的唯一日期边界;【T−2 成熟封顶 2026-10-21】引擎
|
||||
只圈 movement_date ≤ T−2 的成熟记录(T−2 之前数据全部成熟),未配置
|
||||
偏移即处理全部成熟积压;偏移终点落在 T−1/当天(0/1)会被匹配层
|
||||
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(无
|
||||
run_no 且无 errors)置 domain_notification_managed 保持静默(C5),有
|
||||
Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
||||
MOVEMENT_DATE_RANGE_INVALID 拒绝(快速失败交框架通知);空数据日(全部
|
||||
类型均无 run_no 且无 errors)置 domain_notification_managed 保持静默
|
||||
(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
||||
返回:七元组位序=(total, success, failed, skipped, details, errors, step_logs),
|
||||
warnings 无对应槽位——恢复/来源汇总写 step_logs(dict),不得挤占 errors 位。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,11 +27,13 @@ from __future__ import annotations
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
|
||||
from app.services.in_transit_transfer.auto_transfer import run_auto_transfer
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
|
||||
from app.services.in_transit_transfer.inbound_trigger_service import list_inbound_capable_source_codes
|
||||
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome, run_daily_recovery
|
||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||
|
||||
|
||||
@@ -52,6 +60,33 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
|
||||
return codes
|
||||
|
||||
|
||||
def _wanted_transfer_types(params: dict[str, Any], errors: list[str]) -> list[str]:
|
||||
"""提取结构化 transfer_types;留空回落为全部启用中的类型配置(fail-closed)。
|
||||
|
||||
Args:
|
||||
params: 排程结构化参数(job_params.transfer_types 可为列表/字符串/缺省)。
|
||||
errors: 错误累积列表(类型配置读取失败/为空时写入,由调用方硬失败)。
|
||||
Returns:
|
||||
去空白后的类型编码列表;配置为空或脏配置读取失败时为空列表(已落错误)。
|
||||
"""
|
||||
values = params.get("transfer_types") or []
|
||||
if isinstance(values, str):
|
||||
values = [values]
|
||||
codes = [str(item).strip() for item in values if str(item).strip()]
|
||||
if codes:
|
||||
return codes
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||
|
||||
try:
|
||||
codes = [dto.code for dto in get_enabled()]
|
||||
except AppError as exc:
|
||||
errors.append(f"调拨类型配置读取失败: {exc}")
|
||||
return []
|
||||
if not codes:
|
||||
errors.append("无启用中的调拨类型配置(须先在管理端调拨类型页创建并启用)")
|
||||
return codes
|
||||
|
||||
|
||||
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
|
||||
"""把「T−N 偏移天数」参数换算为执行日口径的具体异动日期(T−N)。
|
||||
|
||||
@@ -77,12 +112,14 @@ def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: li
|
||||
|
||||
|
||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
|
||||
"""自动调拨:恢复(一次)→ 按类型逐轮「匹配(严格相等)+ 执行」;通知走排程「启用通知」。
|
||||
|
||||
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
|
||||
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
|
||||
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
|
||||
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
|
||||
核心逻辑:不自建领域汇总通知(收件人取排程表单底部「启用通知」配置);
|
||||
仅在空数据日(全部类型均无 run_no 且无 errors)置 domain_notification_managed
|
||||
抑制框架完成卡(C5 空数据日静默);有 run_no 或硬失败时框架卡照常发送/兜底。
|
||||
调拨类型留空=全部启用类型逐轮执行(D8:类型=平台配置,排程不隐式假设单一
|
||||
类型;配置为空/读取失败 fail-closed 硬失败);历史恢复与类型无关,循环外
|
||||
只跑一次(重复恢复会对同一批行重复建 Attempt 并重复外部查询)。
|
||||
可选异动日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
|
||||
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
|
||||
【T−2 成熟封顶 2026-10-21】引擎只圈 ≤T−2 成熟记录,未配置偏移即处理全部
|
||||
@@ -90,7 +127,7 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
硬失败路径;偏移非法(负数/小数/非数字)同样快速失败不执行。
|
||||
|
||||
Args:
|
||||
task: 排程任务(job_params: source_codes/recover_history/
|
||||
task: 排程任务(job_params: transfer_types/source_codes/recover_history/
|
||||
receipt_from_offset_days/receipt_to_offset_days)。
|
||||
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
|
||||
Returns:
|
||||
@@ -101,60 +138,99 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
recover_history = bool(params.get("recover_history", True))
|
||||
business_date = str(business_date_now())
|
||||
|
||||
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
||||
# 防止坏参数被静默忽略后退化成全量积压处理。
|
||||
param_errors: list[str] = []
|
||||
# [STEP 1] 配置解析与 T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
||||
# 防止坏参数被静默忽略后退化成全量积压处理。硬失败以 failed_count=1 落终态
|
||||
# failed(total=0 且 errors 非空会被框架判 success「无待处理数据」,不可用)。
|
||||
errors: list[str] = []
|
||||
transfer_types = _wanted_transfer_types(params, errors)
|
||||
movement_date_from = _offset_to_date(
|
||||
business_date, params.get("receipt_from_offset_days"), "异动日期起点", param_errors)
|
||||
business_date, params.get("receipt_from_offset_days"), "异动日期起点", errors)
|
||||
movement_date_to = _offset_to_date(
|
||||
business_date, params.get("receipt_to_offset_days"), "异动日期终点", param_errors)
|
||||
if param_errors:
|
||||
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
|
||||
business_date, params.get("receipt_to_offset_days"), "异动日期终点", errors)
|
||||
if errors:
|
||||
return (1, 0, 1, 0, [], errors, [
|
||||
{"step": "config", "status": "failed", "detail": f"sources={len(source_codes)}"},
|
||||
])
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
# [出生翻转 2026-10-14] 调拨类型配置化(D8 匹配创建必填):排程参数
|
||||
# job_params.transfer_type 承载类型编码,原样透传匹配层;缺省 None 时
|
||||
# 匹配层 fail-closed(TRANSFER_TYPE_REQUIRED 随 errors 硬失败透出),
|
||||
# 不回落固定类型(类型=平台配置,排程不隐式假设)。
|
||||
transfer_type = str(params.get("transfer_type") or "").strip() or None
|
||||
outcome = run_auto_transfer(
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
source_codes=source_codes,
|
||||
recover_history=recover_history,
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
|
||||
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
|
||||
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
||||
if not outcome.run_no and not outcome.errors:
|
||||
# [STEP 2] 恢复复核只跑一次:扫全部 blocked_recoverable 行(与类型无关),
|
||||
# result_unknown / manually_closed 在服务内只读隔离/永久排除。恢复失败计一个
|
||||
# failed 单元——否则「恢复失败+各类型均空数据日」total=0 会被框架判 success。
|
||||
recovery = RecoveryOutcome()
|
||||
recovery_failed = False
|
||||
if recover_history:
|
||||
try:
|
||||
recovery = run_daily_recovery(business_date=business_date, deps=deps)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
recovery_failed = True
|
||||
errors.append(f"recovery_failed: {exc}")
|
||||
step_logs: list[dict[str, Any]] = [{
|
||||
"step": "recovery",
|
||||
"status": "failed" if recovery_failed else ("success" if recover_history else "skipped"),
|
||||
"detail": {
|
||||
"recovered": recovery.recovered_count,
|
||||
"still_blocked": recovery.still_blocked_count,
|
||||
"skipped_result_unknown": recovery.skipped_result_unknown,
|
||||
"skipped_manually_closed": recovery.skipped_manually_closed,
|
||||
},
|
||||
}]
|
||||
failed_units = 1 if recovery_failed else 0
|
||||
|
||||
# [STEP 3] 按类型逐轮自动调拨:单类型失败不阻断其余类型(run_auto_transfer
|
||||
# 内部捕获进 outcome.errors)。
|
||||
results: list[dict[str, Any]] = []
|
||||
success_runs = 0
|
||||
failed_runs = 0
|
||||
for code in transfer_types:
|
||||
outcome = run_auto_transfer(
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
source_codes=source_codes,
|
||||
recover_history=False,
|
||||
movement_date_from=movement_date_from,
|
||||
movement_date_to=movement_date_to,
|
||||
transfer_type=code,
|
||||
)
|
||||
errors.extend(outcome.errors)
|
||||
if outcome.run_no:
|
||||
results.append({
|
||||
"transfer_type": code,
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.run_status,
|
||||
})
|
||||
if outcome.run_status in {"success", "partial_failed"}:
|
||||
success_runs += 1
|
||||
else:
|
||||
failed_runs += 1
|
||||
elif outcome.errors:
|
||||
failed_runs += 1
|
||||
|
||||
# [STEP 4] 空数据日静默门禁:全部类型均无 run 且无错误(C5)时置标记抑制
|
||||
# 框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
||||
if not results and not errors:
|
||||
run.response_summary_json = {
|
||||
**(run.response_summary_json or {}),
|
||||
"domain_notification_managed": True,
|
||||
}
|
||||
results: list[dict[str, Any]] = []
|
||||
errors: list[str] = list(outcome.errors)
|
||||
recovery = outcome.recovery
|
||||
warnings: list[str] = [
|
||||
f"sources={len(source_codes)} recovered={recovery.recovered_count} still_blocked={recovery.still_blocked_count}",
|
||||
]
|
||||
if outcome.run_no:
|
||||
results.append({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.run_status,
|
||||
step_logs.append({
|
||||
"step": "auto_transfer", "status": "skipped",
|
||||
"detail": "no executable items; execution and notification skipped",
|
||||
})
|
||||
elif not outcome.errors:
|
||||
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
|
||||
warnings.append("no executable items; execution and notification skipped")
|
||||
success = 1 if outcome.run_status in {"success", "partial_failed"} else 0
|
||||
|
||||
summary_text = (
|
||||
f"sources={len(source_codes)} types={len(transfer_types)} "
|
||||
f"runs={len(results)} recovered={recovery.recovered_count} "
|
||||
f"still_blocked={recovery.still_blocked_count}"
|
||||
)
|
||||
return (
|
||||
success + recovery.recovered_count,
|
||||
success,
|
||||
recovery.still_blocked_count,
|
||||
success_runs + failed_runs + recovery.recovered_count + failed_units,
|
||||
success_runs,
|
||||
failed_runs + failed_units + recovery.still_blocked_count,
|
||||
0,
|
||||
results,
|
||||
warnings,
|
||||
errors,
|
||||
step_logs + [
|
||||
{"step": "summary", "status": "failed" if errors else "success", "detail": summary_text},
|
||||
],
|
||||
)
|
||||
@@ -5,7 +5,8 @@ backend/app/services/schedule/job_options.py
|
||||
依赖:models.Agent、shipping_notice.onhand_source_repository。
|
||||
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
|
||||
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
|
||||
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources。
|
||||
货代 RPA 注册键为 freight_rpa_sources、freight_rpa_inbound_sources 与 freight_rpa_outbound_sources;
|
||||
在途调拨注册键为 transfer_types(启用中的调拨类型配置)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -78,6 +79,20 @@ def _freight_rpa_outbound_sources_options() -> list[dict[str, Any]]:
|
||||
} for source, _config in rows]
|
||||
|
||||
|
||||
def _transfer_types_options() -> list[dict[str, Any]]:
|
||||
"""启用中的调拨类型(value=类型编码;供在途自动调拨排程选类型,留空=全部)。"""
|
||||
from app.services.in_transit_transfer.transfer_type_config_service import get_enabled
|
||||
|
||||
return [
|
||||
{
|
||||
"label": (dto.names or {}).get("zh-CN") or dto.code,
|
||||
"value": dto.code,
|
||||
"description": dto.description or None,
|
||||
}
|
||||
for dto in get_enabled()
|
||||
]
|
||||
|
||||
|
||||
def _hxops_users_options() -> list[dict[str, Any]]:
|
||||
"""全部启用用户(value=users.id);订单交期回复未回复提醒收件人等场景用。"""
|
||||
from app.models import User
|
||||
@@ -118,6 +133,7 @@ _OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
||||
"freight_rpa_sources": _freight_rpa_sources_options,
|
||||
"freight_rpa_inbound_sources": _freight_rpa_inbound_sources_options,
|
||||
"freight_rpa_outbound_sources": _freight_rpa_outbound_sources_options,
|
||||
"transfer_types": _transfer_types_options,
|
||||
"hxops_users": _hxops_users_options,
|
||||
"users": _users_options,
|
||||
}
|
||||
|
||||
@@ -606,10 +606,21 @@ def _register_builtin_platform_jobs() -> None:
|
||||
handler=run_in_transit_transfer_schedule,
|
||||
description=(
|
||||
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
|
||||
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
|
||||
"缺收料文件时自动触发收料 RPA。调拨类型留空=全部启用类型逐轮执行。"
|
||||
"执行时间建议配置在期望调拨时点之前。"
|
||||
),
|
||||
category="platform",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "transfer_types",
|
||||
"type": "multi_select",
|
||||
"label": "调拨类型",
|
||||
"label_key": "admin.schedule.form.transferTypeCodes",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "transfer_types",
|
||||
"help": "留空=全部启用中的调拨类型;按类型逐轮匹配并执行,恢复复核只跑一次。",
|
||||
},
|
||||
{
|
||||
"key": "source_codes",
|
||||
"type": "multi_select",
|
||||
|
||||
@@ -46,26 +46,56 @@ from app.path_utils import resolve_backend_relative_path
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
def _released_line_indexes_for_task(order_task_id: int) -> set[int]:
|
||||
"""按正式 OT 身份读取已审计短缺放行的行号集合(复核 Case 的 confirmed_task_id 恒为 OT id)。"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(order_task_id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
|
||||
ShippingOrderReviewLineDecision.line_index.isnot(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return {int(row.line_index) for row in rows}
|
||||
|
||||
|
||||
def _notice_source_code(task: ShippingNotice) -> str | None:
|
||||
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。
|
||||
|
||||
匹配事实的 task_id 挂在正式 OT 上:传 Notice 时取 order_task_id,
|
||||
传 OT 本身时取 id(整单 ODM 候选投影会在物化前以 OT 调用)。
|
||||
已审计短缺放行行(release_onhand_shortage)的 match_result 恒为 not_found
|
||||
(如预约键 0 命中的料号兜底行),其事实源码与 matched 行同票参与唯一性
|
||||
裁决;只按 matched 过滤会让「整单放行」的单永远解析不到库存源
|
||||
(回归 OT-20261027-4BD4CEFF)。
|
||||
"""
|
||||
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return None
|
||||
task_id = int(task_id)
|
||||
released_line_indexes = _released_line_indexes_for_task(task_id)
|
||||
codes = [
|
||||
str(row[0]).strip().upper()
|
||||
for row in db.session.query(ShippingNoticeLineOnhandMatch.source_code).filter(
|
||||
for row in db.session.query(
|
||||
ShippingNoticeLineOnhandMatch.source_code,
|
||||
ShippingNoticeLineOnhandMatch.match_result,
|
||||
ShippingNoticeLineOnhandMatch.line_index,
|
||||
).filter(
|
||||
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.match_result == 'matched',
|
||||
ShippingNoticeLineOnhandMatch.source_code.isnot(None),
|
||||
).distinct().all()
|
||||
if row[0]
|
||||
).all()
|
||||
if row[0] and (row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes))
|
||||
]
|
||||
codes = list(dict.fromkeys(codes))
|
||||
return codes[0] if len(codes) == 1 else None
|
||||
|
||||
|
||||
@@ -87,19 +117,31 @@ def _notice_chosen_odm(task: ShippingNotice) -> str | None:
|
||||
|
||||
|
||||
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
|
||||
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
|
||||
"""从 Notice 行级匹配读取本次导出的唯一库存文件。
|
||||
|
||||
已审计短缺放行行(not_found 事实)的证据快照与 matched 行同票:整单放行时
|
||||
库存证据文件仍必须落 Artifact 审计,否则证据流断链(回归 OT-20261027-4BD4CEFF)。
|
||||
"""
|
||||
task_id = getattr(task, 'order_task_id', None)
|
||||
if task_id is None:
|
||||
return None
|
||||
task_id = int(task_id)
|
||||
released_line_indexes = _released_line_indexes_for_task(task_id)
|
||||
ids = [
|
||||
int(row[0]) for row in db.session.query(ShippingNoticeLineOnhandMatch.onhand_snapshot_id).filter(
|
||||
int(row[0]) for row in db.session.query(
|
||||
ShippingNoticeLineOnhandMatch.onhand_snapshot_id,
|
||||
ShippingNoticeLineOnhandMatch.match_result,
|
||||
ShippingNoticeLineOnhandMatch.line_index,
|
||||
).filter(
|
||||
ShippingNoticeLineOnhandMatch.task_id == task_id,
|
||||
ShippingNoticeLineOnhandMatch.is_current.is_(True),
|
||||
ShippingNoticeLineOnhandMatch.match_result == 'matched',
|
||||
ShippingNoticeLineOnhandMatch.onhand_snapshot_id.isnot(None),
|
||||
).distinct().all()
|
||||
).all()
|
||||
if row[0] is not None and (
|
||||
row[1] == 'matched' or (row[2] is not None and int(row[2]) in released_line_indexes)
|
||||
)
|
||||
]
|
||||
ids = list(dict.fromkeys(ids))
|
||||
return ids[0] if len(ids) == 1 else None
|
||||
|
||||
|
||||
@@ -799,8 +841,14 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
||||
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
|
||||
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
|
||||
# [身份口径] 复核 Case.confirmed_task_id 恒为正式 OT id;本函数入参可能是
|
||||
# 换绑后的 Notice,必须经 order_task_id 回链 OT,否则放行/结案决定恒查空,
|
||||
# 放行行进不了导出资格、结案行漏剔除(与 _facts_order_task 同款键位纪律)。
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
order_task_id_for_decisions = int(
|
||||
getattr(source_notice, 'order_task_id', None) or source_notice.id
|
||||
)
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
||||
released_source_line_indexes: set[int] = set()
|
||||
if source_notice.id is not None:
|
||||
@@ -808,7 +856,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_onhand_shortage',
|
||||
)
|
||||
@@ -835,7 +883,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewCase.confirmed_task_id == order_task_id_for_decisions,
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||
)
|
||||
|
||||
@@ -2520,7 +2520,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
# 三态结果:success / failed / unknown。result 显式给定则优先,否则由 success 布尔推导。
|
||||
raw_result = str(payload.get('result') or '').strip().lower()
|
||||
if raw_result in {'success', 'failed', 'unknown'}:
|
||||
if raw_result in {'success', 'failed', 'unknown', 'allocating'}:
|
||||
result_status = raw_result
|
||||
else:
|
||||
result_status = 'success' if success else 'failed'
|
||||
@@ -2614,6 +2614,25 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
position=POSITION_UPLOADED if has_verified_upload_success(task) else None,
|
||||
)
|
||||
|
||||
if completed.status == 'running' and completed.error_code == 'CRANE_ALLOCATING':
|
||||
set_task_step_progress(
|
||||
task,
|
||||
stage="freight_uploading",
|
||||
step_title="上传货代",
|
||||
status="running",
|
||||
message='货代已接收文件,正在分配,稍后自动回查一次',
|
||||
progress_percent=90,
|
||||
detail='Processing + Allocating the Shipping Order',
|
||||
)
|
||||
log_task_event(task, 'upload_rpa_allocating', {'artifact_id': completed.artifact_id, 'attempt_id': completed.id})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status='running',
|
||||
task=task,
|
||||
message='货代已接收文件,正在分配',
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if completed.status == 'unknown':
|
||||
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
|
||||
set_task_step_progress(
|
||||
|
||||
@@ -414,7 +414,11 @@ def _shortage_release_required_fields(
|
||||
source_code=resolved_source_code, enabled=True,
|
||||
).first()
|
||||
template = getattr(source, 'excel_template', None) if source is not None else None
|
||||
profile = getattr(source, 'parsing_profile', None) if source is not None else None
|
||||
# [s18 改名] 解析方案绑定归 onhand_report_config 配置行,站点行不再承载该关系
|
||||
# (与 freight_rpa.parsing_profile.require_source_profile 同口径);
|
||||
# 站点行 getattr 读法会静默得 None,曾致短缺放行(自动+人工)全部失败。
|
||||
release_config = getattr(source, 'onhand_report_config', None) if source is not None else None
|
||||
profile = release_config.parsing_profile if release_config is not None else None
|
||||
if template is None or profile is None:
|
||||
raise ConflictError(
|
||||
'Inventory source export template is unavailable',
|
||||
|
||||
@@ -1951,16 +1951,19 @@ def list_freight_notice_groups_for_task(
|
||||
.first()
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
|
||||
projected_upload_status = project_notice_upload_status(notice)
|
||||
hide_allocating_error = projected_upload_status == 'allocating'
|
||||
items.append({
|
||||
'business_no': business_no,
|
||||
'po_number': po_number,
|
||||
# Notice 面契约:成功统一为 uploaded,禁止下发 Attempt 原词 succeeded。
|
||||
'upload_status': project_notice_upload_status(notice),
|
||||
'upload_status': projected_upload_status,
|
||||
'upload_mode': upload_mode,
|
||||
'upload_attempt': upload_attempt,
|
||||
'upload_error_code': getattr(latest_attempt, 'error_code', None),
|
||||
'upload_error_code': None if hide_allocating_error else getattr(latest_attempt, 'error_code', None),
|
||||
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
|
||||
'upload_error_message': (getattr(latest_attempt, 'error_message', None) or '')[:500] or None,
|
||||
# 分配中的内部错误码不是失败原因,不能把这一行显示成需人工。
|
||||
'upload_error_message': None if hide_allocating_error else ((getattr(latest_attempt, 'error_message', None) or '')[:500] or None),
|
||||
'export_file_name': getattr(artifact, 'file_name', None),
|
||||
'available_actions': available_actions,
|
||||
'lines': _notice_line_summary_for_task(notice),
|
||||
|
||||
@@ -75,6 +75,14 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
|
||||
return existing
|
||||
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
|
||||
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
|
||||
allocating = ShippingUploadAttempt.query.filter_by(
|
||||
artifact_id=artifact.id, status='running', error_code='CRANE_ALLOCATING',
|
||||
).first()
|
||||
if allocating is not None:
|
||||
raise ConflictError(
|
||||
'Crane has accepted the file and is still allocating; refresh status instead of uploading again',
|
||||
code='SHIPPING.UPLOAD_CRANE_ALLOCATING',
|
||||
)
|
||||
# 业务决定:结果未知(timed_out/unknown)不再阻断重新下发 RPA。该状态表示“无法判断上传是否成功/失败”,
|
||||
# 为避免用户卡死、无法继续尝试,允许再次触发;若上次实际上传成功,重复触发可能产生重复单,
|
||||
# 需由用户在 CRANE 侧核查(错误文案已提示)。幂等 key 去重仍保留。
|
||||
@@ -123,7 +131,7 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
|
||||
task: 正式 Notice,或可解析到 Notice 的 OT。
|
||||
|
||||
Returns:
|
||||
uploaded | uploading | pending | failed | unknown | 其它透传小写 | None。
|
||||
uploaded | allocating | uploading | pending | failed | unknown | 其它透传小写 | None。
|
||||
"""
|
||||
attempt = latest_upload_attempt(task)
|
||||
if attempt is not None:
|
||||
@@ -131,6 +139,8 @@ def project_notice_upload_status(task: ShippingNotice | Any) -> str | None:
|
||||
# Attempt 层当前写入成功态只有 succeeded(callback result=success 已在 complete_attempt 内翻译)。
|
||||
if status == 'succeeded':
|
||||
return 'uploaded'
|
||||
if status == 'running' and str(getattr(attempt, 'error_code', None) or '') == 'CRANE_ALLOCATING':
|
||||
return 'allocating'
|
||||
if status in _UPLOAD_IN_FLIGHT_TOKENS:
|
||||
return 'uploading'
|
||||
if status == 'pending':
|
||||
@@ -221,9 +231,9 @@ def _normalize_callback_result(result: str | None, success: bool) -> str:
|
||||
"""
|
||||
if result is not None:
|
||||
normalized = str(result or '').strip().lower()
|
||||
if normalized not in {'success', 'failed', 'unknown'}:
|
||||
if normalized not in {'success', 'failed', 'unknown', 'allocating'}:
|
||||
raise ValidationError(
|
||||
'result must be success, failed or unknown',
|
||||
'result must be success, failed, unknown or allocating',
|
||||
code='SHIPPING.UPLOAD_RESULT_INVALID',
|
||||
)
|
||||
return normalized
|
||||
@@ -243,7 +253,7 @@ def complete_attempt(
|
||||
callback_id: 回调幂等键(唯一)。
|
||||
freight_ref_no: 成功时货代回执号。
|
||||
error_message: 失败/未知时的脱敏错误信息。
|
||||
result: 三态结果 success / failed / unknown;三态与布尔推导见 _normalize_callback_result。
|
||||
result: success / failed / unknown / allocating。allocating 表示 Crane 已接收且仍在分配。
|
||||
|
||||
Returns:
|
||||
ShippingUploadAttempt: 已更新状态的 Attob。
|
||||
@@ -266,10 +276,16 @@ def complete_attempt(
|
||||
if artifact.status in {'superseded', 'invalidated'}:
|
||||
raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED')
|
||||
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
|
||||
if str(result or '').strip().lower() == 'allocating':
|
||||
return attempt
|
||||
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
|
||||
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
|
||||
result_status = _normalize_callback_result(result, success)
|
||||
if result_status == 'allocating':
|
||||
from app.services.freight_rpa.upload.crane_recheck import remember_crane_allocating
|
||||
|
||||
return remember_crane_allocating(attempt, artifact, callback)
|
||||
attempt.callback_id = callback
|
||||
attempt.finished_at = datetime.utcnow()
|
||||
task = db.session.get(ShippingNotice, artifact.task_id)
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
"""
|
||||
services/shipping_notice/upload_config_validation.py
|
||||
|
||||
用途:对连接级“发货 Excel 自动上传”配置做后端严格白名单校验,产出受限 JSON。
|
||||
依赖:app.core.errors.ValidationError;仅标准库,不引入第三方。
|
||||
逻辑:配置由管理端表单编辑,但后端只接受本模块允许的字段、枚举与安全边界;
|
||||
禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
|
||||
upload_config 是“这次上传到底用了什么”的快照来源,不做版本管理(见技术文档)。
|
||||
用途:系统连接只保存「是否启用发货 Excel 自动上传」。
|
||||
依赖:app.core.errors.ValidationError;标准库 hashlib/json。
|
||||
逻辑:页面路径、选择器和成功文案由连接器代码固定,管理端提交的这些字段一律丢弃。
|
||||
upload_config 快照只保留 enabled,供本次上传审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,192 +15,34 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
# 连接类型与各平台已审核域名(主机名白名单,后缀匹配以覆盖同域子站)。
|
||||
ALLOWED_CONNECTOR_TYPES = frozenset({'dbs', 'crane'})
|
||||
ALLOWED_PLATFORM_DOMAINS: dict[str, tuple[str, ...]] = {
|
||||
'dbs': ('dbschenker.com',),
|
||||
'crane': ('craneww.com',),
|
||||
}
|
||||
ALLOWED_SUBMIT_MODES = frozenset({'auto_after_file', 'click_submit'})
|
||||
ALLOWED_RESULT_MODES = frozenset({'page_notice', 'history_record'})
|
||||
|
||||
# 字段白名单:禁止把额外键(模板、Cookie、脚本)混入配置。
|
||||
ALLOWED_KEYS = frozenset({
|
||||
'enabled', 'entry_url', 'file_input_selector',
|
||||
'submit_mode', 'submit_selector',
|
||||
'result_mode', 'result_selector', 'success_texts', 'timeout_seconds',
|
||||
})
|
||||
|
||||
MAX_ENTRY_URL_LENGTH = 500
|
||||
MAX_SELECTOR_LENGTH = 200
|
||||
MAX_SUCCESS_TEXTS = 10
|
||||
MAX_SUCCESS_TEXT_LENGTH = 200
|
||||
MIN_TIMEOUT_SECONDS = 1
|
||||
MAX_TIMEOUT_SECONDS = 600
|
||||
DEFAULT_TIMEOUT_SECONDS = 120
|
||||
|
||||
# 复用的字符黑名单:任何脚本/表达式/注入语义都拒绝。
|
||||
_BLOCKED_SELECTOR_MARKERS = (
|
||||
'javascript:', '<script', 'expression(', 'onclick=', 'onload=', 'onerror=',
|
||||
'onmouseover=', 'onmouseout=', 'onfocus=', 'onblur=', 'onchange=', 'oninput=',
|
||||
)
|
||||
_BLOCKED_SELECTOR_CHARS = ('(', ')', '{', '}', ';', '<', '>', '`', '\\', '\n', '\r')
|
||||
|
||||
|
||||
def _reject(message: str, *, field: str) -> None:
|
||||
raise ValidationError(message, code='SHIPPING.UPLOAD_CONFIG_INVALID', details={'field': field})
|
||||
|
||||
|
||||
def _normalize_text(value: Any) -> str:
|
||||
return str(value or '').strip()
|
||||
|
||||
|
||||
def _validate_entry_url(connector_type: str, value: Any, *, required: bool = True) -> str | None:
|
||||
"""校验上传入口为 HTTPS 且主机名属于已审核平台域名。"""
|
||||
url = _normalize_text(value)
|
||||
if not url:
|
||||
if required:
|
||||
_reject('entry_url is required', field='entry_url')
|
||||
return None
|
||||
if len(url) > MAX_ENTRY_URL_LENGTH:
|
||||
_reject('entry_url is too long', field='entry_url')
|
||||
if not url.lower().startswith('https://'):
|
||||
_reject('entry_url must be HTTPS', field='entry_url')
|
||||
# 简单主机名解析:仅定位 host:port 部分,禁止 userinfo/query 进入主机判断。
|
||||
scheme_rest = url[8:]
|
||||
authority = scheme_rest.split('/', 1)[0].split('?', 1)[0].split('#', 1)[0]
|
||||
host = authority.split('@')[-1].split(':')[0].strip().lower()
|
||||
if not host:
|
||||
_reject('entry_url host is invalid', field='entry_url')
|
||||
allowed = ALLOWED_PLATFORM_DOMAINS.get(connector_type, ())
|
||||
if not any(host == domain or host.endswith('.' + domain) for domain in allowed):
|
||||
_reject(
|
||||
f'entry_url host not allowed for {connector_type}',
|
||||
field='entry_url',
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _validate_css_selector(value: Any, *, field: str, required: bool) -> str | None:
|
||||
"""校验普通 CSS selector:限制长度、拒绝脚本及表达式语义。"""
|
||||
selector = _normalize_text(value)
|
||||
if not selector:
|
||||
if required:
|
||||
_reject(f'{field} is required', field=field)
|
||||
return None
|
||||
if len(selector) > MAX_SELECTOR_LENGTH:
|
||||
_reject(f'{field} is too long', field=field)
|
||||
lowered = selector.lower()
|
||||
for marker in _BLOCKED_SELECTOR_MARKERS:
|
||||
if marker in lowered:
|
||||
_reject(f'{field} contains script semantics', field=field)
|
||||
for char in _BLOCKED_SELECTOR_CHARS:
|
||||
if char in selector:
|
||||
_reject(f'{field} contains an invalid character', field=field)
|
||||
return selector
|
||||
|
||||
|
||||
def _validate_success_texts(value: Any) -> list[str]:
|
||||
if value in (None, ''):
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
_reject('success_texts must be a list', field='success_texts')
|
||||
if len(value) > MAX_SUCCESS_TEXTS:
|
||||
_reject('success_texts is too long', field='success_texts')
|
||||
result: list[str] = []
|
||||
for item in value:
|
||||
text = _normalize_text(item)
|
||||
if not text or len(text) > MAX_SUCCESS_TEXT_LENGTH:
|
||||
_reject('success_texts contains an invalid item', field='success_texts')
|
||||
if text not in result:
|
||||
result.append(text)
|
||||
return result
|
||||
|
||||
|
||||
def validate_upload_config(connector_type: str, raw: Any) -> dict[str, Any] | None:
|
||||
"""白名单校验连接级上传配置,返回规范化 JSON;raw 为空/None 表示未配置(返回 None)。
|
||||
"""只保留 enabled。页面参数即使随旧表单提交也不落库。
|
||||
|
||||
Args:
|
||||
connector_type: 连接类型,仅允许 dbs / crane。
|
||||
raw: 管理端提交的原始上传配置对象。
|
||||
raw: 管理端提交的上传配置。None 或空串表示未配置。
|
||||
|
||||
Returns:
|
||||
dict | None: 规范化受限 JSON;未配置时返回 None。
|
||||
dict | None: ``{"enabled": bool}``;未配置时返回 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 含未知字段/非法枚举/不安全 selector/非 HTTPS 或非法域名/
|
||||
enabled=true 但缺少上传或结果判定所需字段。
|
||||
ValidationError: 连接类型非法或上传配置不是对象。
|
||||
"""
|
||||
normalized_connector = _normalize_text(connector_type).lower()
|
||||
normalized_connector = str(connector_type or '').strip().lower()
|
||||
if normalized_connector not in ALLOWED_CONNECTOR_TYPES:
|
||||
_reject('connector_type must be dbs or crane', field='connector_type')
|
||||
if raw in (None, ''):
|
||||
return None
|
||||
if not isinstance(raw, dict):
|
||||
_reject('upload_config must be an object', field='upload_config_json')
|
||||
unknown = set(raw) - ALLOWED_KEYS
|
||||
if unknown:
|
||||
_reject(f'upload_config contains unsupported fields: {sorted(unknown)}', field='upload_config_json')
|
||||
|
||||
enabled = raw.get('enabled') is True
|
||||
|
||||
config: dict[str, Any] = {
|
||||
'enabled': enabled,
|
||||
'entry_url': _validate_entry_url(normalized_connector, raw.get('entry_url'), required=enabled),
|
||||
'file_input_selector': _validate_css_selector(
|
||||
raw.get('file_input_selector'), field='file_input_selector', required=enabled,
|
||||
),
|
||||
'submit_mode': _normalize_text(raw.get('submit_mode')),
|
||||
'submit_selector': _validate_css_selector(
|
||||
raw.get('submit_selector'), field='submit_selector', required=False,
|
||||
),
|
||||
'result_mode': _normalize_text(raw.get('result_mode')),
|
||||
'result_selector': _validate_css_selector(
|
||||
raw.get('result_selector'), field='result_selector', required=False,
|
||||
),
|
||||
'success_texts': _validate_success_texts(raw.get('success_texts')),
|
||||
'timeout_seconds': raw.get('timeout_seconds', DEFAULT_TIMEOUT_SECONDS),
|
||||
}
|
||||
|
||||
if config['submit_mode'] not in ALLOWED_SUBMIT_MODES:
|
||||
_reject('submit_mode must be auto_after_file or click_submit', field='submit_mode')
|
||||
if config['result_mode'] not in ALLOWED_RESULT_MODES:
|
||||
_reject('result_mode must be page_notice or history_record', field='result_mode')
|
||||
if config['submit_mode'] == 'auto_after_file':
|
||||
# auto_after_file 由页面在选文件后自动提交,不应同时配置提交按钮选择器。
|
||||
config['submit_selector'] = None
|
||||
|
||||
try:
|
||||
timeout = int(config['timeout_seconds'])
|
||||
except (TypeError, ValueError):
|
||||
_reject('timeout_seconds must be an integer', field='timeout_seconds')
|
||||
if timeout < MIN_TIMEOUT_SECONDS or timeout > MAX_TIMEOUT_SECONDS:
|
||||
_reject(
|
||||
f'timeout_seconds must be within [{MIN_TIMEOUT_SECONDS}, {MAX_TIMEOUT_SECONDS}]',
|
||||
field='timeout_seconds',
|
||||
)
|
||||
config['timeout_seconds'] = timeout
|
||||
|
||||
if enabled:
|
||||
# 完成一次上传所需的公共字段由上述必填校验覆盖;此处补齐连接差异。
|
||||
if not config['file_input_selector']:
|
||||
_reject('enabled upload requires file_input_selector', field='file_input_selector')
|
||||
if config['submit_mode'] == 'click_submit' and not config['submit_selector']:
|
||||
_reject('enabled click_submit upload requires submit_selector', field='submit_selector')
|
||||
# 结果判定:dbs(DSV) 使用代码内置的受控成功流(History 绿状态/页面证据),
|
||||
# 不强制 admin 填写结果字段;crane 必须由 admin 补全提交/结果判定字段后才可启用。
|
||||
if normalized_connector == 'crane':
|
||||
if config['result_mode'] == 'page_notice':
|
||||
if not config['result_selector'] or not config['success_texts']:
|
||||
_reject(
|
||||
'enabled crane page_notice upload requires result_selector and success_texts',
|
||||
field='result_selector',
|
||||
)
|
||||
elif config['result_mode'] == 'history_record' and not config['result_selector']:
|
||||
_reject('enabled crane history_record upload requires result_selector', field='result_selector')
|
||||
|
||||
# 未启用时仍保存规范化的受限 JSON,方便 admin 预填后续补全。
|
||||
return config
|
||||
return {'enabled': raw.get('enabled') is True}
|
||||
|
||||
|
||||
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None:
|
||||
|
||||
@@ -44,7 +44,7 @@ class DmsArchiveAdapter:
|
||||
"""
|
||||
确保所有归档/{invoice}/ 存在,并把命中文件复制进去(不移动类型目录原件)。
|
||||
【AI 触发时机】扫描命中且 invoice 关联校验通过后调用。
|
||||
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有同 LeafName 则跳过覆盖。
|
||||
核心逻辑:先保证月下「所有归档」与发票子目录;目标已有原名则跳过。带「(重命名)」的副本改回原名,同一目录多出来的该后缀文件删除。
|
||||
"""
|
||||
yyyy = f"{period_month.year:04d}"
|
||||
mm = f"{period_month.month:02d}"
|
||||
|
||||
@@ -4,10 +4,12 @@ backend/app/services/voucher_check/dms_client.py
|
||||
用途:销售开票附件文档库客户端(登录、列目录、建文件夹、上传、复制;不移动原件)。
|
||||
依赖:requests、Flask 配置;登录接口与合同库相同。
|
||||
逻辑:LibraryID 复用文档库;根 FolderID 必须是销售开票附件。上传走 Attachment/Upload + Item/CreateFiles;归档复制同名跳过。
|
||||
文档库复制后 LeafName 写成「原名.pdf(重命名)」,扩展名另存。改回「原名.pdf」会被判同名,必须改成不含扩展名的「原名」;多余副本用 Item/Recycle 删除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import date
|
||||
@@ -23,6 +25,65 @@ _LOCK = threading.Lock()
|
||||
_CACHE: dict[str, Any] = {"session": None, "created_at": 0.0}
|
||||
|
||||
ARCHIVE_ROOT_LEAF = "所有归档"
|
||||
# 文档库同名冲突或复制后自动改名。标记前后可能有空格,后面有时还有 (1)。
|
||||
_DMS_RENAME_RE = re.compile(
|
||||
r"\s*[((]\s*重命名\s*[))]\s*(?:\(\s*\d+\s*\)|(\s*\d+\s*))?"
|
||||
)
|
||||
|
||||
|
||||
def canonical_leaf_name(name: str) -> str:
|
||||
"""
|
||||
去掉文档库自动加上的「重命名」标记,还原业务文件名。
|
||||
核心逻辑:`发票.pdf(重命名).pdf` 或带空格的 `发票.pdf (重命名) .pdf` 去掉标记后会多出一个扩展名,再折成 `发票.pdf`。
|
||||
"""
|
||||
text = str(name or "").strip()
|
||||
cleaned = _DMS_RENAME_RE.sub("", text)
|
||||
if cleaned == text:
|
||||
return text
|
||||
return re.sub(r"(\.[A-Za-z0-9]{1,8})\s*\1$", r"\1", cleaned).strip()
|
||||
|
||||
|
||||
def dms_stored_leaf_name(filename: str) -> str:
|
||||
"""
|
||||
算出文档库改名接口要写入的 LeafName。
|
||||
核心逻辑:库里真实名字是「发票.pdf(重命名)」,扩展名在附件上。改成「发票.pdf」会和自己判成同名;改成「发票」后界面仍显示「发票.pdf」。
|
||||
"""
|
||||
name = str(filename or "").strip()
|
||||
suffix = Path(name).suffix
|
||||
if suffix and name.lower().endswith(suffix.lower()) and len(name) > len(suffix):
|
||||
return name[: -len(suffix)]
|
||||
return name
|
||||
|
||||
|
||||
def row_display_name(row: dict[str, Any]) -> str:
|
||||
"""
|
||||
还原文档库界面上的文件名。
|
||||
核心逻辑:LeafName 没有以附件扩展名结尾时,界面会把扩展名补在后面。
|
||||
"""
|
||||
leaf = str((row or {}).get("LeafName") or "").strip()
|
||||
attachment = (row or {}).get("MainFileAttachment") or {}
|
||||
if not isinstance(attachment, dict):
|
||||
attachment = {}
|
||||
ext = str(attachment.get("Extension") or "").strip()
|
||||
if ext and not ext.startswith("."):
|
||||
ext = f".{ext}"
|
||||
if ext and leaf and not leaf.lower().endswith(ext.lower()):
|
||||
return f"{leaf}{ext}"
|
||||
return leaf
|
||||
|
||||
|
||||
def leaf_names_match(actual: str, wanted: str) -> bool:
|
||||
"""
|
||||
判断目录里的文件名是否就是要找的那一份。
|
||||
核心逻辑:完全一致,或实际名字只是想要的名字加上了文档库「重命名」。
|
||||
"""
|
||||
left = str(actual or "").strip()
|
||||
right = str(wanted or "").strip()
|
||||
if not left or not right:
|
||||
return False
|
||||
if left == right:
|
||||
return True
|
||||
return canonical_leaf_name(left) == right
|
||||
|
||||
|
||||
def _extract_item_id(payload: dict[str, Any]) -> str:
|
||||
@@ -265,14 +326,22 @@ class SalesDmsClient:
|
||||
|
||||
@classmethod
|
||||
def find_child_file(cls, *, parent_folder_id: str, leaf_name: str) -> dict[str, Any] | None:
|
||||
"""在父目录下按 LeafName 找非文件夹条目,找不到返回 None。"""
|
||||
"""
|
||||
在父目录下按 LeafName 找非文件夹条目,找不到返回 None。
|
||||
核心逻辑:优先完全同名。库内名字可能是「原名.pdf(重命名)」或已改回的「原名」,都按界面显示名认成同一份。
|
||||
"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
if not wanted:
|
||||
return None
|
||||
renamed: dict[str, Any] | None = None
|
||||
for row in cls.list_files(folder_id=parent_folder_id):
|
||||
if str(row.get("LeafName") or "").strip() == wanted:
|
||||
leaf = str(row.get("LeafName") or "").strip()
|
||||
shown = row_display_name(row)
|
||||
if leaf == wanted or shown == wanted:
|
||||
return row
|
||||
return None
|
||||
if renamed is None and (leaf_names_match(leaf, wanted) or leaf_names_match(shown, wanted)):
|
||||
renamed = row
|
||||
return renamed
|
||||
|
||||
@classmethod
|
||||
def resolve_period_folder(cls, *, period_month: date) -> tuple[str | None, str | None]:
|
||||
@@ -387,6 +456,121 @@ class SalesDmsClient:
|
||||
failure_message="文档库复制文件失败",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def rename_item(cls, *, item_id: str, leaf_name: str) -> dict[str, Any]:
|
||||
"""
|
||||
把文档库条目改成指定文件名。
|
||||
核心逻辑:POST Item/Rename,与文档库列表「重命名」一致,只改 LeafName、不另存一份。
|
||||
"""
|
||||
item = str(item_id or "").strip()
|
||||
wanted = str(leaf_name or "").strip()
|
||||
if not item:
|
||||
raise ValidationError("重命名条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
if not wanted:
|
||||
raise ValidationError("重命名文件名不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
return cls._post_json(
|
||||
"/Api/_api/APS/Public/Item/Rename",
|
||||
{"ItemID": item, "LeafName": wanted},
|
||||
timeout=30,
|
||||
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
failure_message="文档库去掉重命名后缀失败",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _restore_exact_leaf(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
wanted: str,
|
||||
row: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
所有归档要求界面上不带「(重命名)」。
|
||||
核心逻辑:先确认这份就是目标文件。改名只写不含扩展名的 LeafName;写成「原名.pdf」会和「原名.pdf(重命名)」判成同名。
|
||||
"""
|
||||
leaf = str(row.get("LeafName") or "").strip()
|
||||
shown = row_display_name(row)
|
||||
target = dms_stored_leaf_name(wanted)
|
||||
if leaf in {wanted, target} or shown == wanted:
|
||||
return row
|
||||
if canonical_leaf_name(leaf) != wanted and canonical_leaf_name(shown) != wanted:
|
||||
raise ServiceUnavailableError(
|
||||
"目标目录文件名与归档文件名不一致",
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"leaf_name": wanted, "actual_name": leaf},
|
||||
)
|
||||
cls.rename_item(item_id=str(row.get("ID") or ""), leaf_name=target)
|
||||
for item in cls.list_files(folder_id=parent_folder_id):
|
||||
item_leaf = str(item.get("LeafName") or "").strip()
|
||||
if item_leaf in {wanted, target} or row_display_name(item) == wanted:
|
||||
return item
|
||||
raise ServiceUnavailableError(
|
||||
"去掉重命名后缀后未找到原文件名",
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def recycle_items(cls, *, item_ids: list[str]) -> dict[str, Any]:
|
||||
"""
|
||||
按文档库列表「删除」把条目放进回收站。
|
||||
核心逻辑:POST Item/Recycle,ItemID 为数组;不调用彻底删除,误删可从回收站恢复。
|
||||
"""
|
||||
ids = [str(item_id).strip() for item_id in item_ids if str(item_id).strip()]
|
||||
if not ids:
|
||||
raise ValidationError("删除条目不能为空", code="VOUCHER_CHECK.CONFIG_INVALID")
|
||||
return cls._post_json(
|
||||
"/Api/_api/APS/Public/Item/Recycle",
|
||||
{"ItemID": ids},
|
||||
timeout=30,
|
||||
failure_code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
failure_message="文档库删除多余重命名文件失败",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _drop_extra_renamed_copies(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
wanted: str,
|
||||
keep_item_id: str,
|
||||
) -> None:
|
||||
"""
|
||||
删掉同一目录里多出来的「(重命名)」副本。
|
||||
核心逻辑:只删文件名还原后等于目标原名、且仍带重命名标记的条目;原名和其他文件不动。
|
||||
"""
|
||||
keep = str(keep_item_id or "").strip()
|
||||
extras: list[str] = []
|
||||
for row in cls.list_files(folder_id=parent_folder_id):
|
||||
item_id = str(row.get("ID") or "").strip()
|
||||
leaf = str(row.get("LeafName") or "").strip()
|
||||
shown = row_display_name(row)
|
||||
if not item_id or item_id == keep or ("重命名" not in leaf and "重命名" not in shown):
|
||||
continue
|
||||
if canonical_leaf_name(leaf) == wanted or canonical_leaf_name(shown) == wanted:
|
||||
extras.append(item_id)
|
||||
if extras:
|
||||
cls.recycle_items(item_ids=extras)
|
||||
|
||||
@classmethod
|
||||
def _settle_archived_file(
|
||||
cls,
|
||||
*,
|
||||
parent_folder_id: str,
|
||||
wanted: str,
|
||||
row: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
归档落盘后收成一个界面上不带后缀的原名。
|
||||
核心逻辑:先删掉其余「(重命名)」副本,再把留下的那份改成不含扩展名的 LeafName。先改名会被文档库判成同名。
|
||||
"""
|
||||
cls._drop_extra_renamed_copies(
|
||||
parent_folder_id=parent_folder_id,
|
||||
wanted=wanted,
|
||||
keep_item_id=str(row.get("ID") or "").strip(),
|
||||
)
|
||||
return cls._restore_exact_leaf(parent_folder_id=parent_folder_id, wanted=wanted, row=row)
|
||||
|
||||
@classmethod
|
||||
def copy_file_skip_same_name(
|
||||
cls,
|
||||
@@ -397,10 +581,10 @@ class SalesDmsClient:
|
||||
) -> tuple[dict[str, Any], bool]:
|
||||
"""
|
||||
复制文件到目标目录;目标已有同名文件则跳过、不覆盖。
|
||||
核心逻辑:先按 LeafName 查目标;没有再 Copy。Copy 报同名或复制后已能查到,一律视为跳过成功。
|
||||
核心逻辑:先按 LeafName 查目标。已有原名则跳过复制;只有「(重命名)」副本时改回原名。没有再 Copy。收尾时同一目录多出来的该后缀副本删除。
|
||||
|
||||
Returns:
|
||||
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有同名文件。
|
||||
(目标条目, skipped):skipped=True 表示未发起覆盖,沿用已有文件(必要时已去掉重命名后缀并删除多余副本)。
|
||||
"""
|
||||
wanted = str(leaf_name or "").strip()
|
||||
source = str(source_item_id or "").strip()
|
||||
@@ -414,18 +598,21 @@ class SalesDmsClient:
|
||||
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True
|
||||
|
||||
try:
|
||||
cls.copy_items(item_ids=[source], dest_folder_id=dest)
|
||||
except ServiceUnavailableError as exc:
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing), True
|
||||
if _is_name_conflict(exc.message):
|
||||
existing = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
if existing:
|
||||
return existing, True
|
||||
return (
|
||||
cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=existing),
|
||||
True,
|
||||
)
|
||||
raise
|
||||
|
||||
dest_row = cls.find_child_file(parent_folder_id=dest, leaf_name=wanted)
|
||||
@@ -435,7 +622,7 @@ class SalesDmsClient:
|
||||
code="VOUCHER_CHECK.ARCHIVE_FAILED",
|
||||
details={"leaf_name": wanted},
|
||||
)
|
||||
return dest_row, False
|
||||
return cls._settle_archived_file(parent_folder_id=dest, wanted=wanted, row=dest_row), False
|
||||
|
||||
@classmethod
|
||||
def ensure_period_type_folder(cls, *, period_month: date, type_folder: str) -> str:
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/services/voucher_check/notification.py
|
||||
用途:立账凭证检核缺件通知、以及检核 / PO 生成排程的技术失败告警。
|
||||
依赖:wecom_notify、notify_config_service、ScheduleTask.notify_user_ids_json、engine_persistence。
|
||||
逻辑:缺件按文件类型接收人拆成每人一封,正文只含该人负责且本批缺失的类型;
|
||||
卡片标题为「销售开票附件缺件」,不写业务方代号和批次号;
|
||||
卡片标题为「销售开票附件缺件提醒」,不写业务方代号和批次号;
|
||||
排程「启用通知」为总开关;技术失败仍走排程通知人;domain_notification_managed 避免通用排程重复通知。
|
||||
"""
|
||||
|
||||
@@ -47,7 +47,7 @@ def _missing_type_line(item: dict[str, Any]) -> str:
|
||||
|
||||
def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[str, str]:
|
||||
"""
|
||||
组装销售开票附件缺件 textcard。
|
||||
组装销售开票附件缺件 textcard,标题为「销售开票附件缺件提醒」。
|
||||
核心逻辑:用纯文本而不是 div 着色。企微 description 约 512 字节,
|
||||
颜色标签会挤掉后面的缺件类型。
|
||||
|
||||
@@ -62,7 +62,7 @@ def _missing_textcard(period_month: str, items: list[dict[str, Any]]) -> tuple[s
|
||||
"请尽快补齐。完整清单见详情里的 Excel。",
|
||||
]
|
||||
)
|
||||
return "销售开票附件缺件", body
|
||||
return "销售开票附件缺件提醒", body
|
||||
|
||||
|
||||
def _users_by_ids(user_ids: list[int]) -> list[User]:
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/voucher_check/query_service.py
|
||||
|
||||
用途:查询检核批次列表、最近一次检核、批次明细、企微发送记录,以及工作台强制重检入队。
|
||||
依赖:models.voucher_check、ScheduleRun、aggregator、schedule.queue_service、schedule_seed。
|
||||
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细同时返回 invoice 行与 by_file_type;强制重检写入 run_options.mode=force_all。
|
||||
逻辑:只读引擎表;列表 period 支持 YYYY 或 YYYY-MM;GET latest 不跟筛选;明细可按状态和 invoice 号筛选行,by_file_type 仍是整批;强制重检写入 run_options.mode=force_all。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -545,10 +545,14 @@ def list_run_items(
|
||||
*,
|
||||
run_id: int,
|
||||
result: str | None = None,
|
||||
invoice_no: str | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
) -> dict[str, Any]:
|
||||
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。"""
|
||||
"""分页查询批次明细;返回引擎按 invoice 聚合行,并附带按文件类型汇总。
|
||||
|
||||
核心逻辑:result 精确匹配状态;invoice_no 按包含、忽略大小写筛行。文件类型汇总不跟着这两个条件缩。
|
||||
"""
|
||||
run = ScheduleRun.query.get(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("批次不存在", code="VOUCHER_CHECK.RUN_NOT_FOUND")
|
||||
@@ -574,6 +578,12 @@ def list_run_items(
|
||||
result_filter = str(result).strip() if result else ""
|
||||
if result_filter:
|
||||
items = [row for row in items if row.get("result") == result_filter]
|
||||
invoice_filter = str(invoice_no).strip().casefold() if invoice_no else ""
|
||||
if invoice_filter:
|
||||
items = [
|
||||
row for row in items
|
||||
if invoice_filter in str(row.get("invoice_no") or "").casefold()
|
||||
]
|
||||
total = len(items)
|
||||
sliced = items[(page - 1) * page_size : page * page_size]
|
||||
return {
|
||||
|
||||
@@ -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,41 @@
|
||||
"""设备验收快照增加流程编号、标题和创建时间。
|
||||
|
||||
Revision ID: ea1b2c3d4e5f
|
||||
Revises: ea9d1e2f3a4b
|
||||
Create Date: 2026-10-26 19:20:00.000000
|
||||
|
||||
用途:equipment_acceptance_orders 增加 flow_no、request_title、request_created_at。
|
||||
依赖:ea9d1e2f3a4b 已加上 oa_system。不改合同付款表。
|
||||
逻辑:三列可空。已有行留空,下次同步按来源回填。创建时间不是本地行的 created_at。
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "ea1b2c3d4e5f"
|
||||
down_revision = "ea9d1e2f3a4b"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""加上流程编号、标题和创建时间。已有单据留空,等下一次同步写入。"""
|
||||
op.add_column(
|
||||
"equipment_acceptance_orders",
|
||||
sa.Column("flow_no", sa.String(length=1000), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"equipment_acceptance_orders",
|
||||
sa.Column("request_title", sa.String(length=1000), nullable=True),
|
||||
)
|
||||
op.add_column(
|
||||
"equipment_acceptance_orders",
|
||||
sa.Column("request_created_at", sa.DateTime(), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""去掉流程编号、标题和创建时间。"""
|
||||
op.drop_column("equipment_acceptance_orders", "request_created_at")
|
||||
op.drop_column("equipment_acceptance_orders", "request_title")
|
||||
op.drop_column("equipment_acceptance_orders", "flow_no")
|
||||
@@ -0,0 +1,51 @@
|
||||
"""设备验收快照增加来源,E10 与 E8 的流程号分开。
|
||||
|
||||
Revision ID: ea9d1e2f3a4b
|
||||
Revises: b51c9e4a7d30, tt21c8d9e0f1a2
|
||||
Create Date: 2026-10-26 16:20:00.000000
|
||||
|
||||
用途:equipment_acceptance_orders 增加 oa_system,唯一约束改为 (oa_system, request_id)。
|
||||
依赖:equipment_acceptance_orders 已存在。不改合同付款表。
|
||||
逻辑:已有行回填 e10。E8 的 request_id 可以与 E10 相同,不能再共用单列唯一。
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "ea9d1e2f3a4b"
|
||||
down_revision = ("b51c9e4a7d30", "tt21c8d9e0f1a2")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
"""加上来源列,并把唯一约束从 request_id 改成来源加流程号。"""
|
||||
op.add_column(
|
||||
"equipment_acceptance_orders",
|
||||
sa.Column("oa_system", sa.String(length=8), nullable=False, server_default="e10"),
|
||||
)
|
||||
op.drop_constraint(
|
||||
"uq_equipment_acceptance_orders_request_id",
|
||||
"equipment_acceptance_orders",
|
||||
type_="unique",
|
||||
)
|
||||
op.create_unique_constraint(
|
||||
"uq_equipment_acceptance_orders_oa_request",
|
||||
"equipment_acceptance_orders",
|
||||
["oa_system", "request_id"],
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
"""去掉来源列,恢复只按 request_id 唯一。E8 行若与 E10 撞号,降级会失败。"""
|
||||
op.drop_constraint(
|
||||
"uq_equipment_acceptance_orders_oa_request",
|
||||
"equipment_acceptance_orders",
|
||||
type_="unique",
|
||||
)
|
||||
op.create_unique_constraint(
|
||||
"uq_equipment_acceptance_orders_request_id",
|
||||
"equipment_acceptance_orders",
|
||||
["request_id"],
|
||||
)
|
||||
op.drop_column("equipment_acceptance_orders", "oa_system")
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
"""合并设备验收流程字段与复核行决策码两条 Alembic 头。
|
||||
|
||||
Revision ID: mh24f5a6b7c8
|
||||
Revises: ea1b2c3d4e5f, s20a1b2c3d4e
|
||||
Create Date: 2026-10-28 10:55:00.000000
|
||||
|
||||
用途:将 ``ea1b2c3d4e5f``(设备验收流程编号、标题与来源)与
|
||||
``s20a1b2c3d4e``(复核行决策码改名)收成单一升级路径。
|
||||
依赖:``ea1b2c3d4e5f``、``s20a1b2c3d4e``。
|
||||
逻辑:不修改业务表,只声明两条已完成迁移线在此收敛。
|
||||
"""
|
||||
|
||||
from alembic import op # noqa: F401 - Alembic migration module contract
|
||||
|
||||
|
||||
revision = "mh24f5a6b7c8"
|
||||
down_revision = ("ea1b2c3d4e5f", "s20a1b2c3d4e")
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""合并设备验收 head 与复核行决策码 head,不执行数据库结构变更。"""
|
||||
pass
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""撤销合并节点;不会回滚两个父分支的业务变更。"""
|
||||
pass
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
migrations/versions/s20a1b2c3d4e_review_line_decision_code_rename.py
|
||||
|
||||
用途:批次 S 漏网补丁——复核行决定表的决策码迁移。
|
||||
s17b(表改名)/s17c(枚举数据替换)/s18 均未覆盖
|
||||
shipping_order_review_line_decisions.decision_code:旧码数据不搬、
|
||||
ck_shipping_review_line_decisions_code 不重建,导致新代码写入
|
||||
release_onhand_shortage / wait_onhand 时撞 prod 旧 CHECK
|
||||
(IntegrityError,自动放行被吞、人工放行报错)。
|
||||
依赖:alembic.op、SQLAlchemy;down_revision 为 mh23e4f5a6b7(现仓库唯一 head)。
|
||||
逻辑:先 drop 旧 CHECK(否则新码 UPDATE 直接违约),再做两次精确值替换
|
||||
(release_inventory_shortage→release_onhand_shortage、
|
||||
wait_inventory→wait_onhand,其余码不变),最后按
|
||||
models/shipping_order_review_line_decision.py 的现行码集重建同名 CHECK。
|
||||
line_status 的 CHECK 已是新集(released_shortage 早已在列),本迁移不动。
|
||||
snapshot_json 内的历史码是审计快照,按不可变原则不改写。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
|
||||
revision = "s20a1b2c3d4e"
|
||||
down_revision = "mh23e4f5a6b7"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_TABLE = "shipping_order_review_line_decisions"
|
||||
_CHECK = "ck_shipping_review_line_decisions_code"
|
||||
|
||||
# 与模型 CheckConstraint 逐字一致的新码集(升级方向)
|
||||
_NEW_CODES = (
|
||||
"'wait_onhand', 'use_new_inventory_file', 'change_inventory_source', "
|
||||
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_onhand_shortage'"
|
||||
)
|
||||
# hg1i2j3k4l5m 时的旧码集(降级方向)
|
||||
_OLD_CODES = (
|
||||
"'wait_inventory', 'use_new_inventory_file', 'change_inventory_source', "
|
||||
"'fulfill_complete_line_now', 'close_unfulfillable', 'reopen', 'release_inventory_shortage'"
|
||||
)
|
||||
|
||||
# 旧码 → 新码(词根 inventory→onhand 的两个改名对;升级方向)
|
||||
_UPDATES_UP: tuple[tuple[str, str], ...] = (
|
||||
("release_inventory_shortage", "release_onhand_shortage"),
|
||||
("wait_inventory", "wait_onhand"),
|
||||
)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# [STEP 1] 先摘旧 CHECK:旧码集不含新码,先改值必违约。
|
||||
op.drop_constraint(_CHECK, _TABLE, type_="check")
|
||||
# [STEP 2] 精确值替换(只碰两个改名对,其余决策码保持原值)。
|
||||
for old, new in _UPDATES_UP:
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"UPDATE {_TABLE} SET decision_code = :new WHERE decision_code = :old"
|
||||
).bindparams(old=old, new=new)
|
||||
)
|
||||
# [STEP 3] 按模型现行码集重建同名 CHECK。
|
||||
op.create_check_constraint(_CHECK, _TABLE, f"decision_code IN ({_NEW_CODES})")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# [STEP 1] 先摘新 CHECK,再把新码精确换回旧码。
|
||||
op.drop_constraint(_CHECK, _TABLE, type_="check")
|
||||
for old, new in _UPDATES_UP:
|
||||
op.execute(
|
||||
sa.text(
|
||||
f"UPDATE {_TABLE} SET decision_code = :old WHERE decision_code = :new"
|
||||
).bindparams(old=old, new=new)
|
||||
)
|
||||
# [STEP 2] 恢复旧码集 CHECK。
|
||||
op.create_check_constraint(_CHECK, _TABLE, f"decision_code IN ({_OLD_CODES})")
|
||||
@@ -2255,3 +2255,51 @@ def test_evidence_files_list_returns_today_size_and_presigned_url(
|
||||
event_type="TRANSFER_INBOUND_FILES_DOWNLOADED",
|
||||
).one()
|
||||
assert audit.aggregate_id == EVIDENCE_SOURCE
|
||||
|
||||
|
||||
def test_evidence_file_download_streams_through_the_site(
|
||||
app, client, admin_headers, monkeypatch,
|
||||
):
|
||||
"""单文件下载由当前站点回传,保存名不用对象键。"""
|
||||
now = datetime.utcnow().replace(microsecond=0)
|
||||
source = _ensure_evidence_source()
|
||||
report = _seed_evidence_file(
|
||||
source, kind="inbound", filename="Inbound.xlsx",
|
||||
storage_key="evidence/one", sha="61" * 32, file_size=12,
|
||||
created_at=now,
|
||||
)
|
||||
_patch_archive_bytes(monkeypatch, {"evidence/one": b"PK-xlsx"})
|
||||
|
||||
response = client.get(
|
||||
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files/{report.id}?record_kind=inbound",
|
||||
headers=admin_headers,
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
# [断言意图] 响应体是对象内容,不是跳到 MinIO 的地址。
|
||||
assert response.data == b"PK-xlsx"
|
||||
from app.api.in_transit_transfer import evidence_download_filename
|
||||
|
||||
download_name = evidence_download_filename(EVIDENCE_SOURCE, now, "Inbound.xlsx")
|
||||
# [断言意图] 保存名沿用库存源加东八区时间,浏览器不会落到哈希对象键。
|
||||
assert download_name in response.headers.get("Content-Disposition", "")
|
||||
|
||||
|
||||
def test_evidence_file_download_rejects_unavailable_file(app, client, admin_headers):
|
||||
"""已清理或不在可用窗口的归档不能经站点下载。"""
|
||||
now = datetime.utcnow().replace(microsecond=0)
|
||||
source = _ensure_evidence_source()
|
||||
report = _seed_evidence_file(
|
||||
source, kind="inbound", filename="Deleted.xlsx",
|
||||
storage_key="evidence/gone", sha="62" * 32, file_size=12,
|
||||
created_at=now, deleted=True,
|
||||
)
|
||||
|
||||
response = client.get(
|
||||
f"{API_PREFIX}/sources/{EVIDENCE_SOURCE}/evidence-files/{report.id}?record_kind=inbound",
|
||||
headers=admin_headers,
|
||||
)
|
||||
|
||||
# [断言意图] 清单里不会出现的文件,单文件下载同样拒绝。
|
||||
assert response.status_code == 404
|
||||
assert response.get_json()["error"]["code"] == "SHIPPING.INBOUND_FILE_NOT_FOUND"
|
||||
@@ -3,7 +3,7 @@ tests/services/admin/test_shipping_inventory_service.py
|
||||
|
||||
用途:验证库存主数据管理服务的安全性和关键业务约束。
|
||||
依赖:Flask app/db、freight_rpa_source_admin_service、shipping_onhand_admin_service、库存配置模型。
|
||||
逻辑:管理后台写配置前锁定凭据脱敏、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
|
||||
逻辑:管理后台写配置前锁定用户名可回显、密码与密文不回传、Driver 一致、规则发布不可变和 ERP 默认映射唯一性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,6 +22,7 @@ from app.models import (
|
||||
FreightRpaSource,
|
||||
FreightRpaSourceParsingBindingAudit,
|
||||
FreightRpaOnhandStructureAnalysis,
|
||||
FreightRpaProfile,
|
||||
)
|
||||
|
||||
|
||||
@@ -160,15 +161,50 @@ def _published_route_field_id() -> str:
|
||||
)
|
||||
|
||||
|
||||
def test_profile_credentials_are_not_returned(app):
|
||||
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
|
||||
def test_profile_returns_username_and_keeps_password_secret(app):
|
||||
"""Profile 回执返回用户名明文,密码与密文不得出现。相同用户名再次保存不轮换密文。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
# 用户名是账号标识,管理端需要明文辨认;密码只报告已配置。
|
||||
assert payload['username'] == 'test-user'
|
||||
assert payload['password_configured'] is True
|
||||
assert payload['username_masked'] == 'configured'
|
||||
assert 'password' not in payload
|
||||
assert 'ciphertext' not in payload
|
||||
stored = db.session.get(FreightRpaProfile, payload['id'])
|
||||
original_username = stored.username_ciphertext
|
||||
original_password = stored.password_ciphertext
|
||||
original_updated_at = stored.credential_updated_at
|
||||
unchanged = _profile_data()
|
||||
unchanged.pop('password')
|
||||
unchanged['display_name'] = 'DBS EU renamed'
|
||||
again = freight_rpa_source_admin_service.save_profile(unchanged, actor_id=None, profile_id=payload['id'])
|
||||
# 回显后的原用户名随表单提交时,不得重加密或刷新凭据时间。
|
||||
assert again['username'] == 'test-user'
|
||||
db.session.refresh(stored)
|
||||
assert stored.username_ciphertext == original_username
|
||||
assert stored.password_ciphertext == original_password
|
||||
assert stored.credential_updated_at == original_updated_at
|
||||
assert stored.display_name == 'DBS EU renamed'
|
||||
|
||||
|
||||
def test_profile_username_change_reencrypts_without_touching_password(app):
|
||||
"""只改用户名时重写用户名密文,密码密文保持不变。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
stored = db.session.get(FreightRpaProfile, payload['id'])
|
||||
original_username = stored.username_ciphertext
|
||||
original_password = stored.password_ciphertext
|
||||
changed = _profile_data()
|
||||
changed.pop('password')
|
||||
changed['username'] = 'other-user'
|
||||
updated = freight_rpa_source_admin_service.save_profile(changed, actor_id=None, profile_id=payload['id'])
|
||||
assert updated['username'] == 'other-user'
|
||||
db.session.refresh(stored)
|
||||
assert stored.username_ciphertext != original_username
|
||||
assert stored.password_ciphertext == original_password
|
||||
|
||||
|
||||
def test_profile_rejects_page_operation_configuration(app):
|
||||
@@ -620,29 +656,23 @@ def test_upload_config_change_does_not_bump_rpa_profile_version(app):
|
||||
profile = freight_rpa_source_admin_service.save_profile(_profile_data(), actor_id=None)
|
||||
base_version = profile['config_version']
|
||||
upload_cfg = {
|
||||
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
|
||||
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
|
||||
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
|
||||
'enabled': True, 'entry_url': 'https://evil.example/steal',
|
||||
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file',
|
||||
}
|
||||
updated = freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
assert updated['config_version'] == base_version
|
||||
assert updated['upload_config_json']['enabled'] is True
|
||||
assert updated['upload_config_json'] == {'enabled': True}
|
||||
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
|
||||
bumped = freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
assert bumped['config_version'] == base_version + 1
|
||||
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
|
||||
# 上传配置必须是对象;页面字段不再作为校验对象。
|
||||
with pytest.raises(ValidationError):
|
||||
freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
with pytest.raises(ValidationError):
|
||||
freight_rpa_source_admin_service.save_profile(
|
||||
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
|
||||
{**_profile_data(), 'upload_config_json': 'not-an-object'},
|
||||
actor_id=None, profile_id=profile['id'],
|
||||
)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
backend/tests/services/file_assets/test_storage_presign.py
|
||||
|
||||
用途:验证业务文件预签名下载地址使用浏览器可访问的 MinIO 主机。
|
||||
依赖:file_assets.storage、minio。
|
||||
逻辑:正式环境内网端点与公网基址不同;断言签名 URL 的主机是公网基址,读写客户端仍是内网端点。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.file_assets import storage as storage_mod
|
||||
from app.services.file_assets.storage import resolve_presign_endpoint
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _patch_minio_config(monkeypatch, *, public_base: str, secure: bool = False) -> None:
|
||||
"""把存储配置钉成正式环境形态:容器内网端点 + 浏览器公网基址。"""
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_ENDPOINT", "host.docker.internal:9000")
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_ACCESS_KEY", "test-access")
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECRET_KEY", "test-secret")
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_SECURE", secure)
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_PUBLIC_BASE_URL", public_base)
|
||||
monkeypatch.setattr(storage_mod._cfg, "MINIO_FILE_ASSETS_BUCKET", "hxops-file-assets")
|
||||
|
||||
|
||||
def test_resolve_presign_endpoint_keeps_explicit_port():
|
||||
"""公网基址的非默认端口必须留在预签名端点里。"""
|
||||
endpoint, secure = resolve_presign_endpoint(
|
||||
"http://ai.well-trust.com:9000",
|
||||
"host.docker.internal:9000",
|
||||
False,
|
||||
)
|
||||
# [断言意图] 正式环境浏览器入口是 9000,不能收成 80。
|
||||
assert endpoint == "ai.well-trust.com:9000"
|
||||
assert secure is False
|
||||
|
||||
|
||||
def test_resolve_presign_endpoint_falls_back_when_public_base_empty():
|
||||
"""公网基址为空时继续用内网端点,避免签出空主机。"""
|
||||
endpoint, secure = resolve_presign_endpoint("", "192.168.100.192:9000", False)
|
||||
# [断言意图] 未配置公网基址时行为与改前一致。
|
||||
assert endpoint == "192.168.100.192:9000"
|
||||
assert secure is False
|
||||
|
||||
|
||||
def test_presigned_get_url_uses_public_host(monkeypatch):
|
||||
"""正式环境下载链接的主机必须是 MINIO_PUBLIC_BASE_URL。"""
|
||||
_patch_minio_config(monkeypatch, public_base="http://ai.well-trust.com:9000")
|
||||
store = storage_mod.FileAssetStorage()
|
||||
monkeypatch.setattr(store, "_ensure_bucket_exists", lambda: None)
|
||||
|
||||
url = store.presigned_get_url(
|
||||
"shipping/outbound-reports/2026/10/1/abc.xlsx",
|
||||
expires_seconds=300,
|
||||
download_name="CRANE_20261020_1815.xlsx",
|
||||
)
|
||||
|
||||
# [断言意图] 浏览器打开的是公网 MinIO,签名里不能再出现容器内网主机。
|
||||
assert url.startswith(
|
||||
"http://ai.well-trust.com:9000/hxops-file-assets/shipping/outbound-reports/2026/10/1/abc.xlsx?"
|
||||
)
|
||||
assert "host.docker.internal" not in url
|
||||
assert "X-Amz-Signature=" in url
|
||||
assert "response-content-disposition=" in url
|
||||
# [断言意图] 读写仍走容器内网端点,避免把公网主机写进上传客户端。
|
||||
assert store.client is not store.presign_client
|
||||
assert store.client._base_url.host == "host.docker.internal:9000"
|
||||
assert store.presign_client._base_url.host == "ai.well-trust.com:9000"
|
||||
|
||||
|
||||
def test_presigned_get_url_reuses_client_when_hosts_match(monkeypatch):
|
||||
"""内网端点与公网基址相同时不另建客户端。"""
|
||||
_patch_minio_config(monkeypatch, public_base="http://host.docker.internal:9000")
|
||||
store = storage_mod.FileAssetStorage()
|
||||
# [断言意图] 开发环境两端点一致,预签名与读写共用同一客户端。
|
||||
assert store.presign_client is store.client
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
backend/tests/services/freight_rpa/test_crane_upload_recheck.py
|
||||
|
||||
用途:验证上传配置只保留开关,以及 Crane 分配中只排一次定时回查。
|
||||
依赖:page_contract、upload_attempt_service、crane_recheck、Flask 测试库。
|
||||
逻辑:先断言入口 URL 和行分类,再走 complete_attempt、定时回查和手动刷新。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.services.freight_rpa.upload.crane_recheck import (
|
||||
fire_scheduled_crane_recheck,
|
||||
request_manual_crane_refresh,
|
||||
)
|
||||
from app.services.freight_rpa.upload.page_contract import (
|
||||
build_upload_entry_url,
|
||||
classify_crane_order_row,
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
complete_attempt,
|
||||
project_notice_upload_status,
|
||||
start_rpa_attempt,
|
||||
)
|
||||
from tests.test_shipping_upload_attempt import _ready_artifact
|
||||
|
||||
|
||||
def test_upload_entry_url_comes_from_login_host_and_crane_row_is_classified():
|
||||
"""DBS/Crane 上传页由登录主机拼接;只有两句固定文案分别表示已分配和分配中。"""
|
||||
assert build_upload_entry_url('dbs', 'https://s360.dbschenker.com/login') == (
|
||||
'https://s360.dbschenker.com/main/portal/frame/WMSUpload2'
|
||||
)
|
||||
assert build_upload_entry_url('crane', 'https://wms-portal.craneww.com/') == (
|
||||
'https://wms-portal.craneww.com/#/shipping-order-upload'
|
||||
)
|
||||
assert classify_crane_order_row('Processing', 'Shipping Order Allocated') == 'allocated'
|
||||
assert classify_crane_order_row('Processing', 'Allocating the Shipping Order') == 'allocating'
|
||||
assert classify_crane_order_row('Completed', 'Shipping Order Allocated') == 'other'
|
||||
|
||||
|
||||
def test_allocating_schedules_one_recheck_and_blocks_another_upload(app):
|
||||
"""首次分配中写下 10 分钟回查;第二次回调不改到期时间,也不能重新上传。"""
|
||||
with app.app_context():
|
||||
notice, artifact, _reservation = _ready_artifact()
|
||||
artifact.file_name = 'MXI26082801.xlsx'
|
||||
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key')
|
||||
started = datetime(2026, 10, 23, 3, 0, 0)
|
||||
complete_attempt(attempt, success=False, callback_id='upload-1', result='allocating')
|
||||
# remember 使用 utcnow;这里只断言间隔为 10 分钟,不绑定测试开始时刻。
|
||||
due_at = datetime.fromisoformat(attempt.success_evidence_json['crane_recheck']['due_at'])
|
||||
assert timedelta(minutes=9) < due_at - datetime.utcnow() <= timedelta(minutes=10)
|
||||
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
|
||||
assert project_notice_upload_status(notice) == 'allocating'
|
||||
|
||||
complete_attempt(attempt, success=False, callback_id='recheck-1', result='allocating')
|
||||
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at.isoformat(timespec='seconds')
|
||||
|
||||
with pytest.raises(ConflictError) as blocked:
|
||||
start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-key-2')
|
||||
assert blocked.value.code == 'SHIPPING.UPLOAD_CRANE_ALLOCATING'
|
||||
assert started < due_at
|
||||
|
||||
|
||||
def test_manual_refresh_does_not_move_the_one_scheduled_recheck(app):
|
||||
"""手动刷新另写一条状态回查,不改定时到期时间,也不把定时标记成已触发。"""
|
||||
with app.app_context():
|
||||
notice, artifact, _reservation = _ready_artifact()
|
||||
attempt = start_rpa_attempt(notice, artifact_id=artifact.id, idempotency_key='crane-manual')
|
||||
complete_attempt(attempt, success=False, callback_id='upload-manual', result='allocating')
|
||||
due_at = attempt.success_evidence_json['crane_recheck']['due_at']
|
||||
source = {'login_url': 'https://wms-portal.craneww.com/', 'connector_type': 'crane'}
|
||||
|
||||
first = request_manual_crane_refresh(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
|
||||
)
|
||||
assert first.endswith(f'upload_recheck_{notice.task_no}_manual.json')
|
||||
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
|
||||
assert attempt.success_evidence_json['crane_recheck']['fired'] is False
|
||||
|
||||
with pytest.raises(ConflictError) as inflight:
|
||||
request_manual_crane_refresh(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path,
|
||||
)
|
||||
assert inflight.value.code == 'SHIPPING.UPLOAD_CRANE_REFRESH_INFLIGHT'
|
||||
|
||||
future = datetime.fromisoformat(due_at) + timedelta(seconds=1)
|
||||
assert fire_scheduled_crane_recheck(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
|
||||
) is True
|
||||
assert fire_scheduled_crane_recheck(
|
||||
attempt, source, task_no=notice.task_no, export_file_path=artifact.file_path, now=future,
|
||||
) is False
|
||||
db.session.refresh(attempt)
|
||||
assert attempt.success_evidence_json['crane_recheck']['due_at'] == due_at
|
||||
assert attempt.success_evidence_json['crane_recheck']['fired'] is True
|
||||
@@ -1,16 +1,18 @@
|
||||
"""在途调拨单据级执行测试(execute_items 同步组合路径:门禁 + 组建单 + 逐单执行)。
|
||||
|
||||
用途:验证同步执行组合入口的两道门禁(①存在且可执行 ②文件版本对账,失败路径
|
||||
均携带 details 列表且外部系统 写入为 0;原「行级新鲜度 TTL」门禁已于
|
||||
2026-09-25 退役——items_stale 拒绝用例随之删除,TTL 降级为前端展示徽标)、
|
||||
D1 五元组建单与单据级写语义(一单一次 create_transfer、单内行共享单结果)、
|
||||
写前路由复查(漂移阻断)、result_unknown 不自动重试、单间失败隔离
|
||||
(不同组互不影响)、匹配 scope 执行入口(execute_matching_items)与按
|
||||
外部系统 单号投影。
|
||||
用途:验证同步执行组合入口的执行存在性门禁(①存在且可执行,失败携带 details
|
||||
列表且外部系统 写入为 0;原「文件版本对账」门禁已于 2026-10-22 退役——
|
||||
文件更新/缺失不再拦执行,行装饰 file_current 徽标仅提示,防错下沉 worker
|
||||
写前库存复查;原「行级新鲜度 TTL」门禁已于 2026-09-25 退役——items_stale
|
||||
拒绝用例随之删除,TTL 降级为前端展示徽标)、D1 五元组建单与单据级写语义
|
||||
(一单一次 create_transfer、单内行共享单结果)、写前路由复查(漂移阻断)、
|
||||
result_unknown 不自动重试、单间失败隔离(不同组互不影响)、匹配 scope
|
||||
执行入口(execute_matching_items)与按外部系统单号投影。
|
||||
依赖:transfer_db、fakes、repo_fakes、matching_service、execution_service。
|
||||
逻辑:T10 单据级重构后执行单元 = ERP 调拨单(TransferDocument);本文件为存量按行
|
||||
执行测试的按单改写版(场景不弱化:门禁/幂等/隔离/投影逐一保留);
|
||||
文件对账门禁经 patch_source_file_status 夹具注入来源文件状态投影替身。
|
||||
来源文件状态投影经 patch_source_file_status 夹具注入替身(装饰断言另打
|
||||
matching_service 命名空间)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,6 +31,7 @@ from app.services.in_transit_transfer.matching_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
create_matching,
|
||||
list_executable_items,
|
||||
)
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps, seed_rows_from_file
|
||||
@@ -252,35 +255,57 @@ def test_execute_items_rejects_unknown_or_not_ready_ids(transfer_db, dbs_ready_f
|
||||
assert _execution_runs() == []
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_file_updated(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁②:来源最新可用文件版本 ≠ 行评估版本戳(文件已更新未重新匹配)→ FILE_CHANGED。"""
|
||||
# monkeypatch resolve_source_file_status 返回新 checksum:模拟"文件更新但未重新匹配",
|
||||
# (重跑匹配会把行原地刷成新版本,无法构造本场景)。
|
||||
def test_execute_items_proceeds_when_file_updated_and_decorates_not_current(
|
||||
transfer_db, dbs_ready_file, patch_source_file_status, monkeypatch,
|
||||
):
|
||||
"""[2026-10-22 文件版本对账门禁退役] 文件已更新不再是执行门禁。
|
||||
|
||||
入站抓取是部分导出——新文件不含某行 ≠ 该行失效/已处理,按最新文件 sha
|
||||
对账曾把大量未处理行错误卡死(业务实测 557 行积压)。执行照常写 ERP;
|
||||
行装饰 file_current=False 仅提示不拦截,防错下沉 worker 写前库存复查。
|
||||
"""
|
||||
patch_source_file_status({"DBS-AWSBI": "e" * 64})
|
||||
# 装饰读取走 matching_service 命名空间的同名投影(退役后该函数仅剩展示
|
||||
# 消费方),此处同步打桩保持与执行侧替身同源。
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.matching_service.resolve_source_file_status",
|
||||
lambda *, source_code, record_kind="inbound": {
|
||||
"file_status": "ready", "has_ready_file": True,
|
||||
"file_no": "REC-TEST", "file_sha256": "e" * 64,
|
||||
},
|
||||
)
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
# 断言:行当前性徽标如实提示「行评估版本戳 ≠ 最新可用文件」。
|
||||
listing = list_executable_items(deps=deps)
|
||||
decorated = {row.item_id: row for row in listing["items"]}
|
||||
assert all(decorated[item.id].file_current is False for item in items)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
assert _execution_runs() == []
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# 断言:徽标不拦截执行——同组两 Invoice 合并一单、一次写调用、行全 success。
|
||||
assert outcome.status == "success"
|
||||
assert len(erp.write_calls()) == 1
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in linked.values())
|
||||
|
||||
|
||||
def test_execute_items_rejects_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""门禁②:来源无可用文件(latest 无 file_sha256)也属 FILE_CHANGED(fail-closed)。"""
|
||||
def test_execute_items_proceeds_when_source_file_missing(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
"""[2026-10-22 门禁退役] 来源无可用文件同样不拦执行。
|
||||
|
||||
档是镜像事实,不随当日文件可用性消失(evidence_sync 已落档的行照常可执行)。
|
||||
"""
|
||||
patch_source_file_status({"DBS-AWSBI": None})
|
||||
deps, erp, items = _ready_items(
|
||||
dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"),
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
assert excinfo.value.code == "TRANSFER.FILE_CHANGED"
|
||||
assert sorted(excinfo.value.details["changed_item_ids"]) == sorted(item.id for item in items)
|
||||
assert erp.write_calls() == []
|
||||
outcome = execute_items(item_ids=[item.id for item in items], deps=deps)
|
||||
# 断言:无可用文件不拒绝执行——照常组建单并写入外部系统。
|
||||
assert outcome.status == "success"
|
||||
assert len(erp.write_calls()) == 1
|
||||
linked = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in linked.values())
|
||||
|
||||
|
||||
def test_execute_matching_items_executes_selected_invoices(transfer_db, dbs_ready_file, patch_source_file_status):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨匹配服务测试(L1,SQLite 内存库)。
|
||||
|
||||
用途:验证日期范围校验(截止≤业务日期)、严格数量匹配、来源隔离、
|
||||
匹配快照 Hash 稳定、缺文件等待与进度恢复;专项用例锁生产默认 lag=2。
|
||||
匹配快照 Hash 稳定、缺文件等待与进度恢复、匹配顶替;专项用例锁生产默认 lag=2。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、matching_service。
|
||||
逻辑:全部经真实 ORM 落库(create_matching/restore_matching),
|
||||
外部依赖注入 Fake 替身。圈档记录类型用例直接插出站档行,
|
||||
@@ -1152,3 +1152,182 @@ def test_cancel_matching_releases_ledger_occupancy(transfer_db, dbs_ready_file):
|
||||
born = TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
assert len(born) == 2
|
||||
assert all(row.status == "ready_to_execute" for row in born)
|
||||
|
||||
|
||||
def test_create_matching_supersedes_covered_unwritten_matching(transfer_db, dbs_ready_file):
|
||||
"""新匹配盖住同一类型、同一来源、尚未写 ERP 的旧匹配时,旧匹配取消,货出现在新匹配上。
|
||||
|
||||
夹具两行异动日都是 2026-08-04。第一次与第二次都用 08-01~08-04,新范围盖住旧范围。
|
||||
"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
covered = dict(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
|
||||
first = create_matching(deps=deps, **covered)
|
||||
# [断言意图] 顶替前旧匹配自己先圈到夹具的两张单,证明后面的 2 不是「本来就没占上」。
|
||||
assert first.counts.executable_count == 2
|
||||
|
||||
second = create_matching(deps=deps, **covered)
|
||||
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
# [断言意图] 被盖住且未写 ERP 的旧匹配不再有效,其可执行行不能留在队列里二次写 ERP。
|
||||
assert first_matching.status == "cancelled"
|
||||
retired = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id).all()
|
||||
assert retired
|
||||
assert all(row.status == "cancelled" for row in retired)
|
||||
# [断言意图] 同一批货(HOM-001、HOX-002)出现在新匹配上,且仍可执行。
|
||||
assert second.counts.executable_count == 2
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
reborn = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
}
|
||||
assert reborn == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_create_matching_supersedes_covered_matching_with_only_blocked_rows(transfer_db, dbs_ready_file):
|
||||
"""全阻断的旧匹配状态虽是 success,只要还没写 ERP,新范围盖住时仍要顶替。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
covered = dict(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
first = create_matching(deps=deps, **covered)
|
||||
# [断言意图] 数量对不上时匹配状态是 success,不能因此被当成「已经写出单据」。
|
||||
assert first.status == "success"
|
||||
assert first.counts.executable_count == 0
|
||||
|
||||
second = create_matching(deps=deps, **covered)
|
||||
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
assert first_matching.status == "cancelled"
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
reborn = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
}
|
||||
assert reborn == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_create_matching_keeps_previous_when_new_range_does_not_cover(transfer_db, dbs_ready_file):
|
||||
"""新范围盖不住旧范围时,旧匹配保持有效,货仍留在旧匹配上。"""
|
||||
from app.models import TransferMatching
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
first = create_matching(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
second = create_matching(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-04",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
# [断言意图] 08-04~08-04 盖不住 08-01~08-04,旧匹配不能被取消。
|
||||
assert first_matching.status == "ready_to_execute"
|
||||
# [断言意图] 货仍被旧匹配占用,新匹配圈不到,清单不另列历史匹配编号。
|
||||
assert second.counts.executable_count == 0
|
||||
|
||||
|
||||
def test_supersede_keeps_manually_closed_goods_out_of_the_new_matching(transfer_db, dbs_ready_file):
|
||||
"""顶替后,人工关闭的单号不回到新匹配。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
covered = dict(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
first = create_matching(deps=deps, **covered)
|
||||
first_matching = TransferMatching.query.filter_by(matching_no=first.matching_id).one()
|
||||
closed = TransferInvoiceItem.query.filter_by(matching_id=first_matching.id, invoice_no="HOX-002").one()
|
||||
manual_close_item(item_id=closed.id, reason="这批不再调拨")
|
||||
|
||||
second = create_matching(deps=deps, **covered)
|
||||
|
||||
# [断言意图] 人工关闭跨过顶替仍然有效,新匹配不能把 HOX-002 再圈成可执行。
|
||||
assert db.session.get(TransferInvoiceItem, closed.id).status == "manually_closed"
|
||||
second_matching = TransferMatching.query.filter_by(matching_no=second.matching_id).one()
|
||||
reborn = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=second_matching.id).all()
|
||||
}
|
||||
assert reborn == {"HOM-001"}
|
||||
|
||||
|
||||
def test_unattached_item_does_not_block_a_new_matching(transfer_db, dbs_ready_file):
|
||||
"""没有挂上任何匹配的明细不占货,新匹配仍能圈到那张单。"""
|
||||
from app.models import TransferInvoiceItem, TransferMatching, TransferMovementLedger
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
ledger = TransferMovementLedger.query.filter_by(source_code="DBS-AWSBI", doc_no="HOM-001").first()
|
||||
db.session.add(TransferInvoiceItem(
|
||||
matching_id=None,
|
||||
ledger_record_id=ledger.id,
|
||||
source_code="DBS-AWSBI",
|
||||
invoice_no="HOM-001",
|
||||
material_no="MAT-001",
|
||||
movement_date="2026-08-04",
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
movement_quantity="1200",
|
||||
status="matching",
|
||||
result_code="pending_stock_check",
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
summary = create_matching(
|
||||
source_codes=["DBS-AWSBI"],
|
||||
business_date="2026-08-06",
|
||||
deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
movement_date_from="2026-08-01",
|
||||
movement_date_to="2026-08-04",
|
||||
)
|
||||
matching = TransferMatching.query.filter_by(matching_no=summary.matching_id).one()
|
||||
# [断言意图] 悬挂行没有匹配编号,不能挡住 HOM-001;两张夹具单都进新匹配。
|
||||
invoices = {
|
||||
row.invoice_no
|
||||
for row in TransferInvoiceItem.query.filter_by(matching_id=matching.id).all()
|
||||
}
|
||||
assert invoices == {"HOM-001", "HOX-002"}
|
||||
@@ -3,14 +3,20 @@
|
||||
用途:验证在途自动调拨 platform job 注册契约与 handler 调用形态;
|
||||
in-transit-receipt-file 已于 2026-09-28 下线(文件就绪保障内建于自动调拨,
|
||||
见 job_registry 在途自动调拨描述),此处锁定其"不再注册"防回归。
|
||||
依赖:schedule.job_registry、inbound_trigger_service、in_transit_transfer_job。
|
||||
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
|
||||
依赖:schedule.job_registry、job_options、inbound_trigger_service、
|
||||
transfer_type_config_service、in_transit_transfer_job。
|
||||
逻辑:只验证注册契约与调用形态(run_auto_transfer/run_daily_recovery 打桩),
|
||||
真实排程触发由 scheduler 驱动;七元组位序=(total, success, failed,
|
||||
skipped, results, errors, step_logs),errors 位只放真实错误。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome
|
||||
from app.services.in_transit_transfer.recovery_service import RecoveryOutcome
|
||||
from app.services.schedule.job_options import is_known_options_source
|
||||
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
|
||||
|
||||
|
||||
@@ -22,14 +28,23 @@ def test_receipt_file_job_deregistered():
|
||||
|
||||
|
||||
def test_transfer_job_registered_with_schedule_defaults():
|
||||
"""自动调拨 job 注册且含来源/恢复参数契约;描述不得硬编码时刻。"""
|
||||
"""自动调拨 job 注册且含类型/来源/恢复参数契约;描述不得硬编码时刻。"""
|
||||
import re
|
||||
|
||||
job = get_platform_job("in-transit-transfer")
|
||||
assert job is not None
|
||||
assert job.enabled
|
||||
keys = {field.get("key") for field in job.params_schema}
|
||||
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
|
||||
assert {
|
||||
"transfer_types", "source_codes", "recover_history",
|
||||
"receipt_from_offset_days", "receipt_to_offset_days",
|
||||
} <= keys
|
||||
# 断言:调拨类型=multi_select 动态选项源(启用中的类型配置),留空=全部。
|
||||
types_field = next(f for f in job.params_schema if f.get("key") == "transfer_types")
|
||||
assert types_field.get("type") == "multi_select"
|
||||
assert types_field.get("options_source") == "transfer_types"
|
||||
assert types_field.get("default") == []
|
||||
assert is_known_options_source("transfer_types")
|
||||
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
|
||||
assert "notify_user_ids" not in keys
|
||||
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
||||
@@ -133,55 +148,108 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
|
||||
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
||||
|
||||
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
|
||||
def test_wanted_transfer_types_falls_back_to_all_enabled(monkeypatch):
|
||||
"""调拨类型留空=全部启用类型;显式选择优先;空配置/脏配置 fail-closed 落错误。"""
|
||||
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||
from app.services.schedule.in_transit_transfer_job import _wanted_transfer_types
|
||||
|
||||
errors: list[str] = []
|
||||
monkeypatch.setattr(type_mod, "get_enabled", lambda: [
|
||||
SimpleNamespace(code="in_transit_to_hub"), SimpleNamespace(code="hub_repair_out"),
|
||||
])
|
||||
assert _wanted_transfer_types({}, errors) == ["in_transit_to_hub", "hub_repair_out"]
|
||||
assert errors == []
|
||||
assert _wanted_transfer_types({"transfer_types": ["in_transit_to_hub"]}, errors) == ["in_transit_to_hub"]
|
||||
assert _wanted_transfer_types({"transfer_types": "hub_to_hub"}, errors) == ["hub_to_hub"]
|
||||
|
||||
monkeypatch.setattr(type_mod, "get_enabled", lambda: [])
|
||||
assert _wanted_transfer_types({}, errors) == []
|
||||
# 断言:空类型配置不静默——落错误由调用方硬失败(D8 fail-closed)。
|
||||
assert errors and "调拨类型" in errors[-1]
|
||||
|
||||
|
||||
def test_transfer_types_options_provider_lists_enabled(app, transfer_db):
|
||||
"""transfer_types 选项源:仅启用类型,label 取 names zh-CN,value=类型编码。"""
|
||||
from tests.services.in_transit_transfer.factories import seed_transfer_type_config
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
|
||||
seed_transfer_type_config("in_transit_to_hub", enabled=True)
|
||||
seed_transfer_type_config("hub_repair_out", enabled=False)
|
||||
transfer_db.session.commit()
|
||||
|
||||
options = list_job_options("transfer_types")
|
||||
codes = {option["value"] for option in options}
|
||||
# 断言:停用类型不进选项(与排程留空=全部启用类型的口径一致)。
|
||||
assert "in_transit_to_hub" in codes
|
||||
assert "hub_repair_out" not in codes
|
||||
label = next(o["label"] for o in options if o["value"] == "in_transit_to_hub")
|
||||
assert label == "类型 in_transit_to_hub"
|
||||
|
||||
|
||||
def _patch_schedule_env(monkeypatch, *, types=None, sources=("CRANE_SGP",)):
|
||||
"""handler 单测公共打桩:来源/类型缺省口径 + 依赖与恢复隔离(不触库)。"""
|
||||
import app.services.in_transit_transfer.transfer_type_config_service as type_mod
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: list(sources))
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
monkeypatch.setattr(
|
||||
type_mod, "get_enabled",
|
||||
lambda: [SimpleNamespace(code=code) for code in (types if types is not None else ["in_transit_to_hub"])],
|
||||
)
|
||||
return job_mod
|
||||
|
||||
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(全部类型均无 run 且无 errors):置静默标记抑制框架完成卡(C5)。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome()
|
||||
return AutoTransferOutcome()
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
|
||||
run = ScheduleRun(run_no="RUNR-1", status="running")
|
||||
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
total, success, failed, skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
|
||||
assert "sender" not in captured
|
||||
assert "recipients" not in captured
|
||||
# 断言:恢复在循环外只跑一次;run_auto_transfer 恒收 recover_history=False。
|
||||
assert captured["recover_history"] is False
|
||||
assert captured["movement_date_from"] is None
|
||||
assert captured["movement_date_to"] is None
|
||||
assert captured["source_codes"] == ["CRANE_SGP"]
|
||||
assert captured["recover_history"] is True
|
||||
assert captured["transfer_type"] == "in_transit_to_hub"
|
||||
assert run.response_summary_json["domain_notification_managed"] is True
|
||||
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
||||
assert results == []
|
||||
assert any("no executable items" in w for w in warnings)
|
||||
assert results == [] and errors == []
|
||||
# 断言:恢复汇总与空数据说明落 step_logs(dict),errors 位不受污染。
|
||||
assert step_logs[0]["step"] == "recovery"
|
||||
assert any(item.get("step") == "auto_transfer" for item in step_logs)
|
||||
|
||||
|
||||
def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
|
||||
from datetime import date
|
||||
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome()
|
||||
return AutoTransferOutcome()
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
|
||||
run = ScheduleRun(run_no="RUNR-4", status="running")
|
||||
@@ -195,79 +263,227 @@ def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
|
||||
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run with invalid offsets")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
run = ScheduleRun(run_no="RUNR-5", status="running")
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名;
|
||||
# failed_count=1 使终态为 failed(total=0+errors 会被框架误判 success,禁用)。
|
||||
assert (total, failed) == (1, 1)
|
||||
assert results == []
|
||||
assert any("异动日期起点" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
|
||||
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
||||
_total, _success, _failed, _skipped, _results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:小数偏移同样快速失败。
|
||||
assert any("异动日期终点" in e for e in errors)
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
def test_handler_runs_each_type_once_and_recovery_once(monkeypatch):
|
||||
"""多类型逐轮执行:每类型一次 run_auto_transfer(recover_history=False),恢复只跑一次。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=["in_transit_to_hub", "hub_repair_out"])
|
||||
recovery_calls: list[dict] = []
|
||||
|
||||
def _fake_recovery(**kwargs):
|
||||
recovery_calls.append(kwargs)
|
||||
return RecoveryOutcome(recovered_count=2)
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _fake_recovery)
|
||||
calls: list[dict] = []
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
calls.append(kwargs)
|
||||
return AutoTransferOutcome(run_no=f"TR-{len(calls)}", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={"transfer_types": ["in_transit_to_hub", "hub_repair_out"]})
|
||||
run = ScheduleRun(run_no="RUNR-6", status="running")
|
||||
total, success, failed, skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:逐类型各跑一轮且带类型编码;恢复与类型无关只跑一次。
|
||||
assert [c["transfer_type"] for c in calls] == ["in_transit_to_hub", "hub_repair_out"]
|
||||
assert all(c["recover_history"] is False for c in calls)
|
||||
assert len(recovery_calls) == 1
|
||||
# 断言:total=success+failed+recovered(2 成功 Run + 2 恢复行)。
|
||||
assert (total, success, failed, skipped) == (4, 2, 0, 0)
|
||||
assert [r["run_no"] for r in results] == ["TR-1", "TR-2"]
|
||||
assert errors == []
|
||||
# 断言:恢复汇总落 step_logs(recovered=2),errors 位只放真实错误。
|
||||
assert step_logs[0]["step"] == "recovery"
|
||||
assert step_logs[0]["detail"]["recovered"] == 2
|
||||
|
||||
|
||||
def test_handler_empty_type_config_fails_hard(monkeypatch):
|
||||
"""类型配置为空:fail-closed 硬失败(failed=1 → 框架 failed 终态),不执行。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=[])
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run without transfer types")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-7", status="running")
|
||||
total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:空配置硬失败不执行、不静默,错误信息指向类型配置缺失。
|
||||
assert (total, failed) == (1, 1)
|
||||
assert results == []
|
||||
assert any("调拨类型" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-2", status="running")
|
||||
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
total, success, failed, skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
|
||||
# 断言:有 run 不抑制框架通知;run_no+类型落入 results 供完成卡/留痕展示。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results and results[0]["run_no"] == "TR-1"
|
||||
assert results[0]["transfer_type"] == "in_transit_to_hub"
|
||||
assert (total, success, failed, skipped) == (1, 1, 0, 0)
|
||||
assert errors == []
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
def test_handler_recovery_failure_counts_as_failed(monkeypatch):
|
||||
"""恢复复核抛异常:计一个 failed 单元——防止「恢复失败+空数据日」被框架判 success。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_inbound_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _boom(**_kwargs):
|
||||
raise RuntimeError("stock source offline")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _boom)
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
return AutoTransferOutcome() # 各类型均空数据(无 Run 无错误)
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-9", status="running")
|
||||
total, success, failed, _skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:恢复失败落 errors 且计 failed(终态 failed 交框架失败通知),
|
||||
# 恢复 step_log 标 failed;不置静默标记。
|
||||
assert (total, success, failed) == (1, 0, 1)
|
||||
assert results == []
|
||||
assert errors == ["recovery_failed: stock source offline"]
|
||||
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "failed"
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
|
||||
def test_handler_recovery_skipped_marks_step_log(monkeypatch):
|
||||
"""recover_history=false:恢复不执行,step_log 标 skipped 且不计 failed。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
|
||||
def _must_not_recover(**_kwargs):
|
||||
raise AssertionError("run_daily_recovery must not run when recover_history is false")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", _must_not_recover)
|
||||
monkeypatch.setattr(
|
||||
job_mod, "run_auto_transfer",
|
||||
lambda **_kwargs: AutoTransferOutcome(run_no="TR-10", run_status="success"),
|
||||
)
|
||||
|
||||
task = ScheduleTask(job_params={"recover_history": False})
|
||||
run = ScheduleRun(run_no="RUNR-10", status="running")
|
||||
total, success, failed, _skipped, results, errors, step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:恢复被跳过(step_log=skipped、无恢复错误),Run 照常产出。
|
||||
assert (total, success, failed) == (1, 1, 0)
|
||||
assert results and results[0]["run_no"] == "TR-10"
|
||||
assert errors == []
|
||||
assert step_logs[0]["step"] == "recovery" and step_logs[0]["status"] == "skipped"
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch)
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-3", status="running")
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
_total, _success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results,
|
||||
# 该类型计入 failed_count(终态 failed 交框架失败通知)。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results == []
|
||||
assert errors == ["match pipeline boom"]
|
||||
assert failed == 1
|
||||
|
||||
|
||||
def test_handler_type_failure_isolated_per_type(monkeypatch):
|
||||
"""单类型硬失败不阻断其余类型;失败类型计入 failed,成功类型照常出 Run。"""
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
job_mod = _patch_schedule_env(monkeypatch, types=["bad_type", "in_transit_to_hub"])
|
||||
monkeypatch.setattr(job_mod, "run_daily_recovery", lambda **_kw: RecoveryOutcome())
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
if kwargs["transfer_type"] == "bad_type":
|
||||
return AutoTransferOutcome(errors=["type config disabled"])
|
||||
return AutoTransferOutcome(run_no="TR-9", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-8", status="running")
|
||||
total, success, failed, _skipped, results, errors, _step_logs = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:好类型照常执行出 Run;坏类型落 errors 并计入 failed(部分失败终态)。
|
||||
assert (total, success, failed) == (2, 1, 1)
|
||||
assert len(results) == 1 and results[0]["transfer_type"] == "in_transit_to_hub"
|
||||
assert errors == ["type config disabled"]
|
||||
@@ -4,6 +4,7 @@ backend/tests/test_contract_payment_ledger_focus.py
|
||||
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
||||
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、进行中、本月应付合同后核对计数与 focus 筛选。
|
||||
金额和比例都为 0 的验收款不把合同算进逾期。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,7 +13,7 @@ from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.services.contract_payment.ledger_focus import ledger_focus_counts
|
||||
from app.services.contract_payment.ledger_focus import classify_ledger_status, ledger_focus_counts
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
@@ -136,3 +137,37 @@ def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
|
||||
assert summary.get_json()['data']['active'] == 2
|
||||
assert 'needs_completion' not in summary.get_json()['data']
|
||||
assert empty.get_json()['data']['total'] == 0
|
||||
|
||||
|
||||
def test_zero_amount_stage_does_not_mark_contract_overdue():
|
||||
"""金额和比例都为 0 的阶段不参与逾期。"""
|
||||
status = classify_ledger_status(
|
||||
contract_status='active',
|
||||
parse_status='parsed',
|
||||
nodes=[
|
||||
{
|
||||
'status': 'paid',
|
||||
'percentage': '50',
|
||||
'amount': '4250.00',
|
||||
'due_date': date(2026, 9, 2),
|
||||
'anchor_date': date(2026, 9, 2),
|
||||
},
|
||||
{
|
||||
'status': 'active',
|
||||
'percentage': '0',
|
||||
'amount': '0.00',
|
||||
'due_date': date(2026, 9, 24),
|
||||
'anchor_date': date(2026, 9, 24),
|
||||
},
|
||||
{
|
||||
'status': 'active',
|
||||
'percentage': '0',
|
||||
'amount': '0.00',
|
||||
'due_date': date(2027, 3, 23),
|
||||
'anchor_date': date(2026, 9, 24),
|
||||
},
|
||||
],
|
||||
today=date(2026, 10, 27),
|
||||
)
|
||||
# 关键断言:预付款已付,验收款和质保款为 0,合同应为已完成而不是已逾期。
|
||||
assert status == 'completed'
|
||||
@@ -915,7 +915,14 @@ def test_erp_combined_payment_marks_prepayment_and_shipment_paid():
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("43200")]) == {1, 2}
|
||||
|
||||
|
||||
def test_oa_company_dropdown_uses_selected_option(app):
|
||||
def test_erp_payment_matches_acceptance_amount_without_consuming_earlier_stages():
|
||||
"""关键断言:验收款金额单独命中时只标验收款,不把预付款或出货款记成已付。"""
|
||||
nodes = [
|
||||
(1, "prepayment", Decimal("16740")),
|
||||
(2, "shipment", Decimal("27900")),
|
||||
(3, "acceptance", Decimal("11160")),
|
||||
]
|
||||
assert resolve_paid_node_ids(nodes, [Decimal("11160")]) == {3}
|
||||
"""关键断言:公司下拉框只取 selected 项,不把全部候选项拼进公司名。"""
|
||||
page = """
|
||||
<table><tr>
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
backend/tests/test_equipment_acceptance_e8.py
|
||||
|
||||
用途:E8 状态翻译、分组、查询语句,以及按使用部门担当组装收件人。
|
||||
依赖:e8_status、e8_group、e8_query、alert_service._drafts。不连接 OA,不启动 Flask。
|
||||
逻辑:暂停和撤销都停表。可以验收按 0=是翻转。第 1 档主送使用部门担当。
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.alert_service import _drafts
|
||||
from app.services.equipment_acceptance.e8_group import group_e8_rows
|
||||
from app.services.equipment_acceptance.e8_query import build_e8_acceptance_sql
|
||||
from app.services.equipment_acceptance.e8_status import e8_flow_status
|
||||
from app.services.equipment_acceptance.snapshot_rules import EXCLUDED, classify_monitor_status
|
||||
|
||||
|
||||
def test_e8_null_status_follows_node_type_and_pause_stops():
|
||||
"""空的 currentstatus 看节点类型。暂停和撤销都收成 7。别的值不收成审批中。"""
|
||||
assert e8_flow_status("1", None) == 1
|
||||
assert e8_flow_status(" 3 ", "") == 3
|
||||
assert e8_flow_status("1", 0) == 7
|
||||
assert e8_flow_status("1", 1) == 7
|
||||
assert e8_flow_status("1", 9) is None
|
||||
|
||||
|
||||
def test_unknown_e8_status_is_not_watching():
|
||||
"""认不出的流程状态留空后,有计时起点也不进进行中。"""
|
||||
assert classify_monitor_status(
|
||||
can_accept=1, is_returned=0, flow_status=None, timer_started=True
|
||||
) == EXCLUDED
|
||||
|
||||
|
||||
def test_e8_rows_group_owner_and_pending_handler():
|
||||
"""计时读 syddjssj,可以验收读 sfkys。当前未办人只留查询给出的 userid。"""
|
||||
drafts, skipped = group_e8_rows([
|
||||
{
|
||||
"requestid": 88,
|
||||
"ysddh": "YS-E8",
|
||||
"cgdh": "CG-1",
|
||||
"htbh": "HT-1",
|
||||
"flow_no": "LC-1",
|
||||
"request_title": "设备验收",
|
||||
"createdate": "2026-10-26",
|
||||
"createtime": "15:46:04",
|
||||
"syddjssj": "2026-08-01",
|
||||
"sfkys": 0,
|
||||
"sfzfth": None,
|
||||
"ycsm": "",
|
||||
"sybmdd": 15,
|
||||
"owner_name": "吴敏",
|
||||
"owner_job_num": "10086",
|
||||
"creater": 22,
|
||||
"applicant_name": "赵琴",
|
||||
"applicant_job_num": "20001",
|
||||
"currentnodetype": "1",
|
||||
"currentstatus": None,
|
||||
"currentnodeid": 6,
|
||||
"nodename": "使用部门担当",
|
||||
"userid": 15,
|
||||
"handler_name": "吴敏",
|
||||
"handler_job_num": "10086",
|
||||
},
|
||||
{"ysddh": "NO-ID"},
|
||||
])
|
||||
assert skipped == 1
|
||||
draft = drafts[0]
|
||||
assert draft.oa_system == "e8"
|
||||
assert draft.timer_started_at is not None
|
||||
assert draft.can_accept == 1
|
||||
assert draft.is_returned == 0
|
||||
assert draft.flow_status_raw == 1
|
||||
assert draft.owner_oa_id == 15
|
||||
assert draft.applicant_oa_id == 22
|
||||
assert draft.flow_no == "LC-1"
|
||||
assert draft.request_title == "设备验收"
|
||||
assert draft.request_created_at == datetime(2026, 10, 26, 15, 46, 4)
|
||||
assert [node.node_name for node in draft.nodes] == ["使用部门担当"]
|
||||
assert [item.user_id for item in draft.operators] == [15]
|
||||
|
||||
|
||||
def test_e8_sql_joins_current_node_and_unfinished_operator():
|
||||
"""当前节点用 currentnodeid。未办人用 isremark=0。不取流程编号。"""
|
||||
sql = build_e8_acceptance_sql().lower()
|
||||
assert "formtable_main_324" in sql
|
||||
assert "w.requestid = f.requestid" in sql
|
||||
assert "n.id = w.currentnodeid" in sql
|
||||
assert "op.nodeid = w.currentnodeid" in sql
|
||||
assert "isremark" in sql
|
||||
assert "w.currentnodetype is null" in sql
|
||||
assert "<> n'3'" in sql
|
||||
assert "w.creater" in sql
|
||||
assert "w.creator" not in sql
|
||||
assert "f.lcbh as flow_no" in sql
|
||||
assert "w.requestname as request_title" in sql
|
||||
assert "w.createdate" in sql
|
||||
assert "w.createtime" in sql
|
||||
assert "lastnodeid" not in sql
|
||||
|
||||
|
||||
def test_tier_one_sends_to_usage_owner_not_current_handler():
|
||||
"""第 1 档主送使用部门担当。当前节点上的另一名处理人不进收件人。"""
|
||||
order = SimpleNamespace(
|
||||
oa_system="e10",
|
||||
dwell_days=31,
|
||||
owner_oa_id=15,
|
||||
owner_name="吴敏",
|
||||
owner_job_num="10086",
|
||||
applicant_oa_id=22,
|
||||
applicant_name="赵琴",
|
||||
applicant_job_num="20001",
|
||||
)
|
||||
people = {
|
||||
15: {
|
||||
"name": "吴敏",
|
||||
"job_num": "10086",
|
||||
"superior_id": 30,
|
||||
"superior_name": "钱伟",
|
||||
"superior_job_num": "30001",
|
||||
"department_id": "9",
|
||||
},
|
||||
22: {"name": "赵琴", "job_num": "20001"},
|
||||
}
|
||||
deputies = {"9": [{"oa_id": 40, "name": "孙经理", "job_num": "40001"}]}
|
||||
users = {
|
||||
"10086": SimpleNamespace(id=7, wecom_userid="wx-owner", real_name="吴敏"),
|
||||
"30001": SimpleNamespace(id=8, wecom_userid="wx-boss", real_name="钱伟"),
|
||||
"20001": SimpleNamespace(id=9, wecom_userid="wx-buyer", real_name="赵琴"),
|
||||
"40001": SimpleNamespace(id=10, wecom_userid="wx-deputy", real_name="孙经理"),
|
||||
}
|
||||
drafts = _drafts(
|
||||
order,
|
||||
people,
|
||||
deputies,
|
||||
{},
|
||||
{},
|
||||
users,
|
||||
{},
|
||||
{"coo": None, "buyer": None, "executive": None},
|
||||
(30, 37, 44, 51),
|
||||
max_tier=3,
|
||||
)
|
||||
tier1 = drafts[0]
|
||||
assert tier1["tier"] == 1
|
||||
assert tier1["to_text"] == "吴敏"
|
||||
assert "钱伟" in (tier1["cc_text"] or "")
|
||||
assert "赵琴" in (tier1["cc_text"] or "")
|
||||
labels = [item["label"] for item in tier1["recipients"]]
|
||||
assert "当前处理人" not in labels
|
||||
assert "使用部门担当" in labels
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/tests/test_equipment_acceptance_snapshot.py
|
||||
|
||||
用途:设备验收同步的状态、分组和 SQL 组装单测。
|
||||
依赖:snapshot_rules、source_group、query_sql。不连接 OA,也不启动 Flask。
|
||||
依赖:snapshot_rules、source_group、query_sql、sync_service 的搜索词整理。不连接 OA,也不启动 Flask。
|
||||
逻辑:停表规则、按 requestid 分组、SQL 不查 isremark,发送记录快照字段原样返回。
|
||||
"""
|
||||
|
||||
@@ -13,6 +13,7 @@ import pytest
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
from app.services.equipment_acceptance.query_sql import build_acceptance_sql, resolve_catalogs
|
||||
from app.services.equipment_acceptance.sync_service import _clean_search, _contains_pattern
|
||||
from app.services.equipment_acceptance.snapshot_rules import (
|
||||
EXCLUDED,
|
||||
NOT_STARTED,
|
||||
@@ -51,16 +52,16 @@ def test_returned_yes_stops_even_while_approving():
|
||||
assert status == STOPPED_RETURNED
|
||||
|
||||
|
||||
def test_cannot_accept_stops_and_null_can_accept_is_not_watching():
|
||||
"""can_accept=0 是不可以,停表;空值不是可以验收。"""
|
||||
def test_cannot_accept_stops_and_null_can_accept_still_watches():
|
||||
"""可以验收明确为否才停表。空值未标明,审批中且已计时仍监控。"""
|
||||
stopped = classify_monitor_status(
|
||||
can_accept=0, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
excluded = classify_monitor_status(
|
||||
watching = classify_monitor_status(
|
||||
can_accept=None, is_returned=0, flow_status=1, timer_started=True
|
||||
)
|
||||
assert stopped == STOPPED_CANNOT_ACCEPT
|
||||
assert excluded == EXCLUDED
|
||||
assert watching == WATCHING
|
||||
|
||||
|
||||
def test_not_returned_and_can_accept_watches():
|
||||
@@ -204,10 +205,14 @@ def test_sql_uses_dictionary_catalogs_and_does_not_select_isremark():
|
||||
assert "workflow_requestbase" not in sql
|
||||
assert "[weaver_wfc].[dbo].[wfc_form_data]" in sql
|
||||
assert "d.dataid = f.FORM_DATA_ID" in sql
|
||||
assert "r.flowstatus is null or r.flowstatus <> 3" in sql.lower()
|
||||
assert "r.requestmark as flow_no" in sql.lower()
|
||||
assert "r.requestname as request_title" in sql.lower()
|
||||
assert "r.createdatetime" in sql.lower()
|
||||
assert "lcbh" not in sql
|
||||
assert "htbh1" not in sql
|
||||
assert "ysrq" not in sql
|
||||
assert "requestmark" not in sql
|
||||
assert "requestmark" in sql.lower()
|
||||
assert "operateround" not in sql.lower()
|
||||
assert "optgroupid" not in sql.lower()
|
||||
assert "batch_number" not in sql.lower()
|
||||
@@ -255,3 +260,11 @@ def test_send_record_payload_keeps_written_names():
|
||||
assert payload["threshold_days"] == 37
|
||||
assert payload["status"] == "sent"
|
||||
assert payload["sent_at"]
|
||||
|
||||
|
||||
def test_number_keyword_treats_like_wildcards_as_literal_text():
|
||||
"""单号搜索按包含匹配,% 和 _ 保持原字符,空白不参与过滤。"""
|
||||
assert _clean_search(" ") is None
|
||||
assert _clean_search(" 20260718 ") == "20260718"
|
||||
assert _contains_pattern("a%b_c") == "%a\\%b\\_c%"
|
||||
assert len(_clean_search("x" * 120) or "") == 100
|
||||
@@ -1410,7 +1410,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
|
||||
assert events[0] == ("session", "https://s360.dbschenker.com/")
|
||||
assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2")
|
||||
assert ("file", "#file2") in events
|
||||
assert ("file", "input#file2") in events
|
||||
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
|
||||
@@ -142,7 +142,7 @@ def _freeze_export_snapshot(
|
||||
|
||||
def _materialize_export_notice(
|
||||
*, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: FreightRpaOnhandReportFile,
|
||||
source_code: str, notice_no: str,
|
||||
source_code: str, notice_no: str, match_result: str = 'matched',
|
||||
) -> ShippingNotice:
|
||||
"""从 OT 的冻结快照构造正式 Notice、NoticeLine、匹配事实与活动库存链接。
|
||||
|
||||
@@ -168,7 +168,8 @@ def _materialize_export_notice(
|
||||
for line in snapshot.lines:
|
||||
db.session.add(ShippingNoticeLineOnhandMatch(
|
||||
task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no,
|
||||
match_result='matched', onhand_status='ready',
|
||||
line_index=int(line.line_no) - 1,
|
||||
match_result=match_result, onhand_status='ready',
|
||||
onhand_snapshot_id=inventory_file.id, source_code=source_code,
|
||||
is_current=True, detail_json={},
|
||||
))
|
||||
@@ -922,6 +923,8 @@ def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch
|
||||
|
||||
def _build_multi_odm_notice(
|
||||
*, tmp_path, odm_values=None, customer_odm_ids=None, choice_odm=None, line_specs=None,
|
||||
released_shortage: bool = False, unreleased_shortage: bool = False,
|
||||
order_part: str = 'PN-A', inventory_part: str | None = None,
|
||||
):
|
||||
"""
|
||||
构造「订单行命中多个 ODM ID」的整单导出场景;须在 app_context 内调用。
|
||||
@@ -931,6 +934,11 @@ def _build_multi_odm_notice(
|
||||
line_specs: 多订单行场景 [{'part': 料号, 'odm_values': [...]}];提供时忽略 odm_values。
|
||||
customer_odm_ids: 客户数据的 ODM ID 范围(None = 不限定)。
|
||||
choice_odm: 整单用户选择(写入 OT.chosen_odm_id)
|
||||
released_shortage: True 时唯一行构造为短缺放行场景——订单料号不在库存行
|
||||
(匹配键 0 命中)、事实落 not_found、并落已确认复核 Case 的系统放行决定
|
||||
(release_field_values 携带 ODM 证据值),整单无任何 matched 事实。
|
||||
unreleased_shortage: True 时事实落 not_found 但不落放行决定(未放行短缺)。
|
||||
order_part / inventory_part: 订单行与库存行的料号(放行场景两者必须不同)。
|
||||
Returns:
|
||||
(notice, customer)。
|
||||
"""
|
||||
@@ -979,7 +987,7 @@ def _build_multi_odm_notice(
|
||||
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction); db.session.flush()
|
||||
specs = line_specs or [{'part': 'PN-A', 'odm_values': odm_values}]
|
||||
specs = line_specs or [{'part': order_part, 'odm_values': odm_values}]
|
||||
snapshot_lines = []
|
||||
for index, spec in enumerate(specs, start=1):
|
||||
order_line = ShippingOrderLine(extraction_id=extraction.id, position=index, line_no=index)
|
||||
@@ -998,7 +1006,7 @@ def _build_multi_odm_notice(
|
||||
inventory_rows = []
|
||||
for spec in specs:
|
||||
for odm in spec['odm_values']:
|
||||
inventory_rows.append({_inventory_field_id('part_number'): spec['part'], _inventory_field_id('odm_id'): odm})
|
||||
inventory_rows.append({_inventory_field_id('part_number'): inventory_part or spec['part'], _inventory_field_id('odm_id'): odm})
|
||||
inventory_file = FreightRpaOnhandReportFile(
|
||||
onhand_file_no='SIF-ODMSCOPE', user_id=None, source_file_name='odm-scope.xlsx',
|
||||
storage_path=str(tmp_path / 'odm-scope.xlsx'),
|
||||
@@ -1014,7 +1022,25 @@ def _build_multi_odm_notice(
|
||||
)
|
||||
notice = _materialize_export_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='ODMSCOPE', notice_no='TASK-ODMSCOPE',
|
||||
match_result='not_found' if (released_shortage or unreleased_shortage) else 'matched',
|
||||
)
|
||||
if released_shortage:
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='CASE-ODMSCOPE-RELEASE', run_id=931, unit_id=932, document_id=933,
|
||||
owner_user_id=1, status='confirmed', confirmed_task_id=int(ot.id),
|
||||
)
|
||||
db.session.add(case); db.session.flush()
|
||||
db.session.add(ShippingOrderReviewLineDecision(
|
||||
review_case_id=case.id, draft_line_id='line-1', line_index=0,
|
||||
decision_code='release_onhand_shortage', decision_source='system',
|
||||
line_status='released_shortage', is_active=True,
|
||||
snapshot_json={
|
||||
'release_field_values': {str(_inventory_field_id('odm_id')): 'ODM-1'},
|
||||
'release_evidence_scope': 'part_fallback',
|
||||
},
|
||||
))
|
||||
db.session.flush()
|
||||
if choice_odm is not None:
|
||||
for match in ShippingNoticeLineOnhandMatch.query.filter_by(task_id=int(ot.id), is_current=True).all():
|
||||
match.chosen_odm_id = choice_odm
|
||||
@@ -1113,6 +1139,60 @@ def test_export_keeps_conflict_when_odm_scope_cannot_decide(app, tmp_path):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_export_released_shortage_only_notice_resolves_source_and_rows(app, tmp_path):
|
||||
"""整单短缺放行(0 条 matched 事实)也能解析库存源并按放行证据导出。
|
||||
|
||||
回归 OT-20261027-4BD4CEFF:预约键 0 命中→料号兜底自动放行后,行事实恒为
|
||||
not_found;_notice_source_code 只认 matched 会让整单放行的单报
|
||||
「库存源不存在或已停用」;prepare_export_match_inputs 的放行决定 join 须按
|
||||
confirmed_task_id(OT) 回链,Notice 身份调用不得丢放行行。
|
||||
"""
|
||||
from app.services.shipping_notice.export import _notice_source_code, prepare_export_match_inputs
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
notice, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, released_shortage=True,
|
||||
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
|
||||
)
|
||||
|
||||
# 断言意图 1:源解析把放行行事实与 matched 行同票,整单放行也能拿到唯一源。
|
||||
assert _notice_source_code(notice) == 'ODMSCOPE'
|
||||
|
||||
# 断言意图 2:以 Notice 身份准备导出输入,放行决定经 OT 回链可查到,
|
||||
# 放行行进入导出行集并携带审计补录值(无 matched 事实也不报「没有匹配」)。
|
||||
inputs = prepare_export_match_inputs(notice)
|
||||
assert inputs['released_snapshot_line_ids']
|
||||
assert inputs['released_export_line_indexes'] == {0}
|
||||
assert list(inputs['release_overrides_by_line'][0].values()) == ['ODM-1']
|
||||
assert [row['__order_line_index'] for row in inputs['line_values']] == [0]
|
||||
|
||||
# 断言意图 3:整单放行时证据快照仍落 Artifact 审计(matched-only 不再断证据链)。
|
||||
assert inputs['verification'] is not None
|
||||
|
||||
path, _filename_value, _artifact = generate_shipment_excel(notice)
|
||||
workbook = load_workbook(path, data_only=True)
|
||||
try:
|
||||
assert workbook['Detail'].cell(2, 1).value == 'ODM-1'
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def test_unreleased_shortage_notice_still_lacks_source(app, tmp_path):
|
||||
"""未放行的短缺行不得参与源解析:matched-only 语义对未放行场景保持不变。"""
|
||||
from app.services.shipping_notice.export import _notice_source_code
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
notice, _customer = _build_multi_odm_notice(
|
||||
tmp_path=tmp_path, unreleased_shortage=True,
|
||||
order_part='PN-GONE', inventory_part='PN-OTHER', odm_values=['ODM-1'],
|
||||
)
|
||||
|
||||
# 断言意图:not_found 且无放行决定的事实不充当导出源依据(fail-closed 不变)。
|
||||
assert _notice_source_code(notice) is None
|
||||
|
||||
|
||||
def test_notice_odm_options_and_choice_roundtrip(app, tmp_path):
|
||||
"""整单候选按客户范围逐行投影;合法选择落库并回显,非法选择有明确错误。"""
|
||||
from app.core.errors import AppError
|
||||
|
||||
@@ -3,13 +3,15 @@ backend/tests/test_voucher_check_permissions.py
|
||||
|
||||
用途:验收立账凭证改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、workspace voucher_check 蓝图。
|
||||
逻辑:授予 voucher_check Agent 后可查询任务列表,但不能触发强制重检、也不能改通知配置。
|
||||
逻辑:授予 voucher_check Agent 后可查询任务列表并下载企微记录 Excel,但不能触发强制重检、也不能改通知配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, User
|
||||
from app.models import Agent, ScheduleRun, ScheduleTask, User, VoucherCheckRun
|
||||
|
||||
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
@@ -176,3 +178,63 @@ def test_voucher_check_notify_config_requires_admin(client, app):
|
||||
)
|
||||
assert put_res.status_code == 403
|
||||
assert _json_error(put_res)['code'] == 'VOUCHER_CHECK.ADMIN_REQUIRED'
|
||||
|
||||
|
||||
def test_voucher_check_excel_download_uses_agent_access_not_schedule_notify(client, app):
|
||||
"""企微发送记录的 Excel 按立账凭证访问权下载,不要求是排程负责人或通知人。"""
|
||||
payload = b'voucher-excel'
|
||||
with app.app_context():
|
||||
owner = _create_user(username='vc_excel_owner')
|
||||
granted = _grant_voucher_check_agent(_create_user(username='vc_excel_viewer'))
|
||||
denied = _create_user(username='vc_excel_denied')
|
||||
task = ScheduleTask(
|
||||
schedule_no='VC-EXCEL-1',
|
||||
name='立账凭证周检',
|
||||
owner_user_id=owner.id,
|
||||
cron_expr='0 6 * * 2',
|
||||
notify_user_ids_json=[],
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
schedule_run = ScheduleRun(
|
||||
run_no='RUN-VC-EXCEL-1',
|
||||
schedule_task_id=task.id,
|
||||
status='success',
|
||||
excel_file_data=payload,
|
||||
excel_file_name='voucher_check.xlsx',
|
||||
excel_file_size=len(payload),
|
||||
)
|
||||
db.session.add(schedule_run)
|
||||
db.session.flush()
|
||||
db.session.add(VoucherCheckRun(
|
||||
id=88001,
|
||||
schedule_run_id=schedule_run.id,
|
||||
run_no='RUN-VC-EXCEL-1',
|
||||
profile_code='sales',
|
||||
profile_version='1',
|
||||
profile_snapshot_json={},
|
||||
period_month=date(2026, 9, 1),
|
||||
mode='incremental',
|
||||
status='success',
|
||||
))
|
||||
db.session.commit()
|
||||
schedule_run_id = schedule_run.id
|
||||
granted_id = granted.id
|
||||
denied_id = denied.id
|
||||
|
||||
granted_headers = {'X-User-Id': str(granted_id), 'X-Username': 'vc_excel_viewer'}
|
||||
url = f'/api/workspace/accounting-voucher-check/schedule-runs/{schedule_run_id}/excel'
|
||||
ok_res = client.get(url, headers=granted_headers)
|
||||
# 关键断言:不是排程通知人时,立账凭证授权用户仍能拿到 Excel 正文。
|
||||
assert ok_res.status_code == 200
|
||||
assert ok_res.data == payload
|
||||
|
||||
denied_headers = {'X-User-Id': str(denied_id), 'X-Username': 'vc_excel_denied'}
|
||||
denied_res = client.get(url, headers=denied_headers)
|
||||
assert denied_res.status_code == 403
|
||||
assert _json_error(denied_res)['code'] == 'VOUCHER_CHECK.FORBIDDEN'
|
||||
|
||||
legacy = client.get(f'/api/workspace/schedule-runs/{schedule_run_id}/excel', headers=granted_headers)
|
||||
# 关键断言:旧排程下载口仍只认负责人/通知人,企微记录不能再走这条。
|
||||
assert legacy.status_code == 403
|
||||
assert _json_error(legacy)['code'] == 'AUTH.FORBIDDEN'
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
tests/test_wecom_textcard_source.py
|
||||
|
||||
用途:断言企微 textcard 标题带来源,以及账号类通知不加来源。
|
||||
依赖:app fixture、integrations.wecom.notify。
|
||||
逻辑:直接调用标题函数与发送出口,不经过具体业务模块。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.integrations.wecom.notify import (
|
||||
_with_agent_source_title,
|
||||
send_wecom_event_message,
|
||||
send_wecom_textcard_message,
|
||||
)
|
||||
|
||||
|
||||
def test_agent_source_prefix_stays_when_title_is_truncated():
|
||||
"""超长业务标题截断后,来源前缀仍完整留在最前面。"""
|
||||
title = _with_agent_source_title('缺' * 200)
|
||||
# [断言意图] 前缀不被 120 字上限切掉,业务标题从末尾被截断。
|
||||
assert title.startswith('AI智能体 · ')
|
||||
assert len(title) == 120
|
||||
assert title == f"AI智能体 · {'缺' * 112}"
|
||||
|
||||
|
||||
def test_agent_source_prefix_is_not_repeated():
|
||||
"""已经带来源的标题不再加第二次。"""
|
||||
once = _with_agent_source_title('精益管理培训逾期提醒')
|
||||
twice = _with_agent_source_title(once)
|
||||
# [断言意图] 重复经过发送出口时标题保持单层来源。
|
||||
assert once == 'AI智能体 · 精益管理培训逾期提醒'
|
||||
assert twice == once
|
||||
|
||||
|
||||
def test_textcard_payload_uses_agent_source_title(app, monkeypatch):
|
||||
"""实际发给企业微信的 textcard.title 带来源,调用方传入的仍是业务标题。"""
|
||||
captured = {}
|
||||
|
||||
def _fake_post(_url, params=None, json=None, timeout=None):
|
||||
captured['json'] = json
|
||||
|
||||
class _Resp:
|
||||
def json(self):
|
||||
return {'errcode': 0}
|
||||
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.integrations.wecom.notify._get_access_token',
|
||||
lambda: 'token',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.integrations.wecom.notify.requests.post',
|
||||
_fake_post,
|
||||
)
|
||||
with app.app_context():
|
||||
app.config['WECOM_AGENT_ID'] = '1000002'
|
||||
send_wecom_textcard_message(
|
||||
'wx-user',
|
||||
'销售开票附件缺件提醒',
|
||||
'正文',
|
||||
'https://example.com/detail',
|
||||
)
|
||||
# [断言意图] 企微载荷标题带来源,正文和按钮保持原样。
|
||||
assert captured['json']['textcard']['title'] == 'AI智能体 · 销售开票附件缺件提醒'
|
||||
assert captured['json']['textcard']['description'] == '正文'
|
||||
assert captured['json']['textcard']['btntxt'] == '查看详情'
|
||||
|
||||
|
||||
def test_account_events_keep_business_title(app, monkeypatch):
|
||||
"""密码重置和权限变更不加来源;业务提醒仍然加上。"""
|
||||
captured = {}
|
||||
|
||||
def _fake_send(_userid, title, _description, _jump_url, *, with_agent_source=True):
|
||||
captured['title'] = title
|
||||
captured['with_agent_source'] = with_agent_source
|
||||
return {'errcode': 0}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.integrations.wecom.notify.send_wecom_textcard_message',
|
||||
_fake_send,
|
||||
)
|
||||
with app.app_context():
|
||||
app.config['WECOM_NOTIFY_ENABLED'] = True
|
||||
app.config['WECOM_NOTIFY_EVENTS'] = (
|
||||
'password_reset,permission_request_approved,lean_training_overdue'
|
||||
)
|
||||
user = User(
|
||||
username='source-user',
|
||||
email='source@example.com',
|
||||
role='user',
|
||||
wecom_userid='wx-source',
|
||||
)
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
send_wecom_event_message(
|
||||
event_type='password_reset',
|
||||
user=user,
|
||||
title='和信AI智能工作台 密码重置',
|
||||
content='请重置密码',
|
||||
jump_url='https://example.com/reset',
|
||||
)
|
||||
# [断言意图] 密码重置不是智能体推送,发送出口关闭来源前缀。
|
||||
assert captured['with_agent_source'] is False
|
||||
assert captured['title'] == '和信AI智能工作台 密码重置'
|
||||
|
||||
send_wecom_event_message(
|
||||
event_type='permission_request_approved',
|
||||
user=user,
|
||||
title='权限申请已通过',
|
||||
content='已通过',
|
||||
)
|
||||
# [断言意图] 权限变更与密码重置同一排除名单。
|
||||
assert captured['with_agent_source'] is False
|
||||
|
||||
send_wecom_event_message(
|
||||
event_type='lean_training_overdue',
|
||||
user=user,
|
||||
title='精益管理培训逾期提醒',
|
||||
content='请完成学习',
|
||||
)
|
||||
# [断言意图] 业务提醒仍把来源交给 textcard 出口添加。
|
||||
assert captured['with_agent_source'] is True
|
||||
assert captured['title'] == '精益管理培训逾期提醒'
|
||||
@@ -3,7 +3,7 @@ backend/tests/voucher_check/test_dms_archive.py
|
||||
|
||||
用途:销售一期第 5 步归档(建文件夹、复制、同名跳过)单测。
|
||||
依赖:pytest;不连文档库。
|
||||
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy;断言同名不覆盖、缺月目录为技术失败。
|
||||
逻辑:mock SalesDmsClient 的 Page/SaveFolder/Copy/Rename/Recycle;断言同名不覆盖、带「重命名」的落盘名改回原名、多余副本删除、缺月目录为技术失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,6 +19,10 @@ from app.services.voucher_check.dms_client import (
|
||||
SalesDmsClient,
|
||||
_extract_item_id,
|
||||
_is_name_conflict,
|
||||
canonical_leaf_name,
|
||||
dms_stored_leaf_name,
|
||||
leaf_names_match,
|
||||
row_display_name,
|
||||
)
|
||||
|
||||
|
||||
@@ -55,6 +59,280 @@ def test_ensure_folder_creates_when_missing(monkeypatch):
|
||||
assert SalesDmsClient.ensure_folder(parent_folder_id="month", leaf_name="所有归档") == "new-folder"
|
||||
|
||||
|
||||
def test_recycle_items_posts_library_delete(monkeypatch):
|
||||
# 与文档库列表「删除」同一接口:ItemID 数组,进入回收站。
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
def post(path, payload, **_kwargs):
|
||||
seen["path"] = path
|
||||
seen["payload"] = payload
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
|
||||
SalesDmsClient.recycle_items(item_ids=["extra-1", "extra-2"])
|
||||
assert seen["path"] == "/Api/_api/APS/Public/Item/Recycle"
|
||||
assert seen["payload"] == {"ItemID": ["extra-1", "extra-2"]}
|
||||
|
||||
|
||||
def test_rename_item_posts_library_rename(monkeypatch):
|
||||
# 与文档库列表「重命名」同一接口:ItemID + 改回后的 LeafName。
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
def post(path, payload, **_kwargs):
|
||||
seen["path"] = path
|
||||
seen["payload"] = payload
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "_post_json", post)
|
||||
SalesDmsClient.rename_item(item_id="dest-r", leaf_name="INV001.pdf")
|
||||
assert seen["path"] == "/Api/_api/APS/Public/Item/Rename"
|
||||
assert seen["payload"] == {"ItemID": "dest-r", "LeafName": "INV001.pdf"}
|
||||
|
||||
|
||||
def test_canonical_leaf_name_strips_dms_rename_marker():
|
||||
# 现网复制后的名字是「原名.pdf(重命名).pdf」,还原后必须等于业务文件名。
|
||||
assert canonical_leaf_name("AK260929062-8501-2609290005.pdf(重命名).pdf") == (
|
||||
"AK260929062-8501-2609290005.pdf"
|
||||
)
|
||||
assert canonical_leaf_name("INV001(重命名).pdf") == "INV001.pdf"
|
||||
assert canonical_leaf_name("INV001.pdf") == "INV001.pdf"
|
||||
assert leaf_names_match("AK260929062-8501-2609290005.pdf(重命名).pdf", "AK260929062-8501-2609290005.pdf")
|
||||
assert leaf_names_match("OTHER.pdf(重命名).pdf", "AK260929062-8501-2609290005.pdf") is False
|
||||
assert canonical_leaf_name("QCG260921187-8501-2609210008.pdf (重命名) .pdf") == (
|
||||
"QCG260921187-8501-2609210008.pdf"
|
||||
)
|
||||
# 库内真实名字不带界面补上的第二个 .pdf。改回带 .pdf 的原名会被文档库判成同名。
|
||||
stored = "QCH2609188245-8501-2609170001.pdf(重命名)"
|
||||
assert canonical_leaf_name(stored) == "QCH2609188245-8501-2609170001.pdf"
|
||||
assert dms_stored_leaf_name("QCH2609188245-8501-2609170001.pdf") == "QCH2609188245-8501-2609170001"
|
||||
assert row_display_name({
|
||||
"LeafName": stored,
|
||||
"MainFileAttachment": {"Extension": ".pdf"},
|
||||
}) == "QCH2609188245-8501-2609170001.pdf(重命名).pdf"
|
||||
|
||||
|
||||
def test_find_child_file_accepts_renamed_copy(monkeypatch):
|
||||
# 目录里只有带「重命名」的文件时,按原名查找应命中,避免再次复制。
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{
|
||||
"ID": "dest-r",
|
||||
"LeafName": "AK260929062-8501-2609290005.pdf(重命名).pdf",
|
||||
"IsFolder": False,
|
||||
}],
|
||||
)
|
||||
row = SalesDmsClient.find_child_file(
|
||||
parent_folder_id="inv-folder",
|
||||
leaf_name="AK260929062-8501-2609290005.pdf",
|
||||
)
|
||||
assert row is not None
|
||||
assert row["ID"] == "dest-r"
|
||||
|
||||
|
||||
def test_copy_renames_existing_suffix_back_to_original(monkeypatch):
|
||||
# 目录里只有带「重命名」的文件时,改回原名,不再复制出新文件。
|
||||
files = {"rows": [{"ID": "dest-r", "LeafName": "INV001.pdf(重命名).pdf"}]}
|
||||
copies: list[object] = []
|
||||
renames: list[dict[str, str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return files["rows"]
|
||||
|
||||
def rename_item(**kwargs):
|
||||
renames.append(kwargs)
|
||||
files["rows"] = [{"ID": kwargs["item_id"], "LeafName": kwargs["leaf_name"]}]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copies.append(kwargs))
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["LeafName"] == "INV001"
|
||||
assert renames == [{"item_id": "dest-r", "leaf_name": "INV001"}]
|
||||
assert copies == []
|
||||
|
||||
|
||||
def test_copy_strips_rename_suffix_after_copy(monkeypatch):
|
||||
# 复制成功但落盘名带「重命名」时,立刻改回业务原名。
|
||||
files: dict[str, list[dict[str, str]]] = {"rows": []}
|
||||
renames: list[dict[str, str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return files["rows"]
|
||||
|
||||
def copy_items(**_kwargs):
|
||||
files["rows"] = [{"ID": "new-1", "LeafName": "INV001.pdf(重命名).pdf"}]
|
||||
return {"Code": 0}
|
||||
|
||||
def rename_item(**kwargs):
|
||||
renames.append(kwargs)
|
||||
files["rows"] = [{"ID": kwargs["item_id"], "LeafName": kwargs["leaf_name"]}]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", copy_items)
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is False
|
||||
assert row["ID"] == "new-1"
|
||||
assert row["LeafName"] == "INV001"
|
||||
assert renames == [{"item_id": "new-1", "leaf_name": "INV001"}]
|
||||
|
||||
|
||||
def test_copy_keeps_original_and_recycles_renamed_extras(monkeypatch):
|
||||
# 原名已在时不再复制、不再改名,只删除仍带「重命名」的多余副本。
|
||||
files = {
|
||||
"rows": [
|
||||
{"ID": "clean", "LeafName": "INV001.pdf"},
|
||||
{"ID": "extra", "LeafName": "INV001.pdf(重命名).pdf"},
|
||||
{"ID": "other", "LeafName": "别的资料.pdf"},
|
||||
]
|
||||
}
|
||||
recycled: list[list[str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return list(files["rows"])
|
||||
|
||||
def recycle_items(**kwargs):
|
||||
recycled.append(list(kwargs["item_ids"]))
|
||||
drop = set(kwargs["item_ids"])
|
||||
files["rows"] = [row for row in files["rows"] if row["ID"] not in drop]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应改名")))
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", recycle_items)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="INV001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "clean"
|
||||
assert recycled == [["extra"]]
|
||||
assert [item["ID"] for item in files["rows"]] == ["clean", "other"]
|
||||
|
||||
|
||||
def test_copy_restores_one_of_three_renamed_copies_and_recycles_the_rest(monkeypatch):
|
||||
# 9 月这类目录只有三份带后缀的同一文件时:改回一份原名,删除另外两份。
|
||||
wanted = "QCG260921187-8501-2609210008.pdf"
|
||||
renamed = f"{wanted}(重命名).pdf"
|
||||
files = {
|
||||
"rows": [
|
||||
{"ID": "a", "LeafName": renamed},
|
||||
{"ID": "b", "LeafName": renamed},
|
||||
{"ID": "c", "LeafName": f"{wanted} (重命名) .pdf"},
|
||||
]
|
||||
}
|
||||
recycled: list[list[str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return list(files["rows"])
|
||||
|
||||
def rename_item(**kwargs):
|
||||
for item in files["rows"]:
|
||||
if item["ID"] == kwargs["item_id"]:
|
||||
item["LeafName"] = kwargs["leaf_name"]
|
||||
return {"Code": 0}
|
||||
|
||||
def recycle_items(**kwargs):
|
||||
recycled.append(list(kwargs["item_ids"]))
|
||||
drop = set(kwargs["item_ids"])
|
||||
files["rows"] = [row for row in files["rows"] if row["ID"] not in drop]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", recycle_items)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name=wanted,
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "a"
|
||||
assert row["LeafName"] == "QCG260921187-8501-2609210008"
|
||||
assert recycled == [["b", "c"]]
|
||||
assert [item["ID"] for item in files["rows"]] == ["a"]
|
||||
|
||||
|
||||
def test_copy_renames_real_dms_leaf_without_extension(monkeypatch):
|
||||
# 现网 LeafName 是「原名.pdf(重命名)」,扩展名在附件上。改名必须去掉扩展名,不能写成「原名.pdf」。
|
||||
wanted = "QCH2609188245-8501-2609170001.pdf"
|
||||
stored = f"{wanted}(重命名)"
|
||||
files = {
|
||||
"rows": [
|
||||
{"ID": "a", "LeafName": stored, "MainFileAttachment": {"Extension": ".pdf"}},
|
||||
{"ID": "b", "LeafName": stored, "MainFileAttachment": {"Extension": ".pdf"}},
|
||||
]
|
||||
}
|
||||
renames: list[dict[str, str]] = []
|
||||
|
||||
def list_files(**_kwargs):
|
||||
return list(files["rows"])
|
||||
|
||||
def rename_item(**kwargs):
|
||||
renames.append(kwargs)
|
||||
for item in files["rows"]:
|
||||
if item["ID"] == kwargs["item_id"]:
|
||||
item["LeafName"] = kwargs["leaf_name"]
|
||||
return {"Code": 0}
|
||||
|
||||
def recycle_items(**kwargs):
|
||||
drop = set(kwargs["item_ids"])
|
||||
files["rows"] = [row for row in files["rows"] if row["ID"] not in drop]
|
||||
return {"Code": 0}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "list_files", list_files)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", rename_item)
|
||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", recycle_items)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name=wanted,
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "a"
|
||||
assert renames == [{"item_id": "a", "leaf_name": "QCH2609188245-8501-2609170001"}]
|
||||
assert [item["ID"] for item in files["rows"]] == ["a"]
|
||||
|
||||
|
||||
def test_copy_skips_when_stored_leaf_is_already_the_stem(monkeypatch):
|
||||
# 改名成功后 LeafName 是不带扩展名的原名,下次检核不能再复制。
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{
|
||||
"ID": "a",
|
||||
"LeafName": "QCH2609188245-8501-2609170001",
|
||||
"MainFileAttachment": {"Extension": ".pdf"},
|
||||
}],
|
||||
)
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应复制")))
|
||||
monkeypatch.setattr(SalesDmsClient, "rename_item", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应改名")))
|
||||
monkeypatch.setattr(SalesDmsClient, "recycle_items", lambda **_kwargs: (_ for _ in ()).throw(AssertionError("不应删除")))
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
leaf_name="QCH2609188245-8501-2609170001.pdf",
|
||||
)
|
||||
assert skipped is True
|
||||
assert row["ID"] == "a"
|
||||
|
||||
|
||||
def test_copy_skips_when_dest_has_same_name(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
@@ -63,6 +341,11 @@ def test_copy_skips_when_dest_has_same_name(monkeypatch):
|
||||
)
|
||||
calls: list[object] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: calls.append(kwargs))
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{"ID": "dest-1", "LeafName": "INV001.pdf"}],
|
||||
)
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
source_item_id="src-1",
|
||||
dest_folder_id="inv-folder",
|
||||
@@ -83,6 +366,11 @@ def test_copy_when_dest_has_no_same_name(monkeypatch):
|
||||
return {"ID": "dest-2", "LeafName": "INV001.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{"ID": "dest-2", "LeafName": "INV001.pdf"}],
|
||||
)
|
||||
copied: list[dict] = []
|
||||
monkeypatch.setattr(SalesDmsClient, "copy_items", lambda **kwargs: copied.append(kwargs) or {"Code": 0})
|
||||
row, skipped = SalesDmsClient.copy_file_skip_same_name(
|
||||
@@ -105,6 +393,11 @@ def test_copy_treats_api_same_name_error_as_skip(monkeypatch):
|
||||
return {"ID": "dest-3", "LeafName": "INV001.pdf"}
|
||||
|
||||
monkeypatch.setattr(SalesDmsClient, "find_child_file", find_child_file)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"list_files",
|
||||
lambda **_kwargs: [{"ID": "dest-3", "LeafName": "INV001.pdf"}],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
SalesDmsClient,
|
||||
"copy_items",
|
||||
|
||||
@@ -294,7 +294,7 @@ def test_send_batch_splits_one_card_per_user(app, monkeypatch):
|
||||
po_title, po_body = next((item[1], item[2]) for item in sent if item[0] == "wx-po-recv")
|
||||
bl_body = next(item[2] for item in sent if item[0] == "wx-bl-recv")
|
||||
# 关键断言:卡片面向销售开票附件,不暴露业务方代号和批次号。
|
||||
assert po_title == "销售开票附件缺件"
|
||||
assert po_title == "销售开票附件缺件提醒"
|
||||
assert "2026年8月" in po_body
|
||||
assert "缺 2 份,涉及 1 张发票" in po_body
|
||||
assert "业务方" not in po_body
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# 调拨对话只解释规则并带路
|
||||
|
||||
状态:被 [ADR 0006](0006-defer-transfer-conversation.md) 取代(2026-10-26)。下文保留当时的取舍,不再作为实施依据。
|
||||
|
||||
手工调拨已由卡片按钮测通,自动调拨另案验收。2026-10-26 决定:在途调拨的第一刀对话只做简体中文的规则说明,并按固定带路表打开已有视图、指出按钮。生成调拨单、勾选、关闭、重查、重新触发仍由那些按钮提交。首页已经显示的数量不在对话里重报。Dify 1.16.1 Chatflow 只交回一句中文和一个可选视图代码;未知代码或只问数量时留在首页。提示词以仓库文本为唯一口径,从仓库发布到 Dify。
|
||||
|
||||
这样做是因为写接口一旦成为模型工具,就会绕开卡片上已经测过的门禁(看见的行、关闭必填原因、结果未知只能重新触发)。气泡图平台把写操作做成确认后的工具,是因为那里没有这套卡片。首页数字在能打字时已经可见,再查一套没有意义。
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **Dify 直接调用写接口,或用 Human Input 再确认一次**:被否——同一件提交会有两扇门,Human Input 与匹配卡、执行看板重复。
|
||||
- **每轮把首页计数塞进提示词,由模型报数**:被否——能对话时人就在首页,卡片已经是这套数字的呈现。
|
||||
- **自研多轮工具循环**:被否——HXOPS 的 hybrid 运行时已经只接 Dify Chatflow。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 带路表:规则或数量留在首页;库存匹配打开来源选择(确认范围并匹配);待匹配只读;生成、勾选、可调拨明细打开可调拨明细(生成调拨单);重查、恢复处理、关闭异常行打开待恢复异常(重查库存,或关闭且须填原因);已人工关闭只查看原因;结果未知打开执行看板对应分组(重新触发);关闭调拨单或看失败单打开执行看板的失败分组(关闭调拨单)。没分清是待恢复异常还是失败调拨单时先问,不猜。
|
||||
- 提示词只陈述八条:执行边界是出入站来源实例;数量必须与 ERP 严格相等;恢复处理就是重查库存;人工关闭只保留原因;结果未知只能在执行看板重新触发;写操作在卡片按钮上完成;数量以首页卡片为准;不讲述某一次自动调拨,也不解释某一张发票为什么被挡住。点名发票、追问某次自动运行或要求直接生成时,只说明并打开对应类别的视图。
|
||||
- 界面四语言卡片不变。自动调拨的测试、排程和 ERP 写路径不在本决策内。按发票解释阻断原因、讲述最近一次自动运行、在对话里填好来源和日期并创建匹配,留到下一刀。
|
||||
- 术语见 `docs/features/in-transit-transfer/GLOSSARY.md` 的调拨对话、恢复处理、人工关闭、结果未知。
|
||||
@@ -0,0 +1,18 @@
|
||||
# 调拨对话先不做
|
||||
|
||||
状态:accepted,取代 [ADR 0005](0005-transfer-conversation-explains-and-routes.md)。
|
||||
|
||||
2026-10-26 决定先不做在途调拨对话。匹配、勾选、生成调拨单、重查库存、人工关闭和重新触发都是确定动作,现有卡片已经是最短路径。再加一轮 Chatflow,只是在同一次点击之前多一次等待。规则说明也不在这轮写成卡片旁的固定文字。
|
||||
|
||||
按某张发票解释阻断原因,留到卡片上的现有文字确实答不清时再单独立项。在那之前不接 Chatflow,不发布提示词,不增加视图代码。
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **按 ADR 0005 做解释加带路**:被否——带路的终点仍是现有按钮,对话比直接点卡片更慢。
|
||||
- **现在就把规则写进卡片文案**:被否——这轮连说明文案也不加,避免借停对话之机扩大改动。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 不写规格,不改聊天回合,不改首页视图切换。
|
||||
- 自动调拨的测试、排程和 ERP 写路径仍按原案,与本决定无关。
|
||||
- 术语表不保留「调拨对话」。恢复处理、人工关闭、结果未知仍是现行卡片上的概念。
|
||||
@@ -0,0 +1,18 @@
|
||||
# 新匹配顶替尚未写 ERP 的旧匹配
|
||||
|
||||
状态:accepted。
|
||||
|
||||
2026-10-27 决定:提交一次新匹配时,取消所有被它盖住、且还没有任何 ERP 单据的旧匹配,再按新的日期范围重新圈档。同一批货不能同时留在两张未取消的匹配上,否则可执行行会各写一次 ERP。画面上不再为这件事单加取消按钮。
|
||||
|
||||
顶替只发生在同一调拨类型、同一组来源,且新的日期范围把旧范围整个盖住的时候。旧匹配没有日期范围、正在写 ERP、结果未知,或已经写出单据,都保持有效,货留在原匹配里。清单不列举这些匹配的编号。人工关闭的货不回到新匹配。没有挂上任何匹配的明细不占货。
|
||||
|
||||
## Considered Options
|
||||
|
||||
- **只加取消按钮**:被否——仓库人员的下一步就是再匹配一次,按钮多一次确认,不解决「提交新匹配时期望直接看到货」。
|
||||
- **允许重复匹配**:被否——两张未取消的匹配会把同一批可执行货各写一次 ERP。
|
||||
|
||||
## Consequences
|
||||
|
||||
- 圈档仍互斥。顶替是取消的自动出口,不是第二套占用规则。
|
||||
- 日期没盖住或已经在写 ERP 时,这些货留在原匹配里。新清单只显示这次圈出来的行。
|
||||
- 人工关闭跨过顶替继续有效。未归属匹配的明细不再挡住圈档。
|
||||
+9
-1
@@ -1,5 +1,12 @@
|
||||
# 智能HR请假管理需求
|
||||
|
||||
## 制程品质异常预警(2026-10)
|
||||
|
||||
- 只读统计 OA 制程品质异常通知单。统计键是料号 + 不良类别,料号按原值,计次日期是申请日期。归档和在途计入,废弃和撤销不计入。
|
||||
- 近一年是扫描日减 1 年(含)到扫描日前 1 天(含),同一键 ≥ 3 才预警。当月按申请日期所在自然月计,含扫描日当天。当月笔数只决定升级给谁。
|
||||
- 品质担当每周收一封仍 ≥ 3 的全量清单。升级只在当月进入更高档的那一周发一次:第 1 笔主送品质和生产经副理,第 2 笔主送 COO,第 3 笔及以上主送老板并抄送 COO、品质、生产经副理。跳过的档不补发。渠道是 OA 邮件。
|
||||
- 规则已整理,尚未实现。OA 字段和发信方式见后续设计文档。一单多行计次、空不良类别、五个岗位的具体人员仍待确认。需求见 [制程品质异常预警需求](features/process-quality-alert/demand.md)。
|
||||
|
||||
## 年度教育训练计划(2026-10)
|
||||
|
||||
独立于入职、安全、精益、出国规章培训。年底按主办单位收集下一年度计划,讲师按月排课;课程库保存可重复使用的课件和试题,签到、录制、考试发布和完成状态记在月度场次上。未完成提醒每周一 09:00 发给当月仍有未完成场次的讲师,文案对齐人事课内部邮件。细则见 [features/training/annual-training-plan-demand.md](features/training/annual-training-plan-demand.md),设计方案见 [features/training/annual-training-plan-design.md](features/training/annual-training-plan-design.md),原型见 [features/training/annual-training-plan-prototype.html](features/training/annual-training-plan-prototype.html)。
|
||||
@@ -26,8 +33,9 @@
|
||||
## 设备验收预警(2026-09)
|
||||
|
||||
- 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。
|
||||
- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人发送汇总卡片和 Excel 明细。
|
||||
- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。第 1 档主送使用部门担当,第 2 档主送其经副理,直接主管也取这个人;E8 与 E10 相同,不取当前节点未办人。采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人发送汇总卡片和 Excel 明细。
|
||||
- 规则已冻结。验收单读 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)。
|
||||
- E8 补抓已接上(2026-10-26)。与 E10 分来源保存。暂停按撤销停表。没有作废、强制结束。见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md)、[technical.md](features/equipment-acceptance-warning/technical.md)。
|
||||
|
||||
## 合同付款预警 Agent(2026-08)
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
| [contract-payment-plan](contract-payment-plan/) | 合同付款计划 / 预警 Agent | [方案 V3](contract-payment-plan/contract-payment-warning-proposal-v3.md) · [工作台原型](contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html) · [人工复核原型](contract-payment-plan/contract-payment-review-prototype.html) · [Chat Agent 原型](contract-payment-plan/contract-payment-chat-agent-prototype.html) |
|
||||
| [equipment-maintenance](equipment-maintenance/README.md) | 设备维保助手 | [聊天原型](equipment-maintenance/equipment-maintenance-agent-chat-lofi.html) |
|
||||
| [equipment-acceptance-warning](equipment-acceptance-warning/README.md) | 设备验收停留预警 | [需求说明](equipment-acceptance-warning/demand.md) · [数据设计](equipment-acceptance-warning/technical.md) |
|
||||
| [process-quality-alert](process-quality-alert/demand.md) | 制程品质异常预警 | [需求说明](process-quality-alert/demand.md) · [原型](process-quality-alert/process-quality-alert-prototype.html) |
|
||||
| [training](training/) | 教育训练:新人培训与年度计划 | [年度教育训练计划需求](training/annual-training-plan-demand.md) · [设计方案](training/annual-training-plan-design.md) · [可点击原型](training/annual-training-plan-prototype.html) · [精益周任务规则](training/精益管理周任务规则手册.md) |
|
||||
| [faq](faq/) | 常用问题 / FAQ 缓存直答 | [运维手册](faq/faq_cache_ops_manual.md) · [模糊查询与 AI 自动维护设计](faq/faq_fuzzy_and_ai_maintenance_design.md) |
|
||||
|
||||
|
||||
@@ -244,7 +244,7 @@ flowchart TD
|
||||
| -------- | ------------------------------------------------------------------------------------------------------- |
|
||||
| 触发 | 本批存在必检文件缺件 |
|
||||
| 聚合 | 审计仍是一个检核批次一条;企微按接收人拆信,不在正文逐票展开缺失明细 |
|
||||
| 内容 | 标题为「销售开票附件缺件」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示到详情 Excel 补齐。不写业务方代号和批次号 |
|
||||
| 内容 | 标题为「销售开票附件缺件提醒」。正文为中文年月、该人负责且本批缺失的文件类型(缺多少份、涉及多少张发票),并提示到详情 Excel 补齐。不写业务方代号和批次号 |
|
||||
| 明细查看 | 全部缺件 `invoice`、缺失文件列表和处理状态以 Excel 与执行记录为准 |
|
||||
| 接收人 | 平台管理员在 Chat「通知配置」按文件类型从系统用户多选。未配置任何接收人时不发送空通知,并在发送记录标记未发送原因 |
|
||||
| 技术失败 | 不作为缺件通知;按排程通知人单独告警 |
|
||||
@@ -271,7 +271,7 @@ flowchart TD
|
||||
4. 企业微信按文件类型接收人拆成每人一封,正文只含该人负责的缺件类型,并提供本批 Excel 下载入口;完整 `invoice` 明细不在消息正文展开。审计仍是每批一条。
|
||||
5. OA 关联字段不完整记录被直接丢弃,不进入异常、缺件、打印或归档结果。
|
||||
6. 销售 invoice 清单、文档库(同一 LibraryID、销售独立根 FolderID、建文件夹/复制接口)、周任务星期二、按文件类型选人界面已确认;ERP PO 取数:发票 HXJM、采购单 TGHX,关联 `TRIM(oma99)=TRIM(pmm99)` 已接线(独立抓取,见技术设计 §3.4);OA 销货放行单取数已接线(E10 `ft_xqqgsq` + OpenAPI,独立排程周二 05:30),凭据只进环境变量。
|
||||
7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。
|
||||
7. 归档复制采用「同名跳过」:目标目录已有同名文件不覆盖、不报缺件。文档库自动加上的「(重命名)」改回原名,同一目录多出来的该后缀副本删除。
|
||||
|
||||
## 9. 待补充事项
|
||||
|
||||
|
||||
@@ -281,7 +281,7 @@ OA 销货放行申请单改为查 E10 `ecology10.dbo.ft_xqqgsq`:出货时间 `
|
||||
|
||||
类型目录与一期文件对应(**已确认固定,不改名**):`PO订单`、`报关资料`、`销货放行申请单`、`发票`、`报关单`、`提单`。
|
||||
|
||||
ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 `invoice` 关联、命名和文件完整性校验后,**复制**到「所有归档」下该发票子目录(不移动类型目录原件)。同一 `invoice` 的所有成功资料必须集中在同一归档子目录。**重复文件策略:同名跳过**——目标子目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档。类型目录写入失败或归档复制失败属于技术失败,不可降级为缺件。
|
||||
ERP/OA 打印或目录扫描的成功文件先写入类型存放目录;完成 `invoice` 关联、命名和文件完整性校验后,**复制**到「所有归档」下该发票子目录(不移动类型目录原件)。同一 `invoice` 的所有成功资料必须集中在同一归档子目录。**重复文件策略:同名跳过**——目标子目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档。文档库自动改成 `原名.pdf(重命名)` 时,先删掉多余副本,再用 `Item/Rename` 把留下的那份改成不含扩展名的 `原名`。改成 `原名.pdf` 会被文档库判成同名。类型目录写入失败或归档复制失败属于技术失败,不可降级为缺件。
|
||||
|
||||
### 5.2 建议持久化实体
|
||||
|
||||
|
||||
@@ -373,7 +373,7 @@ sequenceDiagram
|
||||
|
||||
- ERP/OA 打印或目录扫描的成功文件先写入当月类型存放目录,再校验关联字段和命名后复制到「所有归档/{invoice_no}/」。
|
||||
- 同一 invoice 的所有文件进入同一归档子目录;不同 invoice 不得混放。
|
||||
- 复制采用幂等策略:**同名跳过**。目标目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档;不按内容指纹覆盖。归档只 `Copy`、不 `Move`。
|
||||
- 复制采用幂等策略:**同名跳过**。目标目录已有相同 `LeafName` 时不覆盖、不报缺件,记为已归档;不按内容指纹覆盖。文档库复制后的真实名字是 `原名.pdf(重命名)`,扩展名存在附件上,界面显示为 `原名.pdf(重命名).pdf`。把它改成 `原名.pdf` 会被判成同名;`Item/Rename` 只写入不含扩展名的 `原名`。同一目录多出来的该后缀副本先 `Item/Recycle` 删除(进入回收站,不彻底删除)。归档只 `Copy`、不 `Move`。
|
||||
- `invoice_no`、业务单号和路径变量必须做路径穿越校验。
|
||||
- 临时目录和日志不得输出密码、Token 或完整外部系统会话信息。
|
||||
- 归档记录保存来源路径、临时路径、归档路径、指纹、Profile 版本和处理时间。
|
||||
|
||||
@@ -171,7 +171,7 @@ OA“厂商预付款请款作业”的流程状态不作为付款完成依据;
|
||||
- 周汇总批次发送失败时,发送状态旁提供图标;点击后展示该批次的失败原因(如收件人未绑定企业微信、卡片或附件发送失败及企微返回说明)。
|
||||
- 合同台账与待确认列表应支持按合同编号、流程编号、采购单号、供应商名称或申请人模糊检索。
|
||||
- 合同台账应展示四张汇总卡(即将到期 7 日内、逾期未付、未到期 7 日外、本月应付),均按合同计数、统计全部已解析台账;点击卡片过滤下方列表,再次点击取消过滤。即将到期、逾期未付、未到期互斥;本月应付可与这三项重叠。行级「待补充」仍可出现在状态列,但不作为汇总卡。
|
||||
- 合同台账四个阶段列都按日期依据显示已逾期、即将到期或未到期。预付款和出货款另可显示已付;验收款和质保款不能标已付。日期依据缺失时写明原因,不使用「待补充日期」:预付款为合同归档日未填,出货款为交货日期未填,验收款为验收单未归档,质保款为质保到期日未定。
|
||||
- 合同台账四个阶段列都按日期依据显示已逾期、即将到期或未到期。四个阶段对上 ERP 或手动标记后显示已付。日期依据缺失时写明原因,不使用「待补充日期」:预付款为合同归档日未填,出货款为交货日期未填,验收款为验收单未归档,质保款为质保到期日未定。
|
||||
- 同步 OA、强制覆盖 OA 字段、批量重解析存量合同、扫描生成预警和发送预警仅管理员可见;普通授权用户只可查询台账、详情和周汇总批次。
|
||||
- 管理员可手动触发 OA 同步和预警扫描;执行应后台异步化,不阻塞页面请求。
|
||||
|
||||
|
||||
@@ -5,4 +5,4 @@
|
||||
| **需求说明** | 产品、业务、研发 | [demand.md](demand.md) |
|
||||
| **数据设计** | 研发 | [technical.md](technical.md) |
|
||||
|
||||
**状态**:规则已冻结(2026-09-29)。只读同步、Chat 作业面、每日扫描和周五企业微信已实现(2026-10-12)。入口与合同付款预警相同,内置 Agent `equipment_acceptance`。页签有停留情况、发送记录和预警配置。当前处理人取当前节点上的 `userid`,不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。见 [funclist.md](../../funclist.md)「设备验收预警」。
|
||||
**状态**:E10 与 E8 都按使用部门担当发第 1 档。E8 暂停按停表。见 [funclist.md](../../funclist.md)「设备验收预警」。
|
||||
@@ -210,9 +210,9 @@
|
||||
<label class="day">超过 <input value="30" /> 天</label>
|
||||
</div>
|
||||
<div class="people">
|
||||
<div class="line"><span class="tag">主送</span><span class="plain">当前节点处理人</span></div>
|
||||
<div class="line"><span class="tag">主送</span><span class="plain">使用部门担当</span></div>
|
||||
<div class="line"><span class="tag">抄送</span><span class="plain">其直接主管、采购担当</span></div>
|
||||
<span class="note">随当前单据变化,这里不选人</span>
|
||||
<span class="note">随单据上的使用部门担当变化,这里不选人</span>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
@@ -222,7 +222,7 @@
|
||||
<label class="day">超过 <input value="37" /> 天</label>
|
||||
</div>
|
||||
<div class="people">
|
||||
<div class="line"><span class="tag">主送</span><span class="plain">当前节点处理人的经副理</span></div>
|
||||
<div class="line"><span class="tag">主送</span><span class="plain">使用部门担当的经副理</span></div>
|
||||
<div class="line">
|
||||
<span class="tag">抄送</span>
|
||||
<div class="chips">
|
||||
|
||||
@@ -1,101 +1,42 @@
|
||||
# 设备验收预警需求说明
|
||||
|
||||
> **版本**:V1.0
|
||||
> **更新日期**:2026-10-08
|
||||
> **状态**:规则已冻结。只读同步、停留列表、发送记录、预警配置、每日扫描和周五企业微信已实现。入口与合同付款预警相同。当前处理人取当前节点上的 `userid`,不查询、不保存 `isremark`。发送时刻不在配置页,默认排程每天 06:00 扫描、每周五 18:00 发送。数据设计见 [technical.md](technical.md)。
|
||||
> **适用范围**:OA 资产验收单停留预警、企业微信通知、固定岗位配置
|
||||
> **版本**:V2.0
|
||||
> **更新日期**:2026-10-26
|
||||
> **状态**:E10 已上线。E8 查询已接上。字段和关联见 [technical.md](technical.md)。
|
||||
|
||||
## 1. 背景与目标
|
||||
验收单从第一次进入「使用部门担当」起按自然日累计。未归档、已经开始计时,且可以验收不是明确为否的单据,超过 30 / 37 / 44 / 51 天升级提醒。合同付款预警只在归档后取日期,本需求不改那条规则。
|
||||
|
||||
资产验收流程可能在某个节点停留很久。从流程进入「使用部门担当」起按自然日累计停留时间,对仍可验收的未归档单据按 30/37/44/51 天升级提醒,避免验收长期挂起。
|
||||
## 1. 哪些单要提醒
|
||||
|
||||
现有合同付款预警只在验收单归档后读取 OA(`formtable_main_324`,`currentnodetype=3`),不监控进行中的节点停留。本需求是独立能力,不改付款预警的归档口径。
|
||||
| 条件 | 结果 |
|
||||
| --- | --- |
|
||||
| 未归档,可以验收为是或未标明,计时起点已有值 | 提醒 |
|
||||
| 还没进入使用部门担当 | 不计时 |
|
||||
| 可以验收明确为否 | 不监控 |
|
||||
| 退回、撤销 | 停表,取消还没发出的提醒,仍留在列表 |
|
||||
| 归档 | 不抓、不进列表。下次同步从本地删掉,未发出的提醒取消 |
|
||||
| E10 的作废、强制结束、暂停 | 停表 |
|
||||
| E8 | 没有作废、强制结束。暂停与 E10 一样停表 |
|
||||
|
||||
## 2. 范围
|
||||
计时起点写入后不改。换后续节点,或退回、无法验收后再进入,仍从第一次的起点累计,不从 0 重计,已发过的档不重发。
|
||||
|
||||
### 2.1 本期已冻结
|
||||
## 2. 谁收
|
||||
|
||||
- 监控对象、计时起点、自然日累计、停表与再进入规则。
|
||||
- 四档升级的主送、抄送,以及当前节点处理人、上级、申请人的取人规则。
|
||||
- 采购经副理、COO、总经理三个固定岗位可在管理界面配置,禁止在代码中写死姓名或账号。
|
||||
- 企业微信为唯一通知渠道。每日扫描只生成待发送记录;发送时刻可配置,初始为每周五 18:00,按收件人汇总一条。
|
||||
- 数据来源见第 7 节。缺字段的单据跳过并留下原因。
|
||||
每一档在同一段累计里只发一次。超过才发,刚好等于不发。第 4 档默认关闭。
|
||||
|
||||
停留列表已接到对话页:内置 Chat Agent `equipment_acceptance`,与合同付款预警一样替换消息列表和输入框。
|
||||
|
||||
### 2.2 本期不做
|
||||
|
||||
- 不接 Dify 对话。
|
||||
- 不撤回已发送的企业微信。停表只取消尚未发出的预警。
|
||||
- 「使用部门担当」之前的节点(ERP 触发、申请人确认、直属上级)不参与计时。
|
||||
|
||||
## 3. 监控对象
|
||||
|
||||
数据源是 E10 验收单主表,字段对照见 [technical.md](technical.md)。只纳入同时满足以下条件的流程:
|
||||
|
||||
- 未归档
|
||||
- 有效(未撤回、未作废)
|
||||
- 可以验收
|
||||
|
||||
计时起点是该流程**第一次进入「使用部门担当」**。进入之后按自然日持续累计,中途更换后续节点不重置。流程图上该节点之后的使用部门经理、品质担当、品质经理、公用主管、设备管理部、设备管理部经理、固定资产管理人、COO、总经理、总务知会,都算在同一段累计时间里。节点正式名称以 OA 为准。
|
||||
|
||||
## 4. 停表与再进入
|
||||
|
||||
出现任一情况立即停止计时,并取消尚未发出的预警:
|
||||
|
||||
- 归档
|
||||
- 退回、撤回、作废
|
||||
- 验收单上为无法验收(说明正文是 `ycsm`,只作留痕,不单独触发通知)
|
||||
|
||||
已确认:退回或无法验收后再进入,「使用部门担当」的计时起点 `sbsyrjssj` 不会改写,签核天数仍按第一次写入的时间计算,不从 0 重计,也不另找起点。四档按这一段累计天数各发一次,不因再进入而重发。`sfzfth` 不考虑从退回(`0`)改回正常(`1` 或空);不靠这个变化恢复计时。撤回、作废、归档后的同一请求不再恢复。
|
||||
|
||||
## 5. 升级与收件人
|
||||
|
||||
每一档在同一计时周期只产生一次待发送。每日扫描判断是否跨档,跨档后等到固定推送时刻再发。一次汇总前若跨了多档,各档都保留,合并进该收件人的同一条汇总,不逐单刷屏。
|
||||
|
||||
| 停留 | 主送 | 抄送 |
|
||||
| 超过 | 主送 | 抄送 |
|
||||
| --- | --- | --- |
|
||||
| 超过 30 天 | 当前节点处理人(担当) | 其直接主管、采购担当 |
|
||||
| 超过 37 天 | 当前节点处理人的经副理 | COO、采购经副理 |
|
||||
| 超过 44 天 | COO | 采购经副理 |
|
||||
| 超过 51 天 | 总经理 | COO、采购经副理 |
|
||||
| 30 天 | 使用部门担当 | 其直接主管、采购担当 |
|
||||
| 37 天 | 该担当的经副理 | COO、采购经副理 |
|
||||
| 44 天 | COO | 采购经副理 |
|
||||
| 51 天 | 总经理 | COO、采购经副理 |
|
||||
|
||||
第 4 轮在配置里单独开关,默认关闭。关闭时不生成、也不发送总经理这一轮。打开后,下一次扫描才按超过第 4 档的天数产生待发送。前 3 轮不受这个开关影响。
|
||||
- 使用部门担当、直接主管、经副理都按表单上的使用部门担当取,不按当前节点未办人。E8 与 E10 相同。
|
||||
- 采购担当是申请人。
|
||||
- COO、采购经副理、总经理在配置页选择。
|
||||
- 对不上人就记失败,不改发给别人。
|
||||
|
||||
人员解析:
|
||||
## 3. 怎么发
|
||||
|
||||
- 担当、直接主管、经副理取**当前节点处理人**及其上级,不固定成「使用部门担当」本人。
|
||||
- 采购担当取该流程的**申请人**。
|
||||
- 采购经副理、COO、总经理是固定岗位。配置初始值分别为赵琴、COO、廖总,必须能在管理界面修改。代码与环境文件不得写死这三个人的姓名或账号。
|
||||
- 当前节点有多名处理人时,主送这些处理人;直接主管、经副理按各处理人展开后去重。
|
||||
- 收件人解析失败(无上级、未绑定企业微信)时,该条保持失败可追查,不改发给别人。
|
||||
|
||||
## 6. 推送
|
||||
|
||||
已确认:扫描与发送分离。发送时刻做成可配置,**初始对齐合同付款预警,为每周五 18:00**(见 [合同付款预警需求](../contract-payment-plan/demand.md))。到点后按收件人合并为一条企业微信汇总卡片,并紧跟一份只含该收件人明细的 Excel。这份 Excel 按收件人归档,挂在发送记录表的 Excel 附件列上,点文件名再下载。卡片不逐条列出验收单,也不区分主送和抄送。渠道只有企业微信。
|
||||
|
||||
## 7. 数据来源
|
||||
|
||||
权威设计见 [technical.md](technical.md)。摘要如下:
|
||||
|
||||
- 连接只用 `.env.shared` 的 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`。验收单在 `ecology10`,流程实例字典库为 `weaver_wfc`,节点定义字典库为 `weaver_wfp`。
|
||||
- 验收单主表是 `ecology10.dbo.ft_gdzcysdv2`。验收单单号 `ysddh`,采购单号 `cgdh`。计时起点 `sbsyrjssj` 只在第一次进入「使用部门担当」时写入,之后不改。
|
||||
- `sybmdd`(使用部门担当)、`sbglry`(设备管理人员)存人员 ID,关联 `eteams.dbo.employee.ID`,用工号 `JOB_NUM` 匹配 HXOPS 用户。
|
||||
- `sfkyzcys` 是是否可以正常验收:**0 是可以,1 是不可以**,与常见 0/1 相反。空值不纳入监控。无法验收说明正文是 `ycsm`,只留痕,不单独触发停表。
|
||||
- `sfzfth`:**0 是退回,1 和空都是流程正常。** 空值不当成退回。作废不看这一列。
|
||||
- 未归档、归档、作废、撤销看 `wfc_requestbase.flowstatus`(`1` 审批中,`3` 正常归档,`5` 已作废)。`7`、`8`、`99`、`-99` 都按撤销处理,停表且不再提醒。当前节点看 `weaver_wfc.dbo.wfc_currentnode.nodeid`,名称关联 `weaver_wfp.dbo.wfp_node`。`lastnodeid` 是最后操作节点,不当作当前节点。申请人 `sqr` 已确认是人员 ID。
|
||||
- 当前处理人在 `weaver_wfc.dbo.wfc_operate`。`userid` 是操作人,与当前节点按 `requestid`、`nodeid` 对齐,再关联 `employee`。不查询、不保存 `isremark`。同一人只留一行。每日扫描按这些人展开四档收件人。
|
||||
|
||||
直接主管取当前处理人的 `employee.SUPERIOR`。经副理用该人的 `employee.DEPARTMENT` 查 `eteams.dbo.hrm_matrix_condition_data`,人在 `eteams.dbo.hrm_matrix_value_data.relate_id`。不查 E8 矩阵。采购经副理、COO、总经理不从矩阵取,只读界面配置。
|
||||
|
||||
## 8. 验收标准(视图到位后的实现对照)
|
||||
|
||||
| 编号 | 条件 | 期望 |
|
||||
| --- | --- | --- |
|
||||
| AC-01 | 尚未进入「使用部门担当」 | 不计时、不产生预警 |
|
||||
| AC-02 | 签核天数超过 30/37/44/51 | 各档只产生一次待发送,刚好等于还不发。收件人符合第 5 节 |
|
||||
| AC-03 | 进入后更换后续节点 | 累计天数不重置 |
|
||||
| AC-04 | 归档、退回、撤回、作废或无法验收 | 立即停表,取消未发送预警,已发送消息保留 |
|
||||
| AC-05 | 退回或无法验收后再次进入 | 签核天数仍从原 `sbsyrjssj` 计算。不把 `sfzfth` 从 `0` 改回正常当作恢复 |
|
||||
| AC-06 | 发送时刻 | 默认每周五 18:00 按收件人汇总;时刻可配置 |
|
||||
| AC-07 | 修改采购经副理、COO、总经理配置 | 此后新产生的预警使用新人员,不改历史已发送记录 |
|
||||
- 每天扫描,生成待发送。默认每周五 18:00 按收件人发一条企业微信汇总,并附一份只含该人的 Excel。时刻可改。
|
||||
- 已发送的不撤回、不重发。
|
||||
+17
-16
@@ -175,7 +175,7 @@
|
||||
<section class="view" id="v-config">
|
||||
<div class="hero"><div><h1>预警配置</h1><p>天数默认 30、37、44、51,须逐档增大。保存后只影响尚未发送的预警。</p></div></div>
|
||||
<div class="ladder">
|
||||
<label class="rung"><span class="k">第 1 档</span><span class="num"><input id="cfgDay0" type="number" min="1" value="30" /><em>天</em></span><small id="rungWho0">当前处理人</small></label>
|
||||
<label class="rung"><span class="k">第 1 档</span><span class="num"><input id="cfgDay0" type="number" min="1" value="30" /><em>天</em></span><small id="rungWho0">使用部门担当</small></label>
|
||||
<label class="rung"><span class="k">第 2 档</span><span class="num"><input id="cfgDay1" type="number" min="1" value="37" /><em>天</em></span><small id="rungWho1">经副理</small></label>
|
||||
<label class="rung"><span class="k">第 3 档</span><span class="num"><input id="cfgDay2" type="number" min="1" value="44" /><em>天</em></span><small id="rungWho2">COO</small></label>
|
||||
<label class="rung"><span class="k">第 4 档</span><span class="num"><input id="cfgDay3" type="number" min="1" value="51" /><em>天</em></span><small id="rungWho3">总经理</small></label>
|
||||
@@ -217,28 +217,29 @@
|
||||
let digest = null;
|
||||
const cfg = { buyer: '赵琴', coo: 'COO', boss: '廖总', when: '每周五 18:00', days: [30, 37, 44, 51] };
|
||||
const orders = [
|
||||
{ id:'YS-2026-0138', po:'CG-2026-0812', applicant:'王磊', node:'设备管理部', handlers:['陈工'], supervisor:'何主管', deputy:'周经副理', entered:'2026-08-08', days:53, cycle:1, state:'watching', sent:[0,1,2], fail:'', stop:'', note:'同一周期已发过前三档,本周只待第 4 档。' },
|
||||
{ id:'YS-2026-0142', po:'CG-2026-0744', applicant:'张敏', node:'品质经理', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-15', days:46, cycle:1, state:'watching', sent:[0,1], fail:'', stop:'', note:'换到品质经理后累计不重置。' },
|
||||
{ id:'YS-2026-0155', po:'CG-2026-0901', applicant:'赵丽', node:'使用部门经理', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-23', days:38, cycle:1, state:'watching', sent:[0], fail:'', stop:'', note:'' },
|
||||
{ id:'YS-2026-0160', po:'CG-2026-0886', applicant:'孙浩', node:'公用主管', handlers:['吴敏','林可'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-30', days:31, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'当前节点两名处理人,直接主管相同,抄送去重为钱伟。' },
|
||||
{ id:'YS-2026-0188', po:'CG-2026-0910', applicant:'刘洋', node:'品质担当', handlers:['郑凯'], supervisor:'', deputy:'孙经理', entered:'2026-08-28', days:33, cycle:1, state:'watching', sent:[], fail:'直接主管缺失', stop:'', note:'第 1 档无法解析直接主管,保持失败,不改发。' },
|
||||
{ id:'YS-2026-0172', po:'CG-2026-0933', applicant:'陈静', node:'品质担当', handlers:['郑凯'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-09-10', days:20, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'未超过第 1 档,只监控不发。' },
|
||||
{ id:'YS-2026-0098', po:'CG-2026-0618', applicant:'周宁', node:'使用部门担当', handlers:['马超'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-10', days:60, cycle:1, state:'watching', sent:[0,1,2,3], fail:'', stop:'', note:'无法验收后再进入,签核天数仍从第一次写入的计时起点计算,不从 0 重计。' },
|
||||
{ id:'YS-2026-0071', po:'CG-2026-0550', applicant:'吴芳', node:'品质经理', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-01', days:40, cycle:1, state:'stopped', sent:[0], fail:'', stop:'无法验收', note:'无法验收说明:到货规格与请购不符。未发送的后续档已取消。' },
|
||||
{ id:'YS-2026-0066', po:'CG-2026-0702', applicant:'郑明', node:'使用部门经理', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-20', days:18, cycle:1, state:'stopped', sent:[], fail:'', stop:'退回', note:'退回后立即停表。再进入仍用第一次的计时起点,不按 sfzfth 改回正常来恢复。' },
|
||||
{ id:'YS-2026-0201', po:'CG-2026-1008', applicant:'韩冰', node:'直属上级', handlers:['—'], supervisor:'', deputy:'', entered:'', days:0, cycle:0, state:'out', sent:[], fail:'', stop:'', note:'尚未进入使用部门担当,不计时。' }
|
||||
{ id:'YS-2026-0138', po:'CG-2026-0812', applicant:'王磊', node:'设备管理部', owner:'陈工', handlers:['陈工'], supervisor:'何主管', deputy:'周经副理', entered:'2026-08-08', days:53, cycle:1, state:'watching', sent:[0,1,2], fail:'', stop:'', note:'同一周期已发过前三档,本周只待第 4 档。' },
|
||||
{ id:'YS-2026-0142', po:'CG-2026-0744', applicant:'张敏', node:'品质经理', owner:'李倩', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-15', days:46, cycle:1, state:'watching', sent:[0,1], fail:'', stop:'', note:'换到品质经理后累计不重置。' },
|
||||
{ id:'YS-2026-0155', po:'CG-2026-0901', applicant:'赵丽', node:'使用部门经理', owner:'周涛', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-23', days:38, cycle:1, state:'watching', sent:[0], fail:'', stop:'', note:'' },
|
||||
{ id:'YS-2026-0160', po:'CG-2026-0886', applicant:'孙浩', node:'公用主管', owner:'吴敏', handlers:['吴敏','林可'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-30', days:31, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'当前节点有两名处理人,第 1 档只发给使用部门担当吴敏,抄送其直接主管钱伟。' },
|
||||
{ id:'YS-2026-0188', po:'CG-2026-0910', applicant:'刘洋', node:'品质担当', owner:'郑凯', handlers:['郑凯'], supervisor:'', deputy:'孙经理', entered:'2026-08-28', days:33, cycle:1, state:'watching', sent:[], fail:'直接主管缺失', stop:'', note:'第 1 档无法解析使用部门担当的直接主管,保持失败,不改发。' },
|
||||
{ id:'YS-2026-0172', po:'CG-2026-0933', applicant:'陈静', node:'品质担当', owner:'郑凯', handlers:['郑凯'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-09-10', days:20, cycle:1, state:'watching', sent:[], fail:'', stop:'', note:'未超过第 1 档,只监控不发。' },
|
||||
{ id:'YS-2026-0098', po:'CG-2026-0618', applicant:'周宁', node:'使用部门担当', owner:'马超', handlers:['马超'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-10', days:60, cycle:1, state:'watching', sent:[0,1,2,3], fail:'', stop:'', note:'无法验收后再进入,签核天数仍从第一次写入的计时起点计算,不从 0 重计。' },
|
||||
{ id:'YS-2026-0071', po:'CG-2026-0550', applicant:'吴芳', node:'品质经理', owner:'李倩', handlers:['李倩'], supervisor:'钱伟', deputy:'孙经理', entered:'2026-08-01', days:40, cycle:1, state:'stopped', sent:[0], fail:'', stop:'无法验收', note:'无法验收说明:到货规格与请购不符。未发送的后续档已取消。' },
|
||||
{ id:'YS-2026-0066', po:'CG-2026-0702', applicant:'郑明', node:'使用部门经理', owner:'周涛', handlers:['周涛'], supervisor:'马主管', deputy:'孙经理', entered:'2026-08-20', days:18, cycle:1, state:'stopped', sent:[], fail:'', stop:'退回', note:'退回后立即停表。再进入仍用第一次的计时起点,不按 sfzfth 改回正常来恢复。' },
|
||||
{ id:'YS-2026-0201', po:'CG-2026-1008', applicant:'韩冰', node:'直属上级', owner:'', handlers:['—'], supervisor:'', deputy:'', entered:'', days:0, cycle:0, state:'out', sent:[], fail:'', stop:'', note:'尚未进入使用部门担当,不计时。' }
|
||||
];
|
||||
|
||||
/**
|
||||
* 按档位序号取主送与抄送。天数读配置,人员规则不随天数变化。
|
||||
* 第 1 档取当前处理人及其主管、申请人;其后三档读固定岗位。
|
||||
* 第 1 档主送使用部门担当,抄送其直接主管和申请人。第 2 档主送该担当的经副理。其后两档读固定岗位。
|
||||
*/
|
||||
function audience(order, level) {
|
||||
if (level === 0) {
|
||||
const cc = [];
|
||||
if (order.supervisor) cc.push(order.supervisor);
|
||||
cc.push(order.applicant + '(采购担当)');
|
||||
return { to: order.handlers.slice(), cc, blocked: order.supervisor ? '' : '直接主管缺失' };
|
||||
const blocked = order.owner ? (order.supervisor ? '' : '直接主管缺失') : '使用部门担当缺失';
|
||||
return { to: order.owner ? [order.owner] : [], cc, blocked };
|
||||
}
|
||||
if (level === 1) return { to:[order.deputy], cc:[cfg.coo, cfg.buyer], blocked: order.deputy ? '' : '经副理缺失' };
|
||||
if (level === 2) return { to:[cfg.coo], cc:[cfg.buyer], blocked:'' };
|
||||
@@ -436,14 +437,14 @@
|
||||
*/
|
||||
function renderRules() {
|
||||
const rows = [
|
||||
[cfg.days[0], '当前节点处理人', '直接主管、采购担当'],
|
||||
[cfg.days[1], '当前处理人的经副理', cfg.coo + '、' + cfg.buyer],
|
||||
[cfg.days[0], '使用部门担当', '其直接主管、采购担当'],
|
||||
[cfg.days[1], '使用部门担当的经副理', cfg.coo + '、' + cfg.buyer],
|
||||
[cfg.days[2], cfg.coo, cfg.buyer],
|
||||
[cfg.days[3], cfg.boss, cfg.coo + '、' + cfg.buyer]
|
||||
];
|
||||
$('ruleBox').innerHTML = rows.map(([day, to, cc]) => '<tr><td><b>超过 ' + day + ' 天</b></td><td>' + to + '</td><td>' + cc + '</td></tr>').join('')
|
||||
+ '<tr><td><b>解析失败</b></td><td colspan="2">保持失败可追查,不改发给别人</td></tr>';
|
||||
['当前处理人', '经副理', cfg.coo, cfg.boss].forEach((text, index) => { $('rungWho' + index).textContent = text; });
|
||||
['使用部门担当', '使用部门担当的经副理', cfg.coo, cfg.boss].forEach((text, index) => { $('rungWho' + index).textContent = text; });
|
||||
$('banner').textContent = '从第一次进入「使用部门担当」起按自然日累计,换节点不重新计算。超过 ' + cfg.days.join('/') + ' 天各提醒一次,' + cfg.when + ' 合并成一条企业微信。无法验收、退回、撤回、作废或归档后不再提醒。';
|
||||
}
|
||||
|
||||
|
||||
@@ -1,438 +1,154 @@
|
||||
# 设备验收预警设计
|
||||
# 设备验收预警数据来源
|
||||
|
||||
> **版本**:V1.19
|
||||
> **更新日期**:2026-10-12
|
||||
> **状态**:只读同步、停留列表、发送记录、预警配置、每日扫描和周五企业微信已实现。入口与合同付款预警相同:内置 Agent `equipment_acceptance`。当前处理人取当前节点上的 `wfc_operate.userid`,不查询、不保存 `isremark`。发送时刻不在配置表,默认排程是每天 06:00 扫描、每周五 18:00 发送,可在排程页改 Cron。
|
||||
> **业务规则**:[demand.md](demand.md)。本文只说明数据从哪读、人员怎么对上、哪些事实还缺。
|
||||
> **版本**:V2.0
|
||||
> **更新日期**:2026-10-26
|
||||
> **状态**:E10 已在抓。E8 查询已接上,暂停按撤销停表。业务规则见 [demand.md](demand.md)。
|
||||
|
||||
## 1. 结论
|
||||
E10 用 `OA_E10_SQLSERVER_*`,E8 用 `OA_SQLSERVER_*`。一边失败不改走另一边。人员 ID 不混用。流程实例 ID 两边都会撞号,本地用来源分开。合同付款只取 E8 归档日,那条 SQL 不复用。
|
||||
|
||||
验收单主数据读 OA E10 的 `ecology10.dbo.ft_gdzcysdv2`。人员 ID 到 `eteams.dbo.employee` 取出工号,再用工号对上 HXOPS 用户。流程是否归档、作废、撤销,读 `wfc_requestbase.flowstatus`。当前节点读 `wfc_currentnode.nodeid`,再关联 `wfp_node.nodename`。`lastnodeid` 是最后操作节点,不拿来当当前节点。当前处理人读 `wfc_operate.userid`,与当前节点按 `requestid`、`nodeid` 对齐,再关联 `employee`。不查询、不保存 `isremark`。同一节点同一人只留一行。每日扫描按这些处理人展开四档收件人。
|
||||
两边都只抓未归档。E10 不取 `flowstatus = 3`,E8 不取 `currentnodetype = 3`。这两列为空仍抓。退回、作废、强制结束、撤销仍抓。
|
||||
|
||||
## 2. 连接
|
||||
两边表单上的是否字段都是 **0 = 是,1 = 否**。落库翻成 0 = 否、1 = 是。
|
||||
|
||||
查询走 E10 SQL Server,不走 E8 `ecology`。账号只从 `.env.shared` 读取下面三个变量,不把主机、账号、密码写进代码或文档:
|
||||
## 1. 同一件事两边各看哪一列
|
||||
|
||||
| 变量 | 用途 |
|
||||
| ----------------------------- | ------------------- |
|
||||
| `OA_E10_SQLSERVER_HOST` | E10 SQL Server 主机 |
|
||||
| `OA_E10_SQLSERVER_USERNAME` | 只读账号 |
|
||||
| `OA_E10_SQLSERVER_PASSWORD` | 只读密码 |
|
||||
|
||||
验收单在 `ecology10`,人员表在同一实例的 `eteams`。流程字典写明:`wfc_requestbase`、`wfc_currentnode`、`wfc_operate` 所属库 `weaver_wfc`,`wfp_node` 所属库 `weaver_wfp`。现场曾在 `ecology10` 的 `INFORMATION_SCHEMA` 查出 `wfc_requestbase` 的列,查询时先按字典库名,账号看不到 `weaver_wfc` / `weaver_wfp` 时再改用 `ecology10` 里的同名表。本功能要求上述三个变量已配置,不回退到 E8 的 `OA_SQLSERVER_*`。
|
||||
|
||||
## 3. 验收单主表
|
||||
|
||||
表:`ecology10.dbo.ft_gdzcysdv2`。
|
||||
|
||||
| 字段 | 含义 | 在预警里的用法 |
|
||||
| ------------- | -------------------- | -------------------------------------------------------------------------------------------- |
|
||||
| `ysddh` | 验收单单号 | 台账、详情、企业微信上的验收单单号。 |
|
||||
| `cgdh` | 采购单号 | 台账上的采购单号。 |
|
||||
| `htbh` | 合同编号 | 只保存这一列。表上没有第二合同编号。 |
|
||||
| `sbsyrjssj` | 设备使用人员计时时间 | 计时起点。第一次进入「使用部门担当」时写入,之后不改。为空表示还没开始计时。 |
|
||||
| `sybmdd` | 使用部门担当 | 人员 ID,关联 `eteams.dbo.employee.ID`。 |
|
||||
| `sbglry` | 设备管理人员 | 人员 ID,关联方式同 `sybmdd`。 |
|
||||
| `sqr` | 申请人 | 预警规则里的采购担当。已确认是人员 ID,关联 `eteams.dbo.employee.ID`。 |
|
||||
| `syry` | 使用人员 | 样例中同样是长整型 ID,按 `employee.ID` 关联。 |
|
||||
| `gzglry` | 固资管理人员 | 人员字段。样例多为空;非空时按同一 ID 关联。 |
|
||||
| `dx` | 使用人员1 | 同上。 |
|
||||
| `agent` | 资管经办人 | 同上。 |
|
||||
| `sfzfth` | 是否作废退回 | OA 上 **0 是退回,1 和空都是流程正常。** 落库 `is_returned` 翻转成 0 否、1 是,空收成 0。作废不看这一列,作废看 `flowstatus = 5`。 |
|
||||
| `sfkyzcys` | 是否可以正常验收 | OA 上 **0 表示可以,1 表示不可以。** 落库 `can_accept` 翻转成 0 否、1 是。空值保持空,不当成可以验收。 |
|
||||
| `ycsm` | 无法验收说明 | 说明正文。落库 `cannot_accept_note`。只留痕,不单独触发停表。停表仍看 `sfkyzcys = 1`。 |
|
||||
|
||||
`sfkyzcys` 只表达能不能正常验收。说明正文是 `ycsm`。
|
||||
|
||||
已确认按 ID 关联人员的是 `sybmdd`、`sbglry`、`sqr`。`syry`、`gzglry`、`dx`、`agent` 在样例结果里是同类长整型,设计上人员列统一走 `employee.ID`。若核对后某列不是人员 ID,只改该列,不改工号匹配方式。
|
||||
|
||||
## 4. 人员怎么对上系统用户
|
||||
|
||||
`eteams.dbo.employee` 使用这些列:
|
||||
|
||||
| 字段 | 含义 |
|
||||
| ------------ | ----------------------------------------------------- |
|
||||
| `ID` | 与验收单人员字段、操作人 `userid` 关联 |
|
||||
| `USERNAME` | 显示姓名。只用于展示,不作为匹配键。 |
|
||||
| `JOB_NUM` | 工号。对应 HXOPS 用户表的工号,工号在系统用户中唯一。 |
|
||||
| `DEPARTMENT` | 部门 ID。只用来查经副理 |
|
||||
| `SUPERIOR` | 直接主管的人员 ID。再关联本表 `ID` |
|
||||
|
||||
关联顺序:
|
||||
|
||||
1. 验收单上的人员 ID = `eteams.dbo.employee.ID`。
|
||||
2. 取该行 `JOB_NUM`。
|
||||
3. 用 `JOB_NUM` 匹配 HXOPS 用户工号(`users.employee_id`)。
|
||||
4. 企业微信接收人用该用户已绑定的 `wecom_userid`。
|
||||
|
||||
对不上时该条保持失败,可追查,不改发给别人。失败包括:人员 ID 为空、`employee` 无此 ID、`JOB_NUM` 为空、工号在 HXOPS 无用户、用户未绑定企业微信。
|
||||
|
||||
直接主管取当前处理人在 `employee.SUPERIOR` 上的人员 ID,不查矩阵。经副理才查 E10 矩阵,见第 4.1 节。不从 `ft_gdzcysdv2` 臆造,也不查 E8 的 `Matrixtable_3`。
|
||||
|
||||
采购经副理、COO、总经理只读界面配置,不从矩阵表取。
|
||||
|
||||
## 4.1 直接主管与经副理
|
||||
|
||||
按当前处理人查,不按申请人查,也不查 E8。
|
||||
|
||||
1. 当前处理人是 `wfc_operate.userid`,等于 `eteams.dbo.employee.ID`。
|
||||
2. 直接主管是该员工的 `SUPERIOR`。这是人员 ID,再关联 `employee.ID` 取姓名和工号。空或关联不上就记失败,不改发给别人。
|
||||
3. 经副理用该员工的 `DEPARTMENT`(部门 ID)查 E10 部门矩阵。人员在 `hrm_matrix_value_data.relate_id`,再同样关联 `employee`。不要把这个 ID 当成企微 userid,也不要对 `HrmResource.id`。
|
||||
|
||||
多名当前处理人时,各自取 `SUPERIOR` 和经副理,然后去重。
|
||||
|
||||
三个固定值已确认。`tenant_key` 为 `temkc46eme`。矩阵 `id` `1115770797884751874` 是苏州和信的「HXJM-审批矩阵」,取自 `eteams.dbo.hrm_matrix.id`。经副理取值配置 `id` `1115771897387991041` 取自 `eteams.dbo.hrm_matrix_value_config`:`config_name` 为「经副理」,且 `matrix_id` 为上面这个矩阵。该配置 `config_type` 是 `resource`,`single_type = 1`(单选)。查人仍用 `hrm_matrix_value_data.relate_id`,不要把配置表的 `id` 当成人员 ID。`delete_type = 0` 为正常。同一矩阵下还有总经理等其他取值配置,不拿来当经副理。
|
||||
|
||||
矩阵 id 和经副理配置 id 按下面两条查出,不在代码里另找别的矩阵:
|
||||
|
||||
```sql
|
||||
-- 苏州和信「HXJM-审批矩阵」的 id。
|
||||
SELECT id
|
||||
FROM eteams.dbo.hrm_matrix
|
||||
WHERE tenant_key = 'temkc46eme'
|
||||
AND matrix_name = N'HXJM-审批矩阵'
|
||||
AND delete_type = 0
|
||||
AND enable_status = 1;
|
||||
-- 结果:1115770797884751874
|
||||
|
||||
-- 该矩阵下 config_name 为「经副理」的取值配置 id。
|
||||
SELECT id
|
||||
FROM eteams.dbo.hrm_matrix_value_config
|
||||
WHERE tenant_key = 'temkc46eme'
|
||||
AND matrix_id = 1115770797884751874
|
||||
AND config_name = N'经副理'
|
||||
AND delete_type = 0;
|
||||
-- 结果:1115771897387991041
|
||||
```
|
||||
|
||||
已用 `employee.DEPARTMENT = 1115763045510725632` 核对:`hrm_matrix_value_data.matrix_data_id` 没有这个值。因此这张矩阵不能把 `matrix_data_id` 直接当成部门 ID。部门 ID 改到条件表 `hrm_matrix_condition_data.relate_id` 里按字符串匹配,先取出矩阵数据行,再取值:
|
||||
|
||||
```sql
|
||||
-- 经副理。表都在 eteams.dbo,不能省库名。
|
||||
-- 返回的 relate_id 是人员 ID,再关联 eteams.dbo.employee.ID,不要当成企微 userid。
|
||||
-- :department_id 取当前处理人的 employee.DEPARTMENT,必须按字符串比较。
|
||||
-- 已用部门 1115763045510725632 跑通,返回一名经副理。
|
||||
SELECT v.relate_id
|
||||
FROM eteams.dbo.hrm_matrix_value_data AS v
|
||||
WHERE v.tenant_key = 'temkc46eme' -- 租户
|
||||
AND v.matrix_id = 1115770797884751874 -- hrm_matrix:苏州和信「HXJM-审批矩阵」的 id
|
||||
AND v.matrix_value_config_id = 1115771897387991041 -- hrm_matrix_value_config:该矩阵下 config_name 为「经副理」的 id,不是人员 ID
|
||||
AND v.delete_type = 0 -- 0 正常,1/2/3 都是删除
|
||||
AND v.matrix_data_id IN (
|
||||
-- 部门 ID 不在 matrix_data_id 上。先从条件表找出矩阵数据行。
|
||||
SELECT c.matrix_data_id
|
||||
FROM eteams.dbo.hrm_matrix_condition_data AS c
|
||||
WHERE c.tenant_key = 'temkc46eme'
|
||||
AND c.matrix_id = 1115770797884751874
|
||||
AND c.delete_type = 0
|
||||
AND c.relate_id = :department_id -- 字符串,例如 '1115763045510725632'
|
||||
)
|
||||
```
|
||||
|
||||
条件配置 id 还没限定。若同一部门对出多行,再按 `matrix_condition_config_id` 收窄。
|
||||
|
||||
## 5. 计时与停表在现有字段上怎么落
|
||||
|
||||
计时起点用 `sbsyrjssj`。已确认它只在第一次进入「使用部门担当」时写入一次,之后不改写。从该时间起到当前按自然日累计,换节点不重置。字段为空的单据视为尚未开始计时,不产生预警。
|
||||
|
||||
退回只看 `sfzfth`。OA 取值是 0=是、1=否。落库列 `is_returned` 先翻转成标准布尔:0 否,1 是。已确认取值:
|
||||
|
||||
| OA `sfzfth` | 本地 `is_returned` | 含义 | 预警 |
|
||||
| --- | --- | --- | --- |
|
||||
| `0` | `1` | 是,退回 | 立即停表,取消尚未发出的预警。不考虑从 `0` 改回 `1` 或空。 |
|
||||
| `1` | `0` | 否,流程正常 | 不因本字段停表 |
|
||||
| 空 | `0` | 否,流程正常 | 与 OA `1` 相同,不当成退回 |
|
||||
|
||||
字段中文名是「是否作废退回」,已确认的取值只区分退回和正常。作废、撤销仍看下一节的 `flowstatus`,不用 `sfzfth` 代替。出现 `0`、`1`、空以外的值时,不判退回,也不当正常,先记下来待确认。
|
||||
|
||||
不考虑 `sfzfth` 从 `0` 改回 `1` 或空。不把这种改写当作恢复计时或新周期。
|
||||
|
||||
是否可以正常验收看 `sfkyzcys`。OA 取值与常见布尔相反:0=是、1=否。落库列 `can_accept` 翻转成 0 否、1 是。空值不翻转成否。
|
||||
|
||||
| OA `sfkyzcys` | 本地 `can_accept` | 含义 | 预警 |
|
||||
| --- | --- | --- | --- |
|
||||
| `0` | `1` | 是,可以正常验收 | 其他条件也满足时继续计时 |
|
||||
| `1` | `0` | 否,不可以正常验收 | 立即停表,取消尚未发出的预警 |
|
||||
| 空 | 空 | 未标明 | 不纳入监控,不按「可以验收」处理 |
|
||||
|
||||
退回或无法验收后再进入,`sbsyrjssj` 仍是第一次写入的时间,签核天数就按它计算,不从 0 重计。不读取、不保存 `wfc_operate.operateround`。
|
||||
|
||||
## 5.1 流程实例与节点定义
|
||||
|
||||
OA 数据字典:
|
||||
|
||||
| 表 | 中文名 | 字典所属库 | 用途 |
|
||||
| --- | --- | --- | --- |
|
||||
| `wfc_requestbase` | 流程实例基本信息表 | `weaver_wfc` | 一条流程一行。状态、编号、最后操作节点。 |
|
||||
| `wfc_currentnode` | 流程当前节点表 | `weaver_wfc` | 流程当前停在哪个节点。没有处理人。 |
|
||||
| `wfp_node` | 工作流节点基础信息表 | `weaver_wfp` | 节点定义。用 `id` 取出节点名称和节点类型。 |
|
||||
|
||||
`wfc_currentnode` 字段:
|
||||
|
||||
| 字段 | 字典含义 | 用法 |
|
||||
| 事实 | E10 | E8 |
|
||||
| --- | --- | --- |
|
||||
| `requestid` | 流程实例 id。来源说明写着 `wfc_operate` | 等于 `wfc_requestbase.requestid` |
|
||||
| `nodeid` | 数据所在节点 ID。来源说明写着 `wfc_operate` | 等于 `wfp_node.id`,这是当前节点 |
|
||||
| `nodetype` | 节点类型 | 本表字典没有 0–9。类型以 `wfp_node.nodetype` 为准 |
|
||||
| `delete_type` | 是否删除 | 只取 `0` |
|
||||
| `operate_log_id` | 批次号 | 不查询、不保存 |
|
||||
| `creator` | 数据插入人 | 不是当前处理人 |
|
||||
| 验收单单号 | `ft_gdzcysdv2.ysddh` | `formtable_main_324.ysddh` |
|
||||
| 采购单号 | `cgdh` | `cgdh` |
|
||||
| 合同编号 | `htbh` | `htbh` |
|
||||
| 流程编号 | `wfc_requestbase.requestmark` | `formtable_main_324.lcbh` |
|
||||
| 标题 | `wfc_requestbase.requestname`。流程默认标题 | `workflow_requestbase.requestname` |
|
||||
| 创建时间 | `wfc_requestbase.createdatetime`。流程创建时间,不是 `create_time` | `workflow_requestbase.createdate` 加 `createtime` |
|
||||
| 计时起点 | `sbsyrjssj`。空 = 未开始 | `syddjssj`。空 = 未开始 |
|
||||
| 使用部门担当 | `sybmdd` = `eteams.employee.ID` | `sybmdd` = `HrmResource.id` |
|
||||
| 申请人(采购担当) | `sqr` = `employee.ID` | `workflow_requestbase.creater` = `HrmResource.id` |
|
||||
| 直接主管 | 该担当的 `employee.SUPERIOR` | 该担当部门的 `Matrixtable_3.zz` |
|
||||
| 经副理 | 该担当部门的 E10 矩阵 | 该担当部门的 `Matrixtable_3.jfl`。值就是企微 userid |
|
||||
| 退回 | `sfzfth`:0 退回,1 和空未退回 | `sfzfth`:同上 |
|
||||
| 可以验收 | `sfkyzcys`:0 可以,1 不可以,空未标明 | `sfkys`:同上 |
|
||||
| 无法验收说明 | `ycsm`,只留痕 | `ycsm`,只留痕 |
|
||||
| 当前节点 | `wfc_currentnode.nodeid` → `wfp_node.nodename` | `currentnodeid` → `workflow_nodebase.nodename` |
|
||||
| 当前处理人 | `wfc_operate.userid`。不读 `isremark`。只展示 | `workflow_currentoperator.userid`,且 `isremark = 0`。只展示 |
|
||||
| 审批中 / 归档 | `flowstatus` 1 / 3 | `currentnodetype` 0、1、2 / 3 |
|
||||
| 撤销 | `flowstatus` 为 7、8、99、-99 | `currentstatus = 1` |
|
||||
| 暂停 | `flowstatus = 7`,按撤销停表 | `currentstatus = 0`,同样写成 `7`,停表 |
|
||||
| 作废 / 强制结束 | `flowstatus` 5 / 4 | 没有,不查 |
|
||||
|
||||
可以验收为空仍监控。只有明确为否才停表,显示为无法验收。计时起点为空仍是未开始。
|
||||
|
||||
当前处理人不是收件人。第 1 档主送是使用部门担当,第 2 档主送是这个人的经副理。
|
||||
|
||||
## 2. E10
|
||||
|
||||
库:验收单 `ecology10`,人员 `eteams`,流程 `weaver_wfc`,节点 `weaver_wfp`。看不到 `weaver_wfc` / `weaver_wfp` 时,流程表和节点表改用 `ecology10` 里的同名表。
|
||||
|
||||
关联,只取 `delete_type = 0`:
|
||||
|
||||
1. `ft_gdzcysdv2.FORM_DATA_ID` = `wfc_form_data.dataid`
|
||||
2. `wfc_form_data.requestid` = `wfc_requestbase.requestid`
|
||||
3. `wfc_requestbase.requestid` = `wfc_currentnode.requestid`
|
||||
4. `wfc_currentnode.nodeid` = `wfp_node.id`,名称 `nodename`
|
||||
5. `wfc_operate.requestid`、`nodeid` 对上当前节点,人是 `userid`
|
||||
|
||||
`lastnodeid` 是刚办过的节点,不是当前节点。分流时当前节点可以多行,都保留。计时按整单,不按节点重置。
|
||||
|
||||
### 2.1 验收单 `ft_gdzcysdv2`
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `ysddh` | 验收单单号 |
|
||||
| `cgdh` | 采购单号 |
|
||||
| `htbh` | 合同编号。没有第二合同编号 |
|
||||
| `sbsyrjssj` | 计时起点。第一次进入使用部门担当时写入,之后不改 |
|
||||
| `sybmdd` | 使用部门担当,人员 ID |
|
||||
| `sbglry` | 设备管理人员,人员 ID |
|
||||
| `sqr` | 申请人,人员 ID |
|
||||
| `sfzfth` | 是否退回。0 是,1 和空否。作废不看这列 |
|
||||
| `sfkyzcys` | 是否可以正常验收。0 是,1 否,空未标明 |
|
||||
| `ycsm` | 无法验收说明 |
|
||||
|
||||
`syry`、`gzglry`、`dx`、`agent` 也是人员 ID,预警不用。流程编号和标题在流程表,不在这张验收单上。不读验收日期。
|
||||
|
||||
### 2.2 流程 `wfc_requestbase.flowstatus`
|
||||
|
||||
`status` 是文本,不拿来停表。结束时间用 `finishdatetime`,不读 `finshdatetime`。流程编号是 `requestmark`。标题是 `requestname`(流程默认标题),不用 `requestnamehtml` 和 `requestnametitle`。创建时间是 `createdatetime`,不用 `create_time`。
|
||||
|
||||
| 值 | 含义 | 预警 |
|
||||
| --- | --- | --- |
|
||||
| 0 | 草稿 | 不监控 |
|
||||
| 1 | 审批中 | 其他条件满足才计时 |
|
||||
| 3 | 正常归档 | 不抓取 |
|
||||
| 4 | 强制结束 | 停表 |
|
||||
| 5 | 已作废 | 停表 |
|
||||
| 6 | 待提交 | 不监控 |
|
||||
| 7 | 暂停 | 按撤销停表 |
|
||||
| 8 | 撤销 | 停表 |
|
||||
| 99、-99 | 撤销 | 停表 |
|
||||
|
||||
退回后 `flowstatus` 仍可能是 1。退回只看 `sfzfth = 0`。
|
||||
|
||||
### 2.3 人员
|
||||
|
||||
`eteams.employee`:`ID` 对人员字段和 `userid`,`USERNAME` 只展示,`JOB_NUM` 对 `users.employee_id`,发送用 `users.wecom_userid`。`DEPARTMENT` 查经副理,`SUPERIOR` 是直接主管的人员 ID。
|
||||
|
||||
经副理:用使用部门担当的 `DEPARTMENT` 对 `hrm_matrix_condition_data.relate_id`(字符串),取出 `matrix_data_id`,再在 `hrm_matrix_value_data` 取 `relate_id`。该值是人员 ID,再对 `employee.ID`,不是企微 userid。`matrix_data_id` 不是部门 ID。
|
||||
|
||||
固定条件:`tenant_key = temkc46eme`,矩阵 `1115770797884751874`(HXJM-审批矩阵),经副理配置 `1115771897387991041`,`delete_type = 0`。同一部门多行时再按 `matrix_condition_config_id` 收窄。
|
||||
|
||||
对不上人、没有主管或经副理:该席位失败,不改发给别人。
|
||||
|
||||
## 3. E8
|
||||
|
||||
库:`ecology`。人员主键是 `HrmResource.id`,不能对 `eteams.employee.ID`。
|
||||
|
||||
关联:
|
||||
|
||||
1. `ft_gdzcysdv2.FORM_DATA_ID` = `wfc_form_data.dataid`,且 `wfc_form_data.delete_type = 0`。验收单上没有流程编号列,不读 `requestmark`。
|
||||
2. `wfc_form_data.requestid` = `wfc_requestbase.requestid`。本地快照按这个 `requestid` 唯一。归档看 `flowstatus = 3`,不看验收日期。
|
||||
3. `wfc_requestbase.requestid` = `wfc_currentnode.requestid`,且 `wfc_currentnode.delete_type = 0`。
|
||||
4. `wfc_currentnode.nodeid` = `wfp_node.id`。展示名称用 `wfp_node.nodename`。
|
||||
5. 分流时一条流程可以有多行当前节点。这些行都保留,节点名称分别列出。计时仍按整单累计,不按节点重置。
|
||||
1. `formtable_main_324.requestId` = `workflow_requestbase.requestid`
|
||||
2. `workflow_requestbase.currentnodeid` = `workflow_nodebase.id`,名称 `nodename`
|
||||
3. `workflow_currentoperator.requestid` = `workflow_requestbase.requestid`,且 `nodeid` = `currentnodeid`,且 `isremark = 0`
|
||||
|
||||
`wfc_requestbase.lastnodeid` 仍是「最后操作节点 ID」,只表示刚办过的节点。当前节点以 `wfc_currentnode.nodeid` 为准。
|
||||
`lastnodeid` 不是当前节点。`isremark`:0 未操作,2 已操作,4 归档,8 / 9 抄送。只留 0。关联不上不跳过整单。不另存 `isremark`。计时不按节点名过滤。
|
||||
|
||||
`wfp_node.nodetype`:0 发起,1 审批,2 确认,3 结束,4 子流程节点,5 投票,6 循环审批,7 自动处理,8 等待,9 查阅。`nodeattr`:0 一般节点,1 分流点,2 分流中间点,3 合流点。`wfc_requestbase.lastnodetype` 只标了「最后操作流程节点类型」,字典没有给出 0–9。不把 `nodetype` 的枚举直接套到 `lastnodetype`。
|
||||
### 3.1 验收单 `formtable_main_324`
|
||||
|
||||
流程状态以 `flowstatus` 为准。同表的 `status` 是最长 1000 的文本,没有枚举,不拿来判断停表。
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `cgdh` | 采购单号 |
|
||||
| `requestId` | 流程实例 ID |
|
||||
| `ysddh` | 验收单单号 |
|
||||
| `htbh` | 合同编号 |
|
||||
| `lcbh` | 流程编号 |
|
||||
| `syddjssj` | 使用担当接收时间。计时起点,之后不改 |
|
||||
| `sybmdd` | 使用部门担当,人员 ID |
|
||||
| `sfzfth` | 是否退回。0 是,1 和空否 |
|
||||
| `sfkys` | 是否可以正常验收。0 是,1 否,空未标明 |
|
||||
| `ycsm` | 无法验收说明。只留痕 |
|
||||
|
||||
| `flowstatus` | 字典含义 | 预警 |
|
||||
### 3.2 流程 `workflow_requestbase`
|
||||
|
||||
| 字段 | 值 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| `0` | 草稿 | 不监控 |
|
||||
| `1` | 审批中 | 其他条件也满足时可以计时 |
|
||||
| `3` | 正常归档 | 停表,不恢复旧周期 |
|
||||
| `4` | 强制结束 | 流程已结束。业务未单列这一项,先按停表、不恢复处理 |
|
||||
| `5` | 已作废 | 停表,不恢复旧周期 |
|
||||
| `6` | 待提交 | 不按审批中处理 |
|
||||
| `7` | 暂停 | 已确认与撤销相同:停表,不再提醒,不恢复旧周期 |
|
||||
| `8` | 撤销 | 停表,不再提醒,不恢复旧周期 |
|
||||
| `99`、`-99` | `99` 为业务确认值;`-99` 是字典截断处 | 与撤销相同:停表,不再提醒 |
|
||||
| `currentnodetype` | 0、1、2 | 审批中。创建 / 批准 / 提交都算进行中 |
|
||||
| `currentnodetype` | 3 | 正常归档。不抓取 |
|
||||
| `currentstatus` | 空 | 流程正常。再看 `currentnodetype` |
|
||||
| `currentstatus` | 1 | 撤销,停表 |
|
||||
| `currentstatus` | 0 | 暂停。与 E10 一样停表,写成 `7` |
|
||||
| `currentnodeid` | | 当前节点 ID |
|
||||
| `lastnodeid` | | 最后操作节点,不是当前节点 |
|
||||
| `creater` | | 申请人,人员 ID。没有 `creator` 这一列 |
|
||||
| `requestname` | | 标题 |
|
||||
| `createdate` | | 创建日期。与 `createtime` 拼成创建时间 |
|
||||
| `createtime` | | 创建时分秒 |
|
||||
|
||||
字典没有值为「退回」的流程状态。退回后 `flowstatus` 仍可能是 `1`(审批中)。退回以验收单 `sfzfth = 0` 为准,不从 `flowstatus` 推断。
|
||||
没有作废、强制结束。不把任何值写成这两类。`currentstatus` 出现空、0、1 以外的值时,不当成正常。`status` 是文本,不拿来停表。`deleted` 是是否删除,不当作废。
|
||||
|
||||
`finishdatetime` 是流程归档时间。字典另有拼写 `finshdatetime`(少一个 i),含义写成「流程归档时间、作废时间」。现场列清单里是 `finishdatetime`。查询只用 `finishdatetime`,不查 `finshdatetime`。
|
||||
### 3.3 人员
|
||||
|
||||
`lastoperator` 是最后操作人,`wfc_currentnode.creator` 是插行的人,都不是当前待办人。`delete_type` 是记录是否删除,不是作废。作废看 `flowstatus = 5`。
|
||||
使用部门担当、申请人:`HrmResource.id` 取姓名,`workcode` 对 `users.employee_id`,发送用 `users.wecom_userid`。
|
||||
|
||||
## 5.2 流程操作人
|
||||
直接主管和经副理:用该担当的 `departmentid` 对 `Matrixtable_3.bm`,必须只命中一行。`zz` 是直接主管,`jfl` 是经副理。这两个值就是 `HrmResource.id`,也是企微 userid,发送时直接用。无部门、不是一行或对不上,该席位失败,不改发给别人。
|
||||
|
||||
表:`weaver_wfc.dbo.wfc_operate`,中文名「流程操作人表」。当前处理人在这张表。
|
||||
## 4. 状态对照里已经落地的决定
|
||||
|
||||
| 字段 | 字典含义 | 用法 |
|
||||
| --- | --- | --- |
|
||||
| `requestid` | 流程实例 id | 等于 `wfc_currentnode.requestid` |
|
||||
| `nodeid` | 数据所在节点 ID | 等于 `wfc_currentnode.nodeid`。只取当前节点上的操作人 |
|
||||
| `userid` | 操作人 id | 当前处理人。关联 `eteams.dbo.employee.ID` |
|
||||
| `processuser` | 实际操作人 ID | 已经代办或实际点过的人。待办人取 `userid`,不取这一列 |
|
||||
| `usertype` | 人员类型 | 字典没有取值。先按 `userid` 关联员工,关联不上记失败 |
|
||||
| `isremark` | 操作状态 | 不查询、不保存。当前处理人就是当前节点上的 `userid` |
|
||||
| `preisremark` | 插入时的操作状态,插入后不变更 | 不查询、不保存 |
|
||||
| `operatedatetime` | 操作日期时间 | 已办才会有操作时间。不能单靠它为空就把抄送、转发都算成待办 |
|
||||
| `showorder` | 未操作者的显示顺序 | 说明表里包含未操作的人 |
|
||||
| `operateround` | 节点第几次到达 | 不查询、不保存 |
|
||||
| `isbereject` | 是否退回操作 | 字典没有 0/1。退回仍以 `sfzfth = 0` 为准 |
|
||||
| `isprocessing` | 执行中时,流程不出现在待办、已办 | 字典没有哪个值表示执行中。该状态的行不发预警 |
|
||||
| `delete_type` | 是否删除 | 只取 `0` |
|
||||
| `optgroupid` | 操作者批次 | 不查询、不保存 |
|
||||
| `batch_number` | 批次号 | 不查询、不保存。与 `wfc_currentnode.operate_log_id` 一样不参与预警 |
|
||||
|
||||
当前节点上的 `userid` 都是当前处理人。同一人只留一行。直接主管、经副理按各人展开后去重。会签关系 `signorder` 的取值未给,不改变「这些人都要通知」。
|
||||
|
||||
## 6. 查询形态
|
||||
|
||||
同一实例上跨库只读,不把人员 ID 当姓名用。
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
f.ysddh,
|
||||
f.cgdh,
|
||||
f.htbh,
|
||||
f.sbsyrjssj,
|
||||
f.sfzfth,
|
||||
f.sfkyzcys,
|
||||
f.ycsm,
|
||||
f.sybmdd,
|
||||
owner.USERNAME AS owner_name,
|
||||
owner.JOB_NUM AS owner_job_num,
|
||||
f.sbglry,
|
||||
equip.USERNAME AS equip_name,
|
||||
equip.JOB_NUM AS equip_job_num,
|
||||
f.sqr,
|
||||
applicant.USERNAME AS applicant_name,
|
||||
applicant.JOB_NUM AS applicant_job_num,
|
||||
r.requestid,
|
||||
r.flowstatus,
|
||||
r.finishdatetime,
|
||||
c.nodeid,
|
||||
n.nodename,
|
||||
n.nodetype,
|
||||
op.userid,
|
||||
handler.USERNAME AS handler_name,
|
||||
handler.JOB_NUM AS handler_job_num
|
||||
FROM ecology10.dbo.ft_gdzcysdv2 AS f
|
||||
LEFT JOIN eteams.dbo.employee AS owner ON owner.ID = f.sybmdd
|
||||
LEFT JOIN eteams.dbo.employee AS equip ON equip.ID = f.sbglry
|
||||
LEFT JOIN eteams.dbo.employee AS applicant ON applicant.ID = f.sqr
|
||||
LEFT JOIN weaver_wfc.dbo.wfc_form_data AS d
|
||||
ON d.dataid = f.FORM_DATA_ID
|
||||
AND d.delete_type = 0
|
||||
LEFT JOIN weaver_wfc.dbo.wfc_requestbase AS r
|
||||
ON r.requestid = d.requestid
|
||||
AND r.delete_type = 0
|
||||
LEFT JOIN weaver_wfc.dbo.wfc_currentnode AS c
|
||||
ON c.requestid = r.requestid
|
||||
AND c.delete_type = 0
|
||||
LEFT JOIN weaver_wfp.dbo.wfp_node AS n
|
||||
ON n.id = c.nodeid
|
||||
AND n.delete_type = 0
|
||||
LEFT JOIN weaver_wfc.dbo.wfc_operate AS op
|
||||
ON op.requestid = c.requestid
|
||||
AND op.nodeid = c.nodeid
|
||||
AND op.delete_type = 0
|
||||
LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid;
|
||||
```
|
||||
|
||||
验收单上没有流程编号、第二合同编号和验收日期,这三列不查询、也不写入本地表。归档只看 `flowstatus = 3`。不查询 `isremark`。当前节点上的 `userid` 就是当前处理人,同一人只留一行。一条流程有多个当前节点、每个节点有多名操作人时,这个查询会返回多行。库名按第 2 节:看不到 `weaver_wfc` / `weaver_wfp` 时改为 `ecology10`。`syry`、`gzglry`、`dx`、`agent` 需要展示或发通知时,按同样方式再关联 `employee`。不在应用里先全量拉人再在内存里对 ID。
|
||||
|
||||
## 7. 和需求规则的对照
|
||||
|
||||
| 需求事实 | 现在的来源 | 缺口 |
|
||||
| ---------------------- | -------------------------- | --------------------------- |
|
||||
| 验收单单号 | `ysddh` | 无 |
|
||||
| 采购单号 | `cgdh` | 无 |
|
||||
| 一张流程的身份 | `wfc_requestbase.requestid` | 不保存流程编号。验收日期不参与归档。 |
|
||||
| 计时起点 | `sbsyrjssj`,只写一次、不覆盖 | 再进入也用这个时间,不从 0 重计。 |
|
||||
| 使用部门担当 | `sybmdd` → `employee` | 无 |
|
||||
| 申请人(采购担当) | `sqr` → `employee` | 已确认是人员 ID |
|
||||
| 作废 | `flowstatus = 5` | 不看 `sfzfth` |
|
||||
| 撤销 | `flowstatus` 为 `7`、`8`、`99`、`-99` | 都停表且不再提醒。本地状态 `stopped_revoked` |
|
||||
| 退回 | OA `sfzfth = 0`,本地 `is_returned = 1` | `1` 和空都是未退回,本地写成 `0`。 |
|
||||
| 归档、未归档 | `flowstatus`:`3` 正常归档,`1` 审批中 | `4` 强制结束先按结束。 |
|
||||
| 当前节点名称 | `wfc_currentnode.nodeid` → `wfp_node.nodename` | 分流时可能多行,都保留。`lastnodeid` 不是当前节点 |
|
||||
| 当前处理人 | `wfc_operate.userid`,对齐当前 `requestid` + `nodeid` | 不使用 `isremark`。同一人只留一行 |
|
||||
| 可以正常验收 | OA `sfkyzcys`:`0` 可以,`1` 不可以。本地 `can_accept` 为 `1` 可以、`0` 不可以 | 空值不监控,也不写成 0。说明正文是 `ycsm`。 |
|
||||
| 直接主管 | 当前处理人的 `employee.SUPERIOR` | 人员 ID,再关联 `employee` |
|
||||
| 经副理 | `eteams.dbo.hrm_matrix_value_data.relate_id`。部门 ID 在 `eteams.dbo.hrm_matrix_condition_data.relate_id` | 查询已用部门 `1115763045510725632` 跑通。`matrix_data_id` 不是部门 ID |
|
||||
| 再次进入 | 仍用第一次的 `sbsyrjssj` | 不从 0 重计。不看 `sfzfth` 是否从 `0` 改回正常。不用 `operateround`。 |
|
||||
| 固定岗位三人 | 界面配置 | 不读 OA |
|
||||
|
||||
## 8. 已实现的同步
|
||||
|
||||
平台管理员调用 `POST /api/equipment-acceptance/sync`。连接只用 `OA_E10_SQLSERVER_HOST`、`OA_E10_SQLSERVER_USERNAME`、`OA_E10_SQLSERVER_PASSWORD`,不回退 E8 的 `OA_SQLSERVER_*`。库名先按字典;实例里没有 `weaver_wfc` 或 `weaver_wfp` 时,流程表和节点表改用 `ecology10`。人员库只认 `eteams`。
|
||||
|
||||
本地表保存 OA 同步快照,另有一张发送记录表。一张验收单在 `equipment_acceptance_orders` 里一行,当前节点和操作人在另外两张表。每次同步按 `request_id` 更新主表,并整批替换该单的节点和操作人。主表删除时,节点和操作人随外键级联删除,发送记录只把 `order_id` 置空并保留单号快照。不保存流程编号、第二合同编号和验收日期。归档看 `flow_status_raw = 3`,不看验收日期。每日扫描写入发送记录;停表时取消还没发出的行。
|
||||
|
||||
### 8.1 `equipment_acceptance_orders`
|
||||
|
||||
一张验收单的最近一次同步结果。`request_id` 唯一。
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | 本地主键 |
|
||||
| `request_id` | OA 流程实例 ID,来自 `wfc_requestbase.requestid`。一张流程一行 |
|
||||
| `acceptance_no` | 验收单单号,来自 `ysddh` |
|
||||
| `purchase_order_no` | 采购单号,来自 `cgdh` |
|
||||
| `contract_no` | 合同编号,来自 `htbh` |
|
||||
| `timer_started_at` | 计时起点,来自 `sbsyrjssj`。空表示还没开始计时 |
|
||||
| `dwell_days` | 签核天数。归档、强制结束、作废且有 `finished_at` 时停在结束日,否则算到同步日 |
|
||||
| `can_accept` | 是否可以正常验收。**0 否,1 是,空表示未标明。** 由 OA `sfkyzcys` 翻转而来,OA 是 0 是、1 否。空不写成 0 |
|
||||
| `cannot_accept_note` | 无法验收说明正文,来自 `ycsm`。空表示没有说明。不参与停表判断 |
|
||||
| `is_returned` | 是否退回。**0 否,1 是。** 由 OA `sfzfth` 翻转而来,OA 是 0 是、1 否。OA 的 1 和空都收成 0 |
|
||||
| `flow_status_raw` | `wfc_requestbase.flowstatus` 原值。1 审批中,3 正常归档,4 强制结束,5 已作废 |
|
||||
| `finished_at` | 流程结束时间,来自 `finishdatetime`。不拿它判断是否归档 |
|
||||
| `request_match_count` | 这一行对应的流程实例数,现在固定为 1 |
|
||||
| `owner_oa_id` / `owner_name` / `owner_job_num` | 使用部门担当。人员 ID 来自 `sybmdd`,姓名和工号来自 `employee` |
|
||||
| `equip_oa_id` / `equip_name` / `equip_job_num` | 设备管理人员,来自 `sbglry` |
|
||||
| `applicant_oa_id` / `applicant_name` / `applicant_job_num` | 申请人(采购担当),来自 `sqr` |
|
||||
| `monitor_status` | 监控状态,取值见下表 |
|
||||
| `present_in_source` | 这次同步是否还能在 OA 里看到这张单。看不到时保留上次内容,只把本列改成否 |
|
||||
| `synced_at` | 最近一次同步时间 |
|
||||
| `created_at` / `updated_at` | 本地创建、更新时间 |
|
||||
|
||||
`monitor_status`:
|
||||
|
||||
| 值 | 含义 |
|
||||
| --- | --- |
|
||||
| `watching` | 进行中。审批中、可以验收、未退回、已有计时起点 |
|
||||
| `not_started` | 未开始。没有计时起点,且没有更优先的停表原因 |
|
||||
| `stopped_returned` | 已退回。`is_returned = 1` |
|
||||
| `stopped_cannot_accept` | 无法验收。`can_accept = 0` |
|
||||
| `stopped_archived` | 已归档。`flow_status_raw = 3`,之后不再追踪预警 |
|
||||
| `stopped_force_finished` | 已强制结束。`flow_status_raw = 4` |
|
||||
| `stopped_voided` | 已作废。`flow_status_raw = 5` |
|
||||
| `stopped_revoked` | 已撤销,不再提醒。`flow_status_raw` 为 `7`、`8`、`99` 或 `-99` |
|
||||
| `excluded` | 不在监控范围。不含上面的撤销取值 |
|
||||
|
||||
退回、无法验收先于作废、归档、强制结束和撤销。撤销即使没有计时起点也记为 `stopped_revoked`,不记成未开始。归档、强制结束、作废、撤销且有 `finished_at` 时,签核天数截止到该日。`optgroupid`、`batch_number`、`operate_log_id` 不查询、不保存。
|
||||
|
||||
### 8.2 `equipment_acceptance_nodes`
|
||||
|
||||
这张单当前停在哪些节点。同一张单可以有多行,分流时每个当前节点一行。同一张单里 `order_id` + `node_id` 不重复。
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | 本地主键 |
|
||||
| `order_id` | 对应 `equipment_acceptance_orders.id` |
|
||||
| `node_id` | OA 当前节点 ID,来自 `wfc_currentnode.nodeid` |
|
||||
| `node_name` | 节点名称,来自 `wfp_node.nodename` |
|
||||
| `node_type` | 节点类型原值,来自 `wfp_node.nodetype`。0 发起,1 审批,2 确认,3 结束,4 子流程,5 投票,6 循环审批,7 自动处理,8 等待,9 查阅 |
|
||||
|
||||
`lastnodeid` 不写入本表。
|
||||
|
||||
### 8.3 `equipment_acceptance_operators`
|
||||
|
||||
当前节点上的操作人。同一节点同一人只留一行。不保存 `isremark`。
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | 本地主键 |
|
||||
| `order_id` | 对应 `equipment_acceptance_orders.id` |
|
||||
| `node_id` | 这个人所属的当前节点 |
|
||||
| `user_id` | OA 操作人 ID,来自 `wfc_operate.userid` |
|
||||
| `handler_name` | 操作人姓名 |
|
||||
| `handler_job_num` | 操作人工号 |
|
||||
|
||||
扫描按这张表的当前处理人展开直接主管和经副理。直接主管、经副理不在本表,查询时再读 E10。
|
||||
|
||||
`GET /api/equipment-acceptance/orders` 分页列表。`focus` 取 `watching`、`overdue`、`stopped`、`not_started`;`overdue` 是计时中且签核天数超过配置里的第 1 档,默认 30。响应里的 `summary` 始终统计全部单据。`GET /api/equipment-acceptance/orders/<id>` 含当前节点操作人。人员主键以字符串返回。平台管理员,或被授予启用中 Agent 的用户,可以打开列表和详情。同步仍只给平台管理员。停留列表四张汇总卡是进行中、已逾期、不再提醒、未开始。计时中且超过 30 天显示已逾期,未超过显示未超时。停留列表不显示第几档。
|
||||
|
||||
### 8.4 `equipment_acceptance_send_records`
|
||||
|
||||
一张验收单某一档的发送记录。同一张单同一档只有一行。待发送和解析失败的行每次扫描按当前处理人和当前岗位重算;已发送、已取消的姓名不再改写。Chat 页签「发送记录」读 `GET /api/equipment-acceptance/sends`。
|
||||
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `id` | 本地主键 |
|
||||
| `order_id` | 对应 `equipment_acceptance_orders.id`。验收单被删时置空 |
|
||||
| `acceptance_no` / `purchase_order_no` | 写入时的验收单单号、采购单号 |
|
||||
| `tier` | 第几档,1 到 4 |
|
||||
| `threshold_days` | 这一档当时的天数,例如 30 |
|
||||
| `to_text` / `cc_text` | 解析成功的主送、抄送姓名,用顿号拼接 |
|
||||
| `recipients_json` | 每个席位的角色、姓名、系统用户、企微 userid、OA 人员 ID 和失败原因 |
|
||||
| `status` | `pending` 待发送,`sent` 已发送,`failed` 解析或发送失败,`cancelled` 已取消 |
|
||||
| `sent_at` | 发出时间。只有 `sent` 才有 |
|
||||
| `error_message` | 解析失败或企业微信发送失败的原因。能发出的人仍会发送 |
|
||||
| `created_at` | 记录生成时间 |
|
||||
|
||||
页面入口与合同付款预警相同:迁移写入内置 Chat Agent,`agent_code=equipment_acceptance`,`conversation_mode=task_chat`。对话页按该编码替换消息列表和输入框,页签是停留情况、发送记录和预警配置。普通用户要在用户管理里授予该 Agent 后才看得到。
|
||||
|
||||
`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`round_4_enabled` 默认关闭,关闭时扫描不生成第 4 轮,发送也会跳过已经待发送的第 4 轮。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。
|
||||
|
||||
## 9. 扫描与发送
|
||||
|
||||
每天 06:00(Asia/Shanghai)排程 `equipment-acceptance-alert-scan` 先同步 E10,再按签核天数生成待发送。超过配置天数才进档,刚好等于还不发。默认 30/37/44/51。同一张单每一档只生成一次;已发送和已取消不重算、不重发。
|
||||
|
||||
收件人:
|
||||
|
||||
- 超过第 1 档:主送当前处理人,抄送其 `employee.SUPERIOR` 和申请人。
|
||||
- 超过第 2 档:主送各处理人部门的经副理,抄送配置里的 COO 和采购经副理。
|
||||
- 超过第 3 档:主送 COO,抄送采购经副理。
|
||||
- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。配置里的第 4 轮开关默认关闭,关闭时这一档不产生、也不发送。
|
||||
|
||||
人员 ID 先对 `eteams.dbo.employee`,再用 `JOB_NUM` 对 `users.employee_id`,发送用 `users.wecom_userid`。矩阵 `relate_id` 和 E10 人员 ID 都不是企微 userid。没有工号、对不上用户、没绑企微、没有主管或经副理、三个岗位没选,都记在该席位上,不改发给别人。至少有一名可发的人时状态是待发送;一个都没有则整档失败。
|
||||
|
||||
每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号先收一条文本卡片,标题「设备验收停留提醒」,正文先写共多少张验收单已逾期,再写各轮次数量,事件 `equipment_acceptance_warning`。紧跟着一条文件消息《设备验收停留提醒.xlsx》,列是验收单号、采购单号、申请人、轮次、停留天数、当前节点、当前处理人、通知身份。卡片不写主送、抄送,也不逐条列出验收单。卡片和文件都成功才改为已发送。任一失败则整档改为失败,并写上卡片或附件的原因;下次扫描会按当前处理人重算并回到待发送。每位收件人的 Excel 写入 `equipment_acceptance_send_files`,并记下对应的发送记录。发送失败也保留。发送记录表用 Excel 附件列下载,同一行可有多份。已发出的企业微信不撤回。
|
||||
|
||||
停表(归档、退回、撤回、作废、无法验收,以及强制结束)时,待发送和解析失败且还没 `sent_at` 的行改为已取消。
|
||||
|
||||
管理员在发送记录页可以立即「扫描预警」和「发送预警」,对应 `POST /api/equipment-acceptance/alerts/scan` 和 `POST /api/equipment-acceptance/alerts/send`。两个排程启动时写入,已有同编号时不覆盖。Cron 在排程页改,不在预警配置页。
|
||||
|
||||
不查询、不保存 `isremark`。不接 Dify。不给「使用部门担当」之前的节点单独计时。读 OA `sfkyzcys`、`sfzfth` 时仍是 0 表示是、1 表示否,禁止把 OA 原值直接写进 `can_accept`、`is_returned`。`ycsm` 只保存说明,不拿它判断能不能验收。
|
||||
|
||||
数据库升到迁移 `ea8c0a1b2c3d` 后,快照、配置和带收件人明细的发送记录一次建好,扫描才能落库。
|
||||
E8 `currentstatus = 0` 按 E10 的暂停处理:停表,本地流程状态写成 `7`。空、`0`、`1` 以外不写成审批中。
|
||||
@@ -56,7 +56,7 @@ _Avoid_: 仓库映射(专指映射档本身)
|
||||
### 在途调拨 · 平台侧概念
|
||||
|
||||
**匹配明细 (Matching Item)**:
|
||||
一次匹配从异动档圈定并永久绑定的执行明细行,承载库存核对结果、执行状态与 ERP 单据关联;自创建起归属唯一匹配。
|
||||
一次匹配从异动档圈定并永久绑定的执行明细行,承载库存核对结果、执行状态与 ERP 单据关联;自创建起归属唯一匹配。尚未归属任何匹配的行不占货。
|
||||
_Avoid_: 待办行、入站明细
|
||||
|
||||
**记录类型 (Record Kind)**:
|
||||
@@ -75,6 +75,26 @@ _Avoid_: 数据源、站点、Inbound Source Instance
|
||||
一个出入站来源实例上、按记录类型分开的一条抓取与文件状态。同一来源实例可同时有入站证据流和出站证据流。
|
||||
_Avoid_: 来源状态、部分就绪
|
||||
|
||||
**恢复处理 (Recovery Requery)**:
|
||||
对待恢复异常重新核对 ERP 库存的那一次查询。与「重查库存」是同一件事。
|
||||
_Avoid_: 把已人工关闭的记录重新打开
|
||||
|
||||
**人工关闭 (Manual Close)**:
|
||||
仓库人员判定某条明细不再继续调拨,并留下原因之后的状态。该状态只保留原因供查看。匹配顶替不把这些货放回新匹配。
|
||||
_Avoid_: 删除、恢复处理、匹配顶替
|
||||
|
||||
**占用 (Occupancy)**:
|
||||
一批货已被某次仍有效的匹配圈住,因而不能再进一次新匹配。人工关闭的货也算占用。没有挂上任何匹配的明细不构成占用。
|
||||
_Avoid_: 锁定、文件占用
|
||||
|
||||
**匹配顶替 (Matching Supersede)**:
|
||||
新匹配成立时对既有匹配的取代:同一调拨类型、同一组来源、日期范围被新范围完全盖住、且还没有任何 ERP 单据的旧匹配全部不再有效,其中的货按新匹配重新圈定。盖不住、正在写 ERP、或结果未知的旧匹配保持有效。
|
||||
_Avoid_: 重复匹配、再匹配一次
|
||||
|
||||
**结果未知 (Result Unknown)**:
|
||||
一次调拨写入之后,ERP 是否已经生成单据仍不能确定的状态。
|
||||
_Avoid_: 失败、待恢复异常
|
||||
|
||||
**收料 RPA (Receipt RPA · 旧名保留)**:
|
||||
入站证据抓取链路的**实现载体**:在途调拨的入站抓取复用货代 shipping_notice 域的 ShippingReceiptReport RPA,故该域内的数据表名(`shipping_receipt_report_*`)、RPA 契约(`shipping_receipt_rpa.v1` / `receipt_export_batch`)、目录(`freight_rpa/receipt/`)与环境变量(`FREIGHT_RPA_RECEIPT_*`)保留「收料/receipt」旧名,默认不改(与运行期收敛口径一致;如后续确需更名须单独立项评估)。它与在途调拨域所说的「入站(链路/文件/抓取)」是**同一条物理链路**——域内业务说辞(代码、API、前端文案)一律用「入站」,读代码遇到 receipt 旧名时按本条映射理解。
|
||||
_Avoid_: 把「收料」当作独立业务概念(在途调拨域已统一为入站);未经立项更名 shipping_notice 域保留的 receipt 旧名;新增代码用「收料」指代在途调拨业务
|
||||
@@ -12,7 +12,7 @@
|
||||
- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 入站文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。入站文件仓库列原值随明细落库于 `transfer_invoice_items.movement_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / `matching_expired`)。运维注意:来源的 movement 解析方案须把入站文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。
|
||||
- **调拨业务类型(2026-10-14 配置化,取代 2026-09-22 代码枚举)**:调拨类型来自平台配置(表 `transfer_type_configs`,管理端「在途调拨类型」页维护),代码不再枚举类型——类型决定匹配数据范围(范围规则引擎)、仓库取值(仓库定义)与字段转换(如批号前缀替换)。`transfer_runs.transfer_type` CHECK 约束已放开,类型合法性由配置表校验;`transfer_type` 在匹配创建**必填**(缺省/未配置/停用 fail-closed)。配置为空时前端空态 + 匹配 fail-closed(「暂无可用调拨类型」是设计行为,见 §11)。类型、范围规则与转换规则随匹配快照进 `scope_json` 参与匹配 Hash。历史:原三类型枚举(`in_transit_to_hub` 唯一开放 / `hub_repair_out`、`hub_to_hub` 占位「即将上线」)已整体退役,无兼容层。完整模型与上线 SOP 见 §11。
|
||||
- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费匹配/执行 Run/执行 Item 三类 Job。
|
||||
- **排程**:`in-transit-transfer`(建议 09:00 前)platform job(`schedule/job_registry.py`);当日入站文件缺失时该 job 自动触发收料 RPA 抓取(历史独立 `in-transit-receipt-file` job 已并入,注册表中不再单列)。
|
||||
- **排程**:`in-transit-transfer`(建议 09:00 前)platform job(`schedule/job_registry.py`);当日入站文件缺失时该 job 自动触发收料 RPA 抓取(历史独立 `in-transit-receipt-file` job 已并入,注册表中不再单列)。job_params:`transfer_types`(multi_select,选项源 `transfer_types`=启用中的类型配置,**留空=全部启用类型逐轮执行**,恢复复核与类型无关循环外只跑一次,类型配置为空/读取失败 fail-closed 硬失败)、`source_codes`(留空=全部启用入站来源)、`recover_history`(默认开)、`receipt_from/to_offset_days`(T−N 偏移,留空=全部成熟积压,T−2 成熟封顶由匹配层把关)。执行结果通知统一走排程「启用通知」框架完成卡,空数据日(全部类型均无 Run 且无错误)置 `domain_notification_managed` 静默(C5);历史任务级通知人参数 `notify_user_ids` 已移除。
|
||||
|
||||
## 2. 数据库
|
||||
|
||||
@@ -32,7 +32,8 @@
|
||||
| `IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS` | 5 | 老化升级阈值 |
|
||||
| `IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS` | 7 | 老化严重阈值 |
|
||||
| `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` | hxops-transfer | 归档 bucket |
|
||||
| `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | MinIO 连接(复用既有变量) |
|
||||
| `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | 容器内读写 MinIO(正式环境为 `host.docker.internal:9000`,勿改成公网主机) |
|
||||
| `MINIO_PUBLIC_BASE_URL` | 既有 | 预览预签名的浏览器主机。正式环境为 `http://ai.well-trust.com:9000`。单文件「下载」不把该地址交给浏览器,改由站点 HTTPS 接口回传,避免 HTTPS 页面打开 HTTP MinIO 被拦截 |
|
||||
| `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` | 既有 | 收料 RPA trigger 目录(复用收料链路) |
|
||||
|
||||
> 外部系统(ERP)端点与凭据由集成连接器的客户端实例/凭据引用管理,不使用独立环境变量;
|
||||
@@ -385,7 +386,7 @@ cd backend && flask db upgrade
|
||||
### 11.6 items 出生翻转与 D17 圈档互斥(迁移 `tt12c3d4e5f6a7`)
|
||||
|
||||
- **出生翻转(ADR 0001)**:`transfer_invoice_items` 退化为纯匹配执行记录——匹配创建时从档按类型范围规则圈定生成(`matching_id`/`ledger_record_id` 出生即绑定,业务字段取档原值、路由解析落 from/to);证据落地只写档不写行;重查 `requery_items` 弃 items SQL 圈行(`scope_item_query` 退役),改**对档对账**(同一编译器、同一快照规则):档有行无→补建、档证据变→刷新证据并重置待查、档记录被新版本替换→items 失效隔离(`blocked_file_removed` 语义)。
|
||||
- **D17 圈档互斥**:一条档记录一生只生成一次 items 绑定——匹配创建圈档排除「已被有效 items 占用」的档记录(存在所属匹配未取消、行未被失效隔离的 item 引用即占用)。取消匹配(items→cancelled)释放占用,记录可被后续匹配重圈;人工关闭/成功终态不释放(前者=业务裁定不拨,后者=档级封存)。重查只对账本匹配自有 items,不受此规则影响。取消按 `matching_id` 圈定名下 ready 未建单行退役(出生行 `run_id=None`,按 run_id 圈行恒不命中)。
|
||||
- **D17 圈档互斥**:一条档记录一生只生成一次 items 绑定——匹配创建圈档排除「已被有效 items 占用」的档记录(存在所属匹配未取消、行未被失效隔离的 item 引用即占用)。取消匹配(items→cancelled)释放占用,记录可被后续匹配重圈;人工关闭/成功终态不释放(前者=业务裁定不拨,后者=档级封存)。【ADR 0007】提交新匹配时,同一调拨类型、同一组来源、日期范围被新范围整个盖住、且还没有任何 ERP 单据的旧匹配自动取消后再圈档;盖不住或已在写 ERP 的旧匹配保持有效,货留在原匹配里,清单不列举编号。没有挂上匹配的明细不占用。重查只对账本匹配自有 items,不受此规则影响。取消按 `matching_id` 圈定名下 ready 未建单行退役(出生行 `run_id=None`,按 run_id 圈行恒不命中)。
|
||||
|
||||
### 11.7 首页待办看板「待匹配」桶(D16)
|
||||
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# 制程品质异常预警需求说明
|
||||
|
||||
> **版本**:V1.0
|
||||
> **更新日期**:2026-10-23
|
||||
> **状态**:规则已整理,尚未实现。OA 表、字段和 OA 邮件发送方式见后续设计文档。第 9 节三项仍待确认。
|
||||
> **适用范围**:OA 制程品质异常通知单的滚动统计,以及按料号 + 不良类别向品质担当和升级对象发送 OA 邮件
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
制程品质异常通知单已经在 OA 中流转。同一料号、同一不良类别在近一年内反复出现时,需要按固定节奏提醒品质担当,并在当月再次发生时按次数升级到品质、生产经副理、COO 和老板。
|
||||
|
||||
本需求只定义统计、升级和推送规则。不改 OA 流程本身,也不回写异常单。
|
||||
|
||||
## 2. 范围
|
||||
|
||||
### 2.1 本期已确认
|
||||
|
||||
- 统计键、计次日期、纳入状态、近一年窗口、当月窗口。
|
||||
- 品质担当周报与三档升级的收件人、抄送、不补发和同月不重复。
|
||||
- 通知渠道是 OA 邮件。按收件人汇总,不逐单发信。
|
||||
- 品质担当、品质、生产经副理、COO、老板五个岗位在界面配置。代码和配置文件不写死姓名或账号。品质担当与升级档里的「品质」是两个配置项。
|
||||
|
||||
### 2.2 本期不做
|
||||
|
||||
- 不接 Dify 对话。
|
||||
- 不回写 OA 异常单,不改流程状态。
|
||||
- 不撤回已发出的邮件。
|
||||
- 不为已过去的自然月补发升级信。
|
||||
|
||||
OA 流程表、workflow、料号、不良类别、申请日期的字段名,以及 OA 邮件怎么发,写在后续设计文档,不在本需求里展开。
|
||||
|
||||
## 3. 统计对象
|
||||
|
||||
数据源是 OA「制程品质异常通知单」。一笔计入统计的单据同时满足:
|
||||
|
||||
- 流程处于归档或在途。
|
||||
- 流程不是废弃,也不是撤销。
|
||||
|
||||
不按会签判定结果再过滤。料号按单据原值统计,不去斜杠、不截断、不与其他料号合并。不良项目、机种不参与合并。
|
||||
|
||||
统计键是 **料号 + 不良类别**。近一年和当月都用 **申请日期** 判断落在哪个区间。
|
||||
|
||||
## 4. 两个计数
|
||||
|
||||
两个计数分开。近一年决定要不要预警,当月笔数决定升级给谁。
|
||||
|
||||
### 4.1 近一年
|
||||
|
||||
申请日期落在 **扫描日减 1 年(含)到扫描日前 1 天(含)**。申请日期等于扫描日的单据不计入近一年。
|
||||
|
||||
扫描日 2026-10-23 时,区间是 2025-10-23 至 2026-10-22,两端都含。扫描日为闰年 2 月 29 日时,起始日取前一年 2 月 28 日。
|
||||
|
||||
同一键在这个区间内的合格单据笔数 ≥ 3,才进入预警。
|
||||
|
||||
### 4.2 当月
|
||||
|
||||
按申请日期所在自然月计。该月 1 日到月末都算,含扫描日当天。10 月就是 10 月 1 日到 10 月 31 日。
|
||||
|
||||
申请日期为扫描日当天的单据计入当月,次日才进入近一年。当月笔数只决定升级档,不能单独把近一年不足 3 次的键送进预警。
|
||||
|
||||
例:8 月已有 3 笔,10 月 1 日 1 笔,10 月 23 日又 1 笔。10 月 23 日扫描时,近一年已 ≥ 3(不含当天这一笔),当月是第 2 次,走 COO。
|
||||
|
||||
## 5. 升级与收件人
|
||||
|
||||
升级不补发跳过的档。
|
||||
|
||||
- 近一年这次刚到 3,但这笔已是当月第 2 笔时,只走 COO,不补「当月首次」。
|
||||
- 两次扫描之间当月笔数从 1 直接到 3 及以上时,只走老板档,不补首次和第二次。
|
||||
- 已过去的自然月不补发。
|
||||
|
||||
同一键、同一自然月,只在当月笔数进入更高档的那一周发一次升级信。之后几周停在同一档不再发。下个自然月从 0 重新计。近一年仍 ≥ 3 时,新月份的第一笔再走首次档。
|
||||
|
||||
| 条件 | 主送 | 抄送 |
|
||||
| --- | --- | --- |
|
||||
| 近一年 ≥ 3,且当月 1 笔,本月未发过该档 | 品质、生产经副理 | 无 |
|
||||
| 近一年 ≥ 3,且当月 2 笔,本月未发过该档 | COO | 无 |
|
||||
| 近一年 ≥ 3,且当月 ≥ 3 笔,本月未发过该档 | 老板 | COO、品质、生产经副理 |
|
||||
|
||||
当月 0 笔时不发升级信。品质担当周报不看当月笔数,见第 6 节。
|
||||
|
||||
五个岗位的具体人员尚未指定,见第 9 节。上线前必须能在界面配置,不能写死在代码或环境文件里。
|
||||
|
||||
## 6. 推送
|
||||
|
||||
渠道是 OA 邮件。每周扫描一次,按收件人汇总成一封,不逐单刷屏。同一周可以同时有周报和升级信:周报里有这个料号,升级信再发给该档收件人。
|
||||
|
||||
### 6.1 品质担当周报
|
||||
|
||||
每周一封。列出当前近一年仍 ≥ 3 的全部料号 + 不良类别。条件一直成立就每周都发,不因上周已发过而跳过。
|
||||
|
||||
### 6.2 升级信
|
||||
|
||||
只发给第 5 节当前档的主送和抄送。同一键、同一自然月、同一档只发一次。
|
||||
|
||||
## 7. 建议默认
|
||||
|
||||
以下四项先按这个写,确认前可以改:
|
||||
|
||||
- 入口做成内置 Chat Agent,不接 Dify。默认页是 Dashboard,其余页签为异常清单、发送记录、收件人配置。管理员可手动扫描。形态对齐设备验收预警。可点击原型见 [process-quality-alert-prototype.html](process-quality-alert-prototype.html)。本期只冻结规则,不在本文件展开页面。
|
||||
- 发送时刻可配置,初始为每周五 18:00,与合同付款预警、设备验收预警一致。
|
||||
- 上线第一周只发品质担当全量周报,不为已经处在当月第 2、第 3 档的历史组合补发升级。
|
||||
- 邮件明细至少包含:单号、申请日期、机种、料号、不良类别、不良项目、不良发生部、近一年次数、当月次数。
|
||||
|
||||
## 8. 留给设计文档
|
||||
|
||||
- OA 流程表、workflow、料号、不良类别、申请日期等字段名,以及怎么接入制程品质异常通知单。
|
||||
- OA 邮件的发送方式。本需求只定渠道是 OA 邮件。
|
||||
|
||||
## 9. 待确认
|
||||
|
||||
确认前,下面三项不算冻结:
|
||||
|
||||
- 一单多行、每行不良类别不同时,是否按行各计 1 次。
|
||||
- 不良类别为空的行是否排除。
|
||||
- 品质担当、品质、生产经副理、COO、老板五个岗位的具体人员。
|
||||
|
||||
## 10. 验收标准
|
||||
|
||||
| 编号 | 条件 | 期望 |
|
||||
| --- | --- | --- |
|
||||
| AC-01 | 扫描日 2026-10-23 | 近一年只计申请日期 2025-10-23 至 2026-10-22。申请日期为 2026-10-23 的单据只计入 10 月,不计入近一年 |
|
||||
| AC-02 | 同一料号 + 不良类别在近一年内不足 3 笔 | 不进周报,不发升级信 |
|
||||
| AC-03 | 近一年 ≥ 3,当月 0 笔 | 只出现在品质担当周报 |
|
||||
| AC-04 | 近一年 ≥ 3,当月第 1 / 2 / ≥3 笔,且本月该档未发过 | 分别主送品质+生产经副理、COO、老板。老板档抄送 COO、品质、生产经副理 |
|
||||
| AC-05 | 8 月已有 3 笔,10 月 1 日 1 笔,10 月 23 日再 1 笔,扫描日为 10 月 23 日 | 近一年 ≥ 3,当月第 2 次,主送 COO,不补首次档 |
|
||||
| AC-06 | 同一次扫描中当月笔数从 1 跨到 ≥ 3 | 只发老板档,不补首次和第二次 |
|
||||
| AC-07 | 同一档已在本月发过,后续周当月笔数没有进入更高档 | 品质担当仍收周报;升级对象不再收同一档 |
|
||||
| AC-08 | 单据为废弃或撤销 | 不计入近一年,也不计入当月 |
|
||||
| AC-09 | 单据为归档或在途 | 按申请日期计入对应区间 |
|
||||
| AC-10 | 料号原文带空格或符号 | 按原值与不良类别组成统计键,不另做清洗 |
|
||||
@@ -0,0 +1,743 @@
|
||||
<!doctype html>
|
||||
<!--
|
||||
docs/features/process-quality-alert/process-quality-alert-prototype.html
|
||||
用途:制程品质异常预警的可点击评审原型,用样例数据演示近一年窗口、当月升级和 OA 邮件汇总。
|
||||
依赖:浏览器原生 HTML/CSS/JavaScript,无需构建。
|
||||
逻辑:与 demand.md 对齐;不接 OA、不发邮件。默认打开 Dashboard。
|
||||
假设:一单一行计 1 次;样例不含空不良类别。五个岗位人员仍待确认,收件人页改称呼只改写信封。
|
||||
-->
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||
<title>制程品质异常预警 · 原型</title>
|
||||
<style>
|
||||
:root { --ink:#142033; --muted:#64748b; --line:#dce4ef; --bg:#f4f7fb; --nav:#111c31; --brand:#2563eb; --soft:#eaf2ff; --green:#067647; --amber:#b54708; --red:#b42318; }
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; background:var(--bg); color:var(--ink); font:14px/1.5 "Segoe UI","Microsoft YaHei",sans-serif; }
|
||||
button,select,input { font:inherit; }
|
||||
button { cursor:pointer; }
|
||||
.top { display:flex; justify-content:space-between; gap:16px; align-items:center; padding:12px 24px; background:var(--nav); color:#fff; }
|
||||
.top small { color:#aac0db; margin-left:8px; }
|
||||
.tabs { display:flex; gap:5px; flex-wrap:wrap; }
|
||||
.tabs button { border:0; border-radius:7px; padding:7px 11px; color:#c5d3e6; background:transparent; font-weight:700; font-size:12px; }
|
||||
.tabs button.active { color:#fff; background:var(--brand); }
|
||||
main { width:min(1180px,calc(100% - 32px)); margin:auto; padding:22px 0 48px; }
|
||||
.view { display:none; }
|
||||
.view.active { display:block; }
|
||||
.note { margin:0 0 14px; padding:10px 12px; border:1px solid #c9dcfb; border-radius:10px; background:#f3f8ff; color:#334155; font-size:12px; }
|
||||
.hero { display:flex; justify-content:space-between; gap:16px; align-items:flex-start; margin-bottom:14px; }
|
||||
.hero h1 { margin:0; font-size:22px; }
|
||||
.hero p { margin:4px 0 0; color:var(--muted); }
|
||||
.windows { display:flex; flex-wrap:wrap; gap:8px; margin-top:10px; }
|
||||
.windows span { padding:4px 8px; border-radius:99px; background:#fff; border:1px solid var(--line); font-size:12px; font-weight:700; }
|
||||
.btn { border:1px solid var(--line); border-radius:8px; padding:8px 11px; background:#fff; font-size:12px; font-weight:700; }
|
||||
.btn.primary { border-color:var(--brand); color:#fff; background:var(--brand); }
|
||||
.kpis { display:grid; grid-template-columns:repeat(5,minmax(0,1fr)); gap:12px; margin-bottom:14px; }
|
||||
.kpis button { text-align:left; border:1px solid var(--line); border-radius:12px; background:#fff; padding:14px 16px; }
|
||||
.kpis button:hover,.kpis button.active { border-color:#93c5fd; background:#f8fbff; }
|
||||
.kpis b { display:block; font-size:26px; }
|
||||
.kpis span { color:var(--muted); font-size:12px; }
|
||||
.card { border:1px solid var(--line); border-radius:12px; background:#fff; overflow:hidden; }
|
||||
.split { display:grid; grid-template-columns:1.15fr .85fr; gap:14px; margin-bottom:14px; }
|
||||
.hd { display:flex; justify-content:space-between; gap:12px; align-items:flex-start; padding:14px 16px 0; }
|
||||
.hd h2 { margin:0; font-size:15px; }
|
||||
.bd { padding:14px 16px 16px; }
|
||||
.bar { display:grid; grid-template-columns:132px 1fr 28px; gap:8px; align-items:center; margin:8px 0; font-size:12px; }
|
||||
.bar i { display:block; height:10px; border-radius:99px; background:#dbeafe; }
|
||||
.bar i span { display:block; height:100%; border-radius:99px; background:#2563eb; }
|
||||
.bar .amber span { background:#d97706; }
|
||||
.bar .red span { background:#dc2626; }
|
||||
.bar .green span { background:#059669; }
|
||||
.mails { display:grid; gap:8px; }
|
||||
.mail-row { display:flex; justify-content:space-between; gap:8px; padding:8px 10px; border:1px solid var(--line); border-radius:10px; font-size:12px; }
|
||||
.mail-row b { font-size:16px; }
|
||||
.filters { display:flex; flex-wrap:wrap; gap:8px; padding:12px; }
|
||||
.filters button { border:1px solid var(--line); border-radius:99px; padding:5px 10px; background:#fff; font-size:12px; font-weight:700; color:#475569; }
|
||||
.filters button.active { border-color:#bfdbfe; color:#1d4ed8; background:var(--soft); }
|
||||
table { width:100%; border-collapse:collapse; font-size:12px; }
|
||||
th,td { padding:10px 8px; border-bottom:1px solid var(--line); text-align:left; vertical-align:top; }
|
||||
th { color:var(--muted); background:#f8fbff; font-weight:700; }
|
||||
tr.clickable { cursor:pointer; }
|
||||
tr.clickable:hover,tr.selected { background:#f3f7ff; }
|
||||
.badge { display:inline-flex; padding:2px 8px; border-radius:99px; font-size:11px; font-weight:800; }
|
||||
.blue { color:#175cd3; background:var(--soft); }
|
||||
.green { color:var(--green); background:#eafaf1; }
|
||||
.amber { color:var(--amber); background:#fff7e6; }
|
||||
.red { color:var(--red); background:#fff0ef; }
|
||||
.gray { color:#475569; background:#edf1f6; }
|
||||
.muted { color:var(--muted); }
|
||||
.two { display:grid; grid-template-columns:280px 1fr; gap:14px; }
|
||||
.person { display:flex; flex-direction:column; gap:8px; }
|
||||
.person button { border:1px solid var(--line); border-radius:8px; padding:8px 10px; background:#fff; font-size:12px; text-align:left; font-weight:700; }
|
||||
.person button.active { border-color:#93c5fd; background:var(--soft); }
|
||||
.letter { margin-bottom:12px; padding:14px; border:1px solid var(--line); border-radius:12px; background:#fff; }
|
||||
.letter h3 { margin:0 0 8px; font-size:15px; }
|
||||
.kv { display:grid; grid-template-columns:72px 1fr; gap:6px; margin-bottom:8px; font-size:12px; }
|
||||
.kv b { color:var(--muted); font-weight:700; }
|
||||
.toast { position:fixed; right:16px; bottom:16px; padding:10px 12px; border-radius:8px; color:#fff; background:#142036; opacity:0; transition:.2s; }
|
||||
.toast.show { opacity:1; }
|
||||
.people-grid { display:grid; grid-template-columns:minmax(0,1fr) minmax(0,1fr); gap:14px; align-items:start; }
|
||||
#v-people .prow { display:grid; grid-template-columns:minmax(0,1fr) 168px; gap:12px; align-items:center; padding:12px 16px; border-top:1px solid var(--line); }
|
||||
#v-people .prow b { display:block; font-size:13px; }
|
||||
#v-people .prow span { color:var(--muted); font-size:12px; }
|
||||
#v-people select { width:100%; height:36px; padding:0 8px; border:1px solid #d7dee8; border-radius:8px; background:#fff; color:var(--ink); font-weight:650; }
|
||||
#v-people select:focus { outline:2px solid #bfdbfe; border-color:#2563eb; }
|
||||
#v-people .parts { margin:8px 0 0; padding:0; list-style:none; }
|
||||
#v-people .parts li { padding:8px 0; border-top:1px solid var(--line); font-size:12px; }
|
||||
@media (max-width:980px) {
|
||||
.kpis { grid-template-columns:1fr 1fr; }
|
||||
.split,.two,.hero,.top,.people-grid { display:block; }
|
||||
.people-grid > article + article { margin-top:14px; }
|
||||
.tabs { margin-top:8px; }
|
||||
.split > article + article,.two > article + article { margin-top:14px; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header class="top">
|
||||
<div><b>制程品质异常预警</b><small>原型 · 样例数据 · 不接 OA</small></div>
|
||||
<nav class="tabs" id="tabs">
|
||||
<button class="active" data-v="dash">Dashboard</button>
|
||||
<button data-v="list">异常清单</button>
|
||||
<button data-v="mail">发送预览</button>
|
||||
<button data-v="people">收件人</button>
|
||||
</nav>
|
||||
</header>
|
||||
<main>
|
||||
<p class="note">原型假设:一单一行计 1 次;样例不含空不良类别。五个岗位的具体人员仍待确认,这里的姓名只影响预览称呼。扫描日固定为 2026-10-23。近一年计申请日期 2025-10-23 至 2026-10-22。当月计 2026-10-01 至 2026-10-31,含当天。</p>
|
||||
|
||||
<section class="view active" id="v-dash">
|
||||
<div class="hero">
|
||||
<div>
|
||||
<h1>Dashboard</h1>
|
||||
<p>本周五 18:00 将发出的周报和升级信。近一年不足 3 次的键不出现在这里。</p>
|
||||
<div class="windows">
|
||||
<span>扫描日 2026-10-23</span>
|
||||
<span>近一年 2025-10-23 ~ 2026-10-22</span>
|
||||
<span>当月 2026-10-01 ~ 2026-10-31</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="kpis" id="kpis"></div>
|
||||
<div class="split">
|
||||
<article class="card">
|
||||
<div class="hd"><h2>档位分布</h2></div>
|
||||
<div class="bd" id="bars"></div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="hd"><h2>本周收件人</h2><p class="muted">含抄送。同一人收到多封时分开计数。</p></div>
|
||||
<div class="bd mails" id="mailCounts"></div>
|
||||
</article>
|
||||
</div>
|
||||
<article class="card">
|
||||
<div class="hd"><h2>近一年仍 ≥ 3</h2><p class="muted">按近一年次数从高到低。点一行看单据。</p></div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>料号</th><th>不良类别</th><th>机种</th><th>近一年</th><th>当月</th><th>本周动作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="watchRows"></tbody>
|
||||
</table>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="view" id="v-list">
|
||||
<div class="hero">
|
||||
<div>
|
||||
<h1>异常清单</h1>
|
||||
<p>废弃、撤销和近一年不足 3 次的样例留在这里,标成不预警。计入标记按申请日期和流程状态计算。</p>
|
||||
</div>
|
||||
</div>
|
||||
<article class="card">
|
||||
<div class="filters" id="filters"></div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>料号</th><th>不良类别</th><th>近一年</th><th>当月</th><th>状态</th><th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="keyRows"></tbody>
|
||||
</table>
|
||||
</article>
|
||||
<article class="card" style="margin-top:14px">
|
||||
<div class="hd"><h2 id="detailTitle">单据明细</h2></div>
|
||||
<div class="bd" id="detailNote"></div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>单号</th><th>申请日期</th><th>机种</th><th>料号</th><th>不良类别</th><th>不良项目</th><th>不良发生部</th><th>流程</th><th>计入</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="formRows"></tbody>
|
||||
</table>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="view" id="v-mail">
|
||||
<div class="hero">
|
||||
<div>
|
||||
<h1>发送预览</h1>
|
||||
<p>本周五 18:00 的 OA 邮件。品质担当收全量周报。升级信只含本周新跨入的档,不补发跳过的档。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="two">
|
||||
<article class="card"><div class="bd"><div class="person" id="recipients"></div></div></article>
|
||||
<div id="letters"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="view" id="v-people">
|
||||
<div class="hero">
|
||||
<div>
|
||||
<h1>收件人</h1>
|
||||
<p>五个岗位分开配置。改称呼会立刻出现在右侧预览里,不进入正式名单。</p>
|
||||
</div>
|
||||
<button class="btn primary" id="savePeople" type="button">保存称呼</button>
|
||||
</div>
|
||||
<div class="people-grid">
|
||||
<article class="card">
|
||||
<div class="hd"><div><h2>岗位</h2><p class="muted">品质担当和升级档里的品质是两个人。</p></div></div>
|
||||
<div id="slipBands"></div>
|
||||
</article>
|
||||
<article class="card">
|
||||
<div class="hd"><div><h2>本周预览</h2><p class="muted" id="slipMeta"></p></div></div>
|
||||
<div class="filters" id="slipPicks"></div>
|
||||
<div class="bd" id="slipLetter"></div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<div class="toast" id="toast"></div>
|
||||
<script>
|
||||
/**
|
||||
* 用样例异常单演示近一年窗口、当月升级和按收件人汇总的 OA 邮件。
|
||||
* 核心逻辑:近一年不含扫描日;当月含扫描日;废弃和撤销不计入;跳过的档不补发。
|
||||
*/
|
||||
(() => {
|
||||
const SCAN = '2026-10-23';
|
||||
const YEAR_FROM = '2025-10-23';
|
||||
const YEAR_TO = '2026-10-22';
|
||||
const MONTH_FROM = '2026-10-01';
|
||||
const MONTH_TO = '2026-10-31';
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const ROLE_FIELDS = [
|
||||
['owner', '品质担当'],
|
||||
['quality', '品质'],
|
||||
['prod', '生产经副理'],
|
||||
['coo', 'COO'],
|
||||
['boss', '老板']
|
||||
];
|
||||
const NAME_OPTIONS = ['待确认', '样例·甲', '样例·乙'];
|
||||
|
||||
let view = 'dash';
|
||||
let filter = 'watch';
|
||||
let selected = 'A';
|
||||
let mailPerson = 'owner';
|
||||
let slipId = 'weekly';
|
||||
const people = { owner:'待确认', quality:'待确认', prod:'待确认', coo:'待确认', boss:'待确认' };
|
||||
|
||||
const keys = [
|
||||
{
|
||||
id:'A', model:'AR1.2', part:'D4-A12HOX0000040', defect:'外观不良', sent:[],
|
||||
note:'当月 0 笔。近一年仍 ≥ 3,只进品质担当周报。',
|
||||
forms:[
|
||||
{ no:'QA-2025-0901', date:'2025-09-01', model:'AR1.2', item:'外观划伤', dept:'生二包装', status:'归档' },
|
||||
{ no:'QA-2026-0804', date:'2026-08-04', model:'AR1.2', item:'包装破损', dept:'生二包装', status:'归档' },
|
||||
{ no:'QA-2026-0818', date:'2026-08-18', model:'AR1.2', item:'外观划伤', dept:'生二包装', status:'在途' },
|
||||
{ no:'QA-2026-0906', date:'2026-09-06', model:'AR1.2', item:'包装方式', dept:'生二包装', status:'归档' },
|
||||
{ no:'QA-2026-0920', date:'2026-09-20', model:'AR1.2', item:'外观不良', dept:'生二包装', status:'归档' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id:'B', model:'CE001', part:'I6-CE0010321', defect:'尺寸不良', sent:[],
|
||||
note:'当月第 1 笔,本月尚未发过该档。本周主送品质和生产经副理。',
|
||||
forms:[
|
||||
{ no:'QA-2025-1023', date:'2025-10-23', model:'CE001', item:'尺寸超差', dept:'生二下料', status:'归档' },
|
||||
{ no:'QA-2026-0114', date:'2026-01-14', model:'CE001', item:'尺寸超差', dept:'生二下料', status:'归档' },
|
||||
{ no:'QA-2026-0402', date:'2026-04-02', model:'CE001', item:'孔径超差', dept:'生二下料', status:'在途' },
|
||||
{ no:'QA-2026-0719', date:'2026-07-19', model:'CE001', item:'尺寸超差', dept:'生二下料', status:'归档' },
|
||||
{ no:'QA-2026-1008', date:'2026-10-08', model:'CE001', item:'尺寸超差', dept:'生二下料', status:'归档' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id:'C', model:'RT05', part:'I9-RT05001106/107', defect:'错漏混', sent:[],
|
||||
note:'8 月 3 笔,10 月 1 日 1 笔,10 月 23 日又 1 笔。近一年不含当天仍 ≥ 3,当月是第 2 次,本周只主送 COO,不补首次档。料号按原值,不去斜杠。',
|
||||
forms:[
|
||||
{ no:'QA-2026-0805', date:'2026-08-05', model:'RT05', item:'漏装', dept:'生二焊接', status:'归档' },
|
||||
{ no:'QA-2026-0812', date:'2026-08-12', model:'RT05', item:'错料', dept:'生二焊接', status:'在途' },
|
||||
{ no:'QA-2026-0820', date:'2026-08-20', model:'RT05', item:'漏焊', dept:'生二焊接', status:'归档' },
|
||||
{ no:'QA-2026-1001', date:'2026-10-01', model:'RT05', item:'错料', dept:'生二焊接', status:'归档' },
|
||||
{ no:'QA-2026-1023', date:'2026-10-23', model:'RT05', item:'漏装', dept:'生二焊接', status:'在途' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id:'D', model:'AR1.1', part:'B3-AR100253', defect:'实物与图不符', sent:[],
|
||||
note:'上次扫描时当月还是 0 笔。本周一次看到 10 月 20、21、22 日三笔,只走老板档,不补首次和第二次。',
|
||||
forms:[
|
||||
{ no:'QA-2026-0302', date:'2026-03-02', model:'AR1.1', item:'实物不符', dept:'生一冲压', status:'归档' },
|
||||
{ no:'QA-2026-0411', date:'2026-04-11', model:'AR1.1', item:'图物不符', dept:'生一冲压', status:'归档' },
|
||||
{ no:'QA-2026-0619', date:'2026-06-19', model:'AR1.1', item:'实物不符', dept:'生一冲压', status:'在途' },
|
||||
{ no:'QA-2026-1020', date:'2026-10-20', model:'AR1.1', item:'实物不符', dept:'生一冲压', status:'归档' },
|
||||
{ no:'QA-2026-1021', date:'2026-10-21', model:'AR1.1', item:'图物不符', dept:'生一冲压', status:'归档' },
|
||||
{ no:'QA-2026-1022', date:'2026-10-22', model:'AR1.1', item:'实物不符', dept:'生一冲压', status:'在途' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id:'E', model:'AR1.2', part:'D4-AR1200100', defect:'尺寸不良', sent:['first'],
|
||||
note:'10 月 10 日已发过当月首次。本周当月仍是 1 笔,周报继续收,升级信不再发。',
|
||||
forms:[
|
||||
{ no:'QA-2026-0702', date:'2026-07-02', model:'AR1.2', item:'尺寸超差', dept:'生二折弯', status:'归档' },
|
||||
{ no:'QA-2026-0814', date:'2026-08-14', model:'AR1.2', item:'尺寸超差', dept:'生二折弯', status:'在途' },
|
||||
{ no:'QA-2026-1006', date:'2026-10-06', model:'AR1.2', item:'孔径超差', dept:'生二折弯', status:'归档' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id:'F', model:'CE001', part:'I6-CE0010362', defect:'尺寸不良', sent:[],
|
||||
note:'归档和在途都计入,但近一年只有 2 笔,不预警。',
|
||||
forms:[
|
||||
{ no:'QA-2026-0912', date:'2026-09-12', model:'CE001', item:'尺寸超差', dept:'生二折弯', status:'归档' },
|
||||
{ no:'QA-2026-1015', date:'2026-10-15', model:'CE001', item:'尺寸超差', dept:'生二折弯', status:'在途' }
|
||||
]
|
||||
},
|
||||
{
|
||||
id:'G', model:'AR1.2', part:'D4-AR1200098', defect:'错漏混', sent:[],
|
||||
note:'废弃和撤销不计入。剩下 2 笔有效单,近一年不足 3 次,不预警。',
|
||||
forms:[
|
||||
{ no:'QA-2026-0601', date:'2026-06-01', model:'AR1.2', item:'漏孔', dept:'生二包装', status:'归档' },
|
||||
{ no:'QA-2026-0708', date:'2026-07-08', model:'AR1.2', item:'混料', dept:'生二包装', status:'在途' },
|
||||
{ no:'QA-2026-0819', date:'2026-08-19', model:'AR1.2', item:'漏孔', dept:'生二包装', status:'废弃' },
|
||||
{ no:'QA-2026-0903', date:'2026-09-03', model:'AR1.2', item:'错料', dept:'生二包装', status:'撤销' }
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
/**
|
||||
* 判断申请日期是否落在近一年窗口。
|
||||
* 扫描日当天不算。两端日期都含。
|
||||
* @param {string} date - 申请日期,YYYY-MM-DD
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function inYear(date) {
|
||||
return date >= YEAR_FROM && date <= YEAR_TO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断申请日期是否落在扫描日所在自然月。
|
||||
* 该月 1 日到月末都算,含扫描日当天。
|
||||
* @param {string} date - 申请日期,YYYY-MM-DD
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function inMonth(date) {
|
||||
return date >= MONTH_FROM && date <= MONTH_TO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归档和在途计入。废弃、撤销不计入。
|
||||
* @param {{status:string}} form - 样例单据
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function countable(form) {
|
||||
return form.status === '归档' || form.status === '在途';
|
||||
}
|
||||
|
||||
/**
|
||||
* 近一年有效笔数,不含扫描日当天。
|
||||
* @param {{forms:Array}} key - 料号 + 不良类别
|
||||
* @returns {number}
|
||||
*/
|
||||
function yearCount(key) {
|
||||
return key.forms.filter((form) => countable(form) && inYear(form.date)).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当月有效笔数,含扫描日当天。
|
||||
* @param {{forms:Array}} key - 料号 + 不良类别
|
||||
* @returns {number}
|
||||
*/
|
||||
function monthCount(key) {
|
||||
return key.forms.filter((form) => countable(form) && inMonth(form.date)).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前所处档位。近一年不足 3 次为 none,当月 0 笔为 weekly。
|
||||
* @param {{forms:Array}} key - 料号 + 不良类别
|
||||
* @returns {'none'|'weekly'|'first'|'second'|'third'}
|
||||
*/
|
||||
function standingTier(key) {
|
||||
if (yearCount(key) < 3) return 'none';
|
||||
const month = monthCount(key);
|
||||
if (month <= 0) return 'weekly';
|
||||
if (month === 1) return 'first';
|
||||
if (month === 2) return 'second';
|
||||
return 'third';
|
||||
}
|
||||
|
||||
/**
|
||||
* 本周要新发的升级档。已发过的同一档不再发,也不补发更低档。
|
||||
* @param {{forms:Array, sent:string[]}} key - 料号 + 不良类别
|
||||
* @returns {'first'|'second'|'third'|null}
|
||||
*/
|
||||
function upgradeTier(key) {
|
||||
const tier = standingTier(key);
|
||||
if (tier === 'none' || tier === 'weekly') return null;
|
||||
if (key.sent.includes(tier)) return null;
|
||||
return tier;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清单和 Dashboard 上的本周动作文案。
|
||||
* @param {{forms:Array, sent:string[]}} key - 料号 + 不良类别
|
||||
* @returns {string}
|
||||
*/
|
||||
function actionLabel(key) {
|
||||
const upgrade = upgradeTier(key);
|
||||
if (standingTier(key) === 'none') return '不预警';
|
||||
if (upgrade === 'first') return '周报 + 首次升级';
|
||||
if (upgrade === 'second') return '周报 + 主送 COO';
|
||||
if (upgrade === 'third') return '周报 + 主送老板';
|
||||
if (standingTier(key) === 'weekly') return '只发周报';
|
||||
return '周报照发。当月这一档已经发过,这周不再发升级信';
|
||||
}
|
||||
|
||||
/**
|
||||
* 把本周动作写成徽章。
|
||||
* @param {{forms:Array, sent:string[]}} key - 料号 + 不良类别
|
||||
* @returns {string}
|
||||
*/
|
||||
function actionBadge(key) {
|
||||
const upgrade = upgradeTier(key);
|
||||
if (standingTier(key) === 'none') return '<span class="badge gray">不预警</span>';
|
||||
if (upgrade === 'first') return '<span class="badge blue">首次升级</span>';
|
||||
if (upgrade === 'second') return '<span class="badge amber">第二次 · COO</span>';
|
||||
if (upgrade === 'third') return '<span class="badge red">第三次及以上 · 老板</span>';
|
||||
if (standingTier(key) === 'weekly') return '<span class="badge green">只发周报</span>';
|
||||
return '<span class="badge gray">升级已发过</span>';
|
||||
}
|
||||
|
||||
/**
|
||||
* 单笔单据的计入说明。废弃和撤销优先于日期窗口。
|
||||
* @param {{date:string, status:string}} form - 样例单据
|
||||
* @returns {string}
|
||||
*/
|
||||
function countBadge(form) {
|
||||
if (!countable(form)) return '<span class="badge red">不计入(' + form.status + ')</span>';
|
||||
const year = inYear(form.date);
|
||||
const month = inMonth(form.date);
|
||||
if (year && month) return '<span class="badge blue">近一年 + 当月</span>';
|
||||
if (year) return '<span class="badge green">近一年</span>';
|
||||
if (month) return '<span class="badge amber">只算当月</span>';
|
||||
return '<span class="badge gray">两者都不算</span>';
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前筛选留下的统计键。
|
||||
* @returns {Array}
|
||||
*/
|
||||
function visibleKeys() {
|
||||
return keys.filter((key) => {
|
||||
const tier = standingTier(key);
|
||||
const upgrade = upgradeTier(key);
|
||||
if (filter === 'watch') return yearCount(key) >= 3;
|
||||
if (filter === 'weekly') return tier === 'weekly';
|
||||
if (filter === 'first') return upgrade === 'first';
|
||||
if (filter === 'second') return upgrade === 'second';
|
||||
if (filter === 'third') return upgrade === 'third';
|
||||
if (filter === 'skip') return tier === 'none';
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 岗位显示名。待确认时带上岗位,避免预览里五个人都叫同一句话。
|
||||
* @param {'owner'|'quality'|'prod'|'coo'|'boss'} role - 岗位键
|
||||
* @returns {string}
|
||||
*/
|
||||
function personName(role) {
|
||||
const label = ROLE_FIELDS.find((item) => item[0] === role)[1];
|
||||
if (people[role] === '待确认') return label + '(待确认)';
|
||||
return people[role] + ' · ' + label;
|
||||
}
|
||||
|
||||
/**
|
||||
* 本周要发出的邮件。周报一封;每个新升级档一封,不把跳过的档补进去。
|
||||
* @returns {Array<{id:string, kind:string, to:string[], cc:string[], keys:Array}>}
|
||||
*/
|
||||
function letters() {
|
||||
const watch = keys.filter((key) => yearCount(key) >= 3)
|
||||
.sort((a, b) => yearCount(b) - yearCount(a) || a.part.localeCompare(b.part));
|
||||
const ofTier = (tier) => watch.filter((key) => upgradeTier(key) === tier);
|
||||
const batch = [];
|
||||
if (watch.length) {
|
||||
batch.push({ id:'weekly', kind:'周报', to:[personName('owner')], cc:[], keys:watch });
|
||||
}
|
||||
const first = ofTier('first');
|
||||
if (first.length) {
|
||||
batch.push({ id:'first', kind:'当月首次', to:[personName('quality'), personName('prod')], cc:[], keys:first });
|
||||
}
|
||||
const second = ofTier('second');
|
||||
if (second.length) {
|
||||
batch.push({ id:'second', kind:'当月第二次', to:[personName('coo')], cc:[], keys:second });
|
||||
}
|
||||
const third = ofTier('third');
|
||||
if (third.length) {
|
||||
batch.push({
|
||||
id:'third',
|
||||
kind:'当月第三次及以上',
|
||||
to:[personName('boss')],
|
||||
cc:[personName('coo'), personName('quality'), personName('prod')],
|
||||
keys:third
|
||||
});
|
||||
}
|
||||
return batch;
|
||||
}
|
||||
|
||||
/**
|
||||
* 某人作为主送或抄送会收到的邮件。
|
||||
* @param {string} name - personName 的结果
|
||||
* @returns {Array}
|
||||
*/
|
||||
function lettersFor(name) {
|
||||
return letters().filter((letter) => letter.to.includes(name) || letter.cc.includes(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换页签。从 Dashboard 点进清单时保留已选统计键。
|
||||
* @param {string} next - dash、list、mail、people
|
||||
*/
|
||||
function show(next) {
|
||||
view = next;
|
||||
document.querySelectorAll('.tabs button').forEach((button) => {
|
||||
button.classList.toggle('active', button.dataset.v === next);
|
||||
});
|
||||
document.querySelectorAll('.view').forEach((section) => {
|
||||
section.classList.toggle('active', section.id === 'v-' + next);
|
||||
});
|
||||
if (next === 'list') renderList();
|
||||
if (next === 'mail') renderMail();
|
||||
if (next === 'people') renderPeople();
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开某个统计键的单据明细。
|
||||
* @param {string} id - 样例键 id
|
||||
* @param {string} [nextFilter] - 清单筛选
|
||||
*/
|
||||
function openKey(id, nextFilter) {
|
||||
selected = id;
|
||||
if (nextFilter) filter = nextFilter;
|
||||
show('list');
|
||||
}
|
||||
|
||||
/**
|
||||
* 画 Dashboard 的指标、档位条、收件人封数和预警清单。
|
||||
*/
|
||||
function renderDash() {
|
||||
const watch = keys.filter((key) => yearCount(key) >= 3);
|
||||
const cards = [
|
||||
['watch', watch.length, '近一年仍 ≥ 3'],
|
||||
['weekly', watch.filter((key) => standingTier(key) === 'weekly').length, '本周只发周报(当月 0 笔)'],
|
||||
['first', watch.filter((key) => upgradeTier(key) === 'first').length, '本周首次升级'],
|
||||
['second', watch.filter((key) => upgradeTier(key) === 'second').length, '本周第二次(COO)'],
|
||||
['third', watch.filter((key) => upgradeTier(key) === 'third').length, '本周第三次及以上(老板)']
|
||||
];
|
||||
$('kpis').innerHTML = cards.map(([id, num, label]) => (
|
||||
'<button type="button" data-jump="' + id + '"><b>' + num + '</b><span>' + label + '</span></button>'
|
||||
)).join('');
|
||||
$('kpis').querySelectorAll('button').forEach((button) => {
|
||||
button.onclick = () => openKey(selected, button.dataset.jump === 'watch' ? 'watch' : button.dataset.jump);
|
||||
});
|
||||
|
||||
const buckets = [
|
||||
['只发周报', cards[1][1], 'green'],
|
||||
['本周首次', cards[2][1], ''],
|
||||
['本周第二次', cards[3][1], 'amber'],
|
||||
['本周第三次及以上', cards[4][1], 'red'],
|
||||
['升级已发过', watch.filter((key) => standingTier(key) !== 'weekly' && !upgradeTier(key)).length, 'green']
|
||||
];
|
||||
const max = Math.max(1, ...buckets.map((item) => item[1]));
|
||||
$('bars').innerHTML = buckets.map(([label, num, tone]) => (
|
||||
'<div class="bar"><span>' + label + '</span><i class="' + tone + '"><span style="width:' + (num / max * 100) + '%"></span></i><b>' + num + '</b></div>'
|
||||
)).join('');
|
||||
|
||||
const names = ['owner', 'quality', 'prod', 'coo', 'boss'].map(personName);
|
||||
$('mailCounts').innerHTML = names.map((name) => {
|
||||
const mine = lettersFor(name);
|
||||
return '<div class="mail-row"><span>' + name + '</span><b>' + mine.length + ' 封</b></div>';
|
||||
}).join('');
|
||||
|
||||
const rows = watch.slice().sort((a, b) => yearCount(b) - yearCount(a) || a.part.localeCompare(b.part));
|
||||
$('watchRows').innerHTML = rows.map((key) => (
|
||||
'<tr class="clickable" data-id="' + key.id + '"><td>' + key.part + '</td><td>' + key.defect + '</td><td>' + key.model + '</td><td>' + yearCount(key) + '</td><td>' + monthCount(key) + '</td><td>' + actionBadge(key) + '</td></tr>'
|
||||
)).join('');
|
||||
$('watchRows').querySelectorAll('tr').forEach((row) => {
|
||||
row.onclick = () => openKey(row.dataset.id, 'all');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 画异常清单和当前统计键的单据明细。
|
||||
*/
|
||||
function renderList() {
|
||||
const filters = [
|
||||
['all', '全部'],
|
||||
['watch', '近一年 ≥ 3'],
|
||||
['weekly', '只发周报'],
|
||||
['first', '本周首次'],
|
||||
['second', '本周第二次'],
|
||||
['third', '本周第三次及以上'],
|
||||
['skip', '不预警']
|
||||
];
|
||||
$('filters').innerHTML = filters.map(([id, label]) => (
|
||||
'<button type="button" data-f="' + id + '"' + (filter === id ? ' class="active"' : '') + '>' + label + '</button>'
|
||||
)).join('');
|
||||
$('filters').querySelectorAll('button').forEach((button) => {
|
||||
button.onclick = () => { filter = button.dataset.f; renderList(); };
|
||||
});
|
||||
|
||||
const rows = visibleKeys().sort((a, b) => yearCount(b) - yearCount(a) || a.part.localeCompare(b.part));
|
||||
if (!rows.some((key) => key.id === selected) && rows[0]) selected = rows[0].id;
|
||||
$('keyRows').innerHTML = rows.map((key) => (
|
||||
'<tr class="clickable' + (key.id === selected ? ' selected' : '') + '" data-id="' + key.id + '"><td>' + key.part + '</td><td>' + key.defect + '</td><td>' + yearCount(key) + '</td><td>' + monthCount(key) + '</td><td>' + actionBadge(key) + '</td><td>' + actionLabel(key) + '</td></tr>'
|
||||
)).join('') || '<tr><td colspan="6" class="muted">这个筛选下没有样例。</td></tr>';
|
||||
$('keyRows').querySelectorAll('tr[data-id]').forEach((row) => {
|
||||
row.onclick = () => { selected = row.dataset.id; renderList(); };
|
||||
});
|
||||
|
||||
const key = keys.find((item) => item.id === selected) || rows[0];
|
||||
if (!key) {
|
||||
$('detailTitle').textContent = '单据明细';
|
||||
$('detailNote').textContent = '';
|
||||
$('formRows').innerHTML = '';
|
||||
return;
|
||||
}
|
||||
$('detailTitle').textContent = key.part + ' · ' + key.defect;
|
||||
$('detailNote').innerHTML = '<p class="muted" style="margin:0">' + key.note + ' 近一年 ' + yearCount(key) + ' 笔,当月 ' + monthCount(key) + ' 笔。</p>';
|
||||
$('formRows').innerHTML = key.forms.map((form) => (
|
||||
'<tr><td>' + form.no + '</td><td>' + form.date + '</td><td>' + form.model + '</td><td>' + key.part + '</td><td>' + key.defect + '</td><td>' + form.item + '</td><td>' + form.dept + '</td><td>' + form.status + '</td><td>' + countBadge(form) + '</td></tr>'
|
||||
)).join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* 画某个收件人本周会收到的 OA 邮件。
|
||||
*/
|
||||
function renderMail() {
|
||||
const batch = letters();
|
||||
const peopleInBatch = [];
|
||||
batch.forEach((letter) => {
|
||||
letter.to.concat(letter.cc).forEach((name) => {
|
||||
if (!peopleInBatch.includes(name)) peopleInBatch.push(name);
|
||||
});
|
||||
});
|
||||
if (!peopleInBatch.includes(mailPerson) && !peopleInBatch.some((name) => name.startsWith(personName(mailPerson)))) {
|
||||
mailPerson = 'owner';
|
||||
}
|
||||
const activeName = personName(mailPerson);
|
||||
$('recipients').innerHTML = ROLE_FIELDS.map(([role]) => {
|
||||
const name = personName(role);
|
||||
const count = lettersFor(name).length;
|
||||
return '<button type="button" data-role="' + role + '"' + (mailPerson === role ? ' class="active"' : '') + '>' + name + '<br><span class="muted">' + count + ' 封</span></button>';
|
||||
}).join('');
|
||||
$('recipients').querySelectorAll('button').forEach((button) => {
|
||||
button.onclick = () => { mailPerson = button.dataset.role; renderMail(); };
|
||||
});
|
||||
|
||||
const mine = lettersFor(activeName);
|
||||
$('letters').innerHTML = mine.map((letter) => {
|
||||
const roleLine = letter.to.includes(activeName) ? '主送' : '抄送';
|
||||
const body = letter.keys.map((key) => (
|
||||
key.forms.filter((form) => countable(form) && (inYear(form.date) || inMonth(form.date))).map((form) => (
|
||||
'<tr><td>' + form.no + '</td><td>' + form.date + '</td><td>' + form.model + '</td><td>' + key.part + '</td><td>' + key.defect + '</td><td>' + form.item + '</td><td>' + form.dept + '</td><td>' + yearCount(key) + '</td><td>' + monthCount(key) + '</td></tr>'
|
||||
)).join('')
|
||||
)).join('');
|
||||
return '<article class="letter"><h3>' + letter.kind + '</h3><div class="kv"><b>发送</b><span>2026-10-23 18:00 · OA 邮件</span><b>你的身份</b><span>' + roleLine + '</span><b>主送</b><span>' + letter.to.join('、') + '</span><b>抄送</b><span>' + (letter.cc.length ? letter.cc.join('、') : '无') + '</span></div><table><thead><tr><th>单号</th><th>申请日期</th><th>机种</th><th>料号</th><th>不良类别</th><th>不良项目</th><th>不良发生部</th><th>近一年</th><th>当月</th></tr></thead><tbody>' + body + '</tbody></table></article>';
|
||||
}).join('') || '<article class="letter"><p class="muted">这位本周没有邮件。</p></article>';
|
||||
}
|
||||
|
||||
const SLIPS = [
|
||||
{ id:'weekly', title:'周报', to:['owner'], cc:[] },
|
||||
{ id:'first', title:'当月首次', to:['quality','prod'], cc:[] },
|
||||
{ id:'second', title:'当月第二次', to:['coo'], cc:[] },
|
||||
{ id:'third', title:'第三次及以上', to:['boss'], cc:['coo','quality','prod'] }
|
||||
];
|
||||
const ROLE_DUTY = {
|
||||
owner:'周报主送',
|
||||
quality:'首次主送,第三次抄送',
|
||||
prod:'首次主送,第三次抄送',
|
||||
coo:'第二次主送,第三次抄送',
|
||||
boss:'第三次主送'
|
||||
};
|
||||
|
||||
/**
|
||||
* 当前这封信要列出的料号。周报是近一年仍不少于 3 次的全部键,升级信只含本周新跨入的那一档。
|
||||
* @param {string} id - weekly、first、second、third
|
||||
* @returns {Array}
|
||||
*/
|
||||
function slipKeys(id) {
|
||||
const watch = keys.filter((key) => yearCount(key) >= 3);
|
||||
if (id === 'weekly') return watch.sort((a, b) => yearCount(b) - yearCount(a));
|
||||
return watch.filter((key) => upgradeTier(key) === id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 画出五个岗位和右侧这封信。每个岗位只出现一次,改称呼只改预览。
|
||||
*/
|
||||
function renderPeople() {
|
||||
$('slipBands').innerHTML = ROLE_FIELDS.map(([role, label]) => {
|
||||
const options = NAME_OPTIONS.map((name) => (
|
||||
'<option' + (people[role] === name ? ' selected' : '') + '>' + name + '</option>'
|
||||
)).join('');
|
||||
return '<div class="prow"><div><b>' + label + '</b><span>' + ROLE_DUTY[role] + '</span></div><select data-role="' + role + '" aria-label="' + label + '">' + options + '</select></div>';
|
||||
}).join('');
|
||||
$('slipBands').querySelectorAll('select').forEach((select) => {
|
||||
select.onchange = () => {
|
||||
people[select.dataset.role] = select.value;
|
||||
renderPeople();
|
||||
renderDash();
|
||||
renderMail();
|
||||
};
|
||||
});
|
||||
$('slipPicks').innerHTML = SLIPS.map((slip) => (
|
||||
'<button type="button" data-slip="' + slip.id + '"' + (slip.id === slipId ? ' class="active"' : '') + '>' + slip.title + '</button>'
|
||||
)).join('');
|
||||
$('slipPicks').querySelectorAll('button').forEach((button) => {
|
||||
button.onclick = () => { slipId = button.dataset.slip; renderPeople(); };
|
||||
});
|
||||
const slip = SLIPS.find((item) => item.id === slipId);
|
||||
const rows = slipKeys(slip.id);
|
||||
const to = slip.to.map(personName).join('、');
|
||||
const cc = slip.cc.length ? slip.cc.map(personName).join('、') : '无';
|
||||
const list = rows.map((key) => (
|
||||
'<li>' + key.part + ' · ' + key.defect + ' · 近一年 ' + yearCount(key) + ' · 当月 ' + monthCount(key) + '</li>'
|
||||
)).join('') || '<li>本周这封没有料号。</li>';
|
||||
$('slipMeta').textContent = '2026-10-23 18:00 · OA 邮件 · ' + rows.length + ' 个料号';
|
||||
$('slipLetter').innerHTML = '<div class="kv"><b>主送</b><span>' + to + '</span><b>抄送</b><span>' + cc + '</span></div><ul class="parts">' + list + '</ul>';
|
||||
}
|
||||
|
||||
/**
|
||||
* 短暂提示称呼已用于预览。
|
||||
* @param {string} text - 提示文案
|
||||
*/
|
||||
function toast(text) {
|
||||
const node = $('toast');
|
||||
node.textContent = text;
|
||||
node.classList.add('show');
|
||||
setTimeout(() => node.classList.remove('show'), 1600);
|
||||
}
|
||||
|
||||
document.querySelectorAll('.tabs button').forEach((button) => {
|
||||
button.onclick = () => show(button.dataset.v);
|
||||
});
|
||||
$('savePeople').onclick = () => toast('预览称呼已更新,未写入正式配置');
|
||||
|
||||
renderDash();
|
||||
renderList();
|
||||
renderMail();
|
||||
renderPeople();
|
||||
const openView = new URLSearchParams(location.search).get('view') || (location.hash || '').replace('#', '');
|
||||
if (['dash', 'list', 'mail', 'people'].includes(openView)) show(openView);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1858,21 +1858,16 @@ GET /api/admin/shipping-order-schema/published-contract
|
||||
|
||||
### 连接级受控上传参数(upload_config_json,连接例外)
|
||||
|
||||
发货 Excel 自动上传的页面参数作为 `ShippingRpaProfile.upload_config_json` 直接挂在既有“系统连接”上,一条连接只保存一份上传配置。**这是连接级受控上传参数的例外**:它只作用于货代上传,不向库存 RPA 或收料 RPA 扩散,也不新建 Upload Profile、关联表、版本表或发布流。
|
||||
发货 Excel 自动上传只在系统连接上保存是否启用。页面路径、按钮和成功判断写在对应货代的连接器里。**这是连接级开关,不是页面参数**:它只作用于货代上传,不向库存 RPA 或收料 RPA 扩散,也不新建 Upload Profile、关联表、版本表或发布流。
|
||||
|
||||
- **配置由管理端表单编辑,后端保存为受限 JSON**。白名单字段仅 `enabled / entry_url / file_input_selector / submit_mode / submit_selector / result_mode / result_selector / success_texts / timeout_seconds`;保存时后端严格校验:
|
||||
- `connector_type` 仍只能是 `dbs / crane`。
|
||||
- `entry_url` 必须 HTTPS,且主机名只允许该连接已审核的平台域名(`dbschenker.com` / `craneww.com` 后缀匹配)。
|
||||
- 三个 selector 只允许普通 CSS selector,限制长度(≤200)并拒绝 `javascript:`、`<script`、`expression(`、`on*=` 及 `() {} ; < >` 等脚本/表达式语义。
|
||||
- `submit_mode` 只允许 `auto_after_file / click_submit`;`result_mode` 只允许 `page_notice / history_record`。
|
||||
- `enabled=true` 时须具备完成一次上传与判定结果所需的全部字段:公共必填 `entry_url / file_input_selector / submit_mode / timeout_seconds`;`click_submit` 须有 `submit_selector`;crane 启用时还须补全 `result_selector` 与成功文本/记录判定字段(DSV 由代码内置的受控成功流判定,不强制管理员填写)。
|
||||
- 禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
|
||||
- **DSV 初始值**:`enabled=true`,`entry_url=https://s360.dbschenker.com/main/portal/frame/WMSUpload2`,`file_input_selector=input#file2`,`submit_mode=auto_after_file`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。
|
||||
- **Crane 初始值**:`enabled=false`(提交按钮、成功提示或上传历史记录的稳定选择器尚未确认,仅有文件选择器不代表可安全自动提交),`entry_url=https://wms-portal.craneww.com/#/shipping-order-upload`,`file_input_selector=input[name="OrderFileUpload"]`,`submit_mode=click_submit`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。管理员完成页面验证并补全提交/成功判定字段后才可 `enabled=true`。
|
||||
- **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期;不维护 `upload_config_version`(无发布流、无并发编辑审批、无历史回放需求)。每个 trigger 固化本次 upload_config 快照即可保证“这次上传用了什么”;需要审计关联时对快照计算 `config_hash`(sha256)。
|
||||
- **Worker 保留两个受控 Adapter**:`DsvUploadAdapter`(DSV 入口、文件选择与结果判定)与 `CraneUploadAdapter`(Crane 入口、文件选择、提交与结果判定),**不再根据环境变量拼接 DSV/Crane 页面动作**。用连接 `login_url` 登录后访问 `upload_config.entry_url` 进入上传页;`upload_config` 决定“该连接使用哪个已支持的受控流程及其页面参数”,浏览器动作与安全边界由代码负责;Worker 上传与最终提交的全局开关(`FREIGHT_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留,但不再承载页面参数。
|
||||
- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及 `upload_config_json` → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger(复用“临时文件 + fsync + os.replace”,携带 `schema_version / task_no / attempt_id / artifact_id / callback_id / connector_type / upload_config 快照 / upload_config_hash / login_url / credential_envelope`)→ Windows Worker 取 trigger → 按 `connector_type` 进入 DSV/Crane Adapter → 登录、打开 entry_url、选择 Excel、提交 → 以受控页面选择器判定 → 回调。
|
||||
- **结果三态**:`success`(取得可核验成功证据)、`failed`(明确页面失败、浏览器错误、超时或回调失败)、`unknown`(已可能提交但无法确认外部系统结果)。`unknown` 必须转人工处理,禁止自动重试以避免重复上传;成功/失败/未知、页面证据摘要与脱敏错误写入现有 Upload Attempt 与货代审计事件。
|
||||
- **配置只保存是否启用**。`upload_config_json` 落库只保留 `{enabled}`。旧客户端带来的入口 URL、文件选择器、提交方式、结果选择器和成功文本在保存时丢弃,不作为运行参数。`connector_type` 仍只能是 `dbs / crane`。
|
||||
- **页面动作在连接器代码里**。Worker 用连接 `login_url` 的主机拼出上传页:DBS 为 `/main/portal/frame/WMSUpload2`,Crane 为 `/#/shipping-order-upload`。DBS 固定点击 `Process File`,并同时核对成功提示与两个错误面板。Crane 固定使用 `input[name="OrderFileUpload"]`。
|
||||
- **DBS 同步完成**。同一页面即可判定成功或失败,没有状态回查。
|
||||
- **Crane 先进入分配中**。提交后若该行是 `Processing + Allocating the Shipping Order`,尝试保持 `running` 且 `error_code=CRANE_ALLOCATING`,业务状态为 `allocating`(已接收,分配中)。只有 `Processing + Shipping Order Allocated` 才算上传成功。自动上传后只排一次 10 分钟后的 Worker 重新登录回查;手动刷新是另一次立即回查,不改那一次定时的到期时间。两条回查都只按 Pull Request #(Excel 文件名去扩展名)看行,不重新上传。仍在分配中时禁止再次上传同一文件。
|
||||
- **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期。
|
||||
- **Worker 保留两个受控 Adapter**:`DsvUploadAdapter` 与 `CraneUploadAdapter`。Worker 上传与最终提交的全局开关(`FREIGHT_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留。
|
||||
- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及是否启用自动上传 → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger → Windows Worker 按 `connector_type` 登录并打开代码固定的上传页。Crane 分配中的到期回查由 Worker 心跳写成 `mode=status_check` 的 trigger。
|
||||
- **结果**:`success`(取得可核验成功证据)、`failed`(明确页面失败)、`unknown`(无法确认,转人工且禁止自动重试)、`allocating`(Crane 已接收,仍在分配)。分配中的状态回查若暂时看不到行,保持分配中,不改成 unknown。
|
||||
|
||||
发布门禁:全局只有一个 published 版本;已发布版本不可编辑;字段首次发布后 `scope/value_type` 不可修改;**同一 field_id 的 `field_code` 一经发布不可变更**(改名 = 退役旧字段 + 新建字段,允许同一 `field_code` 漂移到新 `field_id`),历史发布快照保留旧名称;证据来源、比较器、规范化器和校验器只能引用后端白名单。
|
||||
|
||||
@@ -2425,7 +2420,7 @@ cd C:\HxopsRpaTest
|
||||
|
||||
默认 Secret 路径为 `C:\HxopsRpaSecrets\test.xml` 与 `prod.xml`。文件不得进入仓库、SMB 共享、日志或其他 Windows 用户目录。
|
||||
|
||||
DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Profile 中配置。后端将加密凭据作为 trigger 的 `credential_envelope` 发送给 Worker,Worker 只用 `FREIGHT_RPA_CREDENTIAL_KEY` 解密,不从 Windows Secret 文件重新录入。
|
||||
DSV/Crane 登录地址、账号和密码必须先在 HXOPS 管理端的 RPA Profile 中配置。管理端 Profile 接口回传用户名明文,便于辨认账号;密码与密文不返回,留空保存表示不修改。库内仍只存 Fernet 密文。后端将加密凭据作为 trigger 的 `credential_envelope` 发送给 Worker,Worker 只用 `FREIGHT_RPA_CREDENTIAL_KEY` 解密,不从 Windows Secret 文件重新录入。
|
||||
|
||||
手工启动 test:
|
||||
|
||||
|
||||
+15
-6
@@ -34,23 +34,32 @@
|
||||
| OA 合同与请款同步 | 已实现 | 合同申请单走 HTTP 待办/已办;验收归档查 OA SQL(`formtable_main_324.cgdh` × `workflow_requestbase.currentnodetype=3`)按采购单号落事件;普通同步只补空字段,管理员可强制覆盖 OA 非空字段并保留变更审计。 |
|
||||
| 四阶段三轮预警扫描 | 已实现 | 每日扫描只生成 pending 预警;第一轮按台账申请人真实姓名匹配系统用户,第二、三轮按申请人部门查 OA `HrmResource` + `Matrixtable_3`(`zz`/`jfl` 即企微 userid)。 |
|
||||
| 企业微信周汇总 | 已实现 | 每周五 18:00 按收件人发一条汇总卡片及逐笔 Excel 附件;Excel「收件人」列为系统用户真实姓名;“周汇总批次”保留批次审计,发送失败可点击图标查看原因。 |
|
||||
| 合同付款台账与详情 | 已实现 | 预付款和出货款按 OA「公司」选择账套查询(默认 HXJM,无锡和宏智散热科技有限公司为 WZHHZ,和泰科技(吴江)有限公司为 HTT)。未付的预付款、出货款可手动标为已付。Chat Agent「合同付款预警」以 Tab 展示合同台账:服务端分页展示合同、采购单号、供应商、四阶段列、申请人和简洁状态标签,列表不展示合同申请单流程编号。阶段列只显示阶段名;预付款和出货款以已付(付款日)或已逾期、即将到期、未到期区分;验收款和质保款不能标已付,但日期已过、7日内或更远时同样显示已逾期、即将到期、未到期。日期依据缺失时按阶段写明原因:合同归档日未填、交货日期未填、验收单未归档、质保到期日未定;关键词同时匹配合同号、流程号、采购单号、供应商和申请人;四张汇总卡按合同统计即将到期(7日内)、逾期未付、未到期(7日外)、本月应付(全量台账),点击过滤列表;点击合同在当前 Tab 内查看概览、原文附件、付款计划和预警记录。 |
|
||||
| 合同付款台账与详情 | 已实现 | 预付款和出货款按 OA「公司」选择账套查询(默认 HXJM,无锡和宏智散热科技有限公司为 WZHHZ,和泰科技(吴江)有限公司为 HTT)。未付的四个阶段都可手动标为已付。Chat Agent「合同付款预警」以 Tab 展示合同台账:服务端分页展示采购单号、供应商、四阶段列、申请人和简洁状态标签,列表不展示合同号和合同申请单流程编号。阶段列只显示阶段名;预付款和出货款以已付(付款日)或已逾期、即将到期、未到期区分;金额和比例都为 0 的阶段不标已逾期,也不参与汇总。四个阶段都按 ERP `apa_file`(`apa00=15`、`apa41=Y`、`apa63=1`,按 `apa34f` 对金额)标已付,也可以手动标为已付。对上或手动标记后不再显示已逾期。有应付金额且 ERP 未对上时,日期已过、7日内或更远仍显示已逾期、即将到期、未到期。日期依据缺失时按阶段写明原因:合同归档日未填、交货日期未填、验收单未归档、质保到期日未定;关键词同时匹配合同号、流程号、采购单号、供应商和申请人;四张汇总卡按合同统计即将到期(7日内)、逾期未付、未到期(7日外)、本月应付(全量台账),点击过滤列表;点击合同在当前 Tab 内查看概览、原文附件、付款计划和预警记录。 |
|
||||
| 通用合同解析与待确认合同 | 已实现 | 不再校验 V4 或其他固定模板;只校验合同号、金额、交期、采购单号及四阶段付款比例完整、无重复、合计 100%。关键事实或比例校验失败合同归入 Chat「待确认」Tab,不得触发自动预警。待确认合同可人工复核:补齐采购单号、合同金额和四阶段比例、金额、日期依据,启用阶段合计 100% 后进入合同台账;勾选无此阶段的节点不参与预警。 |
|
||||
| 扫描版合同 MinerU 解析 | 已实现 | OA PDF 附件优先经 MinerU 生成 Markdown 后再解析合同号、金额、交期与四阶段付款比例;服务未配置、失败或空结果时安全回退既有文字层/OCR,历史合同可用“批量重新解析存量合同”刷新。 |
|
||||
| 存量合同批量重解析 | 已实现 | 管理员可直接用已归档附件批量刷新历史解析结果,不覆盖 OA 字段。原文若已被临时文件清理删除,则按附件 ID 从 OA 或 DMS 重新下载后再解析。 |
|
||||
| 合同付款 Agent 授权 | 已实现 | 入口为 Chat builtin Agent `contract_payment`:平台管理员默认可访问;权限组启用后把该 Agent 勾到角色包即可,不再按人授权。旧功能权限 `contract_payment.access` 由迁移写入 Agent 授权后删除。无授权直链提示并回应用管理,API 返回 403。同步 OA、强制覆盖、批量重解析、扫描预警和发送预警仅平台管理员可见并可调用。 |
|
||||
| OA 盖章合同优先 | 已实现 | 合同申请单存在“盖章完成合同上传”时固定优先下载和解析该附件;“合同附件”仅作为失败降级来源。 |
|
||||
|
||||
## 制程品质异常预警
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 滚动统计与升级规则 | 规划中 | 料号 + 不良类别,申请日期计次。近一年为扫描日减 1 年至前 1 天,≥ 3 才预警;当月按自然月计含当天。周报给品质担当,当月第 1/2/≥3 笔分别升级到品质+生产经副理、COO、老板(抄送 COO、品质、生产经副理)。废弃和撤销不计入。权威:[features/process-quality-alert/demand.md](features/process-quality-alert/demand.md)。 |
|
||||
| OA 接入与 OA 邮件 | 未开始 | 流程表、字段和发信方式留设计文档。需求只定渠道是 OA 邮件。 |
|
||||
| 收件人与待确认口径 | 待确认 | 五个岗位界面配置、不写死姓名。一单多行是否按行计次、空不良类别是否排除、具体人员尚未确认。 |
|
||||
|
||||
## 设备验收预警
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。只监控未归档、有效、可以验收的 OA 资产验收单。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 |
|
||||
| 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 验收单、流程状态、当前节点和操作人。按 `sfkyzcys`、`sfzfth`、`flowstatus` 3/4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 |
|
||||
| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。有权限的用户看列表和详情,同步按钮只给平台管理员。 |
|
||||
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。未归档且已开始计时的单据,可以验收为是或未标明都监控,明确为否才不监控。再进入仍用第一次写入的 `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`。 |
|
||||
| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。只列出未归档单据,并展示流程编号、标题和创建时间。有权限的用户看列表和详情,同步按钮只给平台管理员。 |
|
||||
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:00。 |
|
||||
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 |
|
||||
| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人发送一条汇总卡片和一份 Excel 明细。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
||||
| 四档企业微信升级 | 已按使用部门担当 | 超过 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)。 |
|
||||
| E8 补抓 | 已接上查询 | 读取 `ecology` 上的验收单,与 E10 分来源保存。计时起点 `syddjssj`。暂停 `currentstatus = 0` 按撤销停表。没有作废、强制结束。见 [technical.md](features/equipment-acceptance-warning/technical.md)。 |
|
||||
|
||||
## 知识库同步状态校验
|
||||
|
||||
@@ -820,7 +829,7 @@
|
||||
| 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行提交执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按票聚合结果(写路径已接线,见下行「ERP 建单写路径」) |
|
||||
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 入站文件与 09:00 自动调拨(现注册表单列 `in-transit-transfer` platform job,缺当日入站文件自动触发收料 RPA);任务参数=来源实例/历史可恢复异常复核/可选异动日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部成熟积压;非法偏移快速失败,偏移终点落在 T−1/当天或更晚由匹配层卡控截止≤T−2);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) |
|
||||
| 调拨类型配置化(2026-10-14) | 已实现 | 类型来自平台配置表 `transfer_type_configs`(ADR 0002,代码枚举/CHECK 约束/前端 union/「即将上线」占位全退役):管理端「在途调拨类型」页四块配置(基本信息/范围规则/仓库定义/字段转换),admin CRUD API + chat enabled 最小暴露 API;`transfer_type` 匹配创建必填(未配置/停用 fail-closed),配置为空前端空态;范围规则引擎(18 字段白名单、规则间 AND 值间 OR、内存谓词+SQL 编译双形态)、仓库定义(mapped/fixed+法人覆盖)、字段转换(批号前缀替换,六个系统边界生效,行/档保原值);规则随匹配快照进 scope_json;管理页见 `features/admin/modules/transfer-types/`,运维手册 technical.md §11 |
|
||||
| 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放);2026-10-21 外部单据身份扩维:自然键 8→10 成分(+外部单号/外部项次=WMS Order #/行号,迁移 tt21c8d9e0f1a2)作档幂等主键管控,movement 契约字段目录扩至 20 字段(解析 Profile 可映射),解析层料号空行静默跳过(不管控、不进异动表) |
|
||||
| 库存异动档与出生翻转(2026-10-14) | 已实现 | 新建 `transfer_movement_ledger`(ADR 0001,外部入站/出站记录唯一镜像):自然键幂等五语义(插入/sha 幂等跳过/证据变原行更新/缺席不删/已执行封存)、record_kind 声明+in_out_flag 交叉校验(矛盾打审计标记照常落档)、D13 业务字段+出站预留列、档级封存回写(执行成功 transfer_executed=true 防二次调拨);items 出生翻转=匹配创建时从档圈定建行(matching_id/ledger_record_id 出生即绑定),落地停写 items、重查对档对账、scope_item_query 退役;D17 圈档互斥(一条档记录一生一次绑定,取消释放/终态不释放;ADR 0007:新匹配自动顶替同一类型、同一来源、日期被盖住且尚未写 ERP 的旧匹配,人工关闭仍排除,未挂匹配的明细不占用,清单不列举历史匹配编号);2026-10-21 外部单据身份扩维:自然键 8→10 成分(+外部单号/外部项次=WMS Order #/行号,迁移 tt21c8d9e0f1a2)作档幂等主键管控,movement 契约字段目录扩至 20 字段(解析 Profile 可映射),解析层料号空行静默跳过(不管控、不进异动表) |
|
||||
| 入站/出站统一改版与幂等修复(2026-10-15) | 已实现 | record_kind 枚举值改版 inbound/outbound(迁移 tt14 值迁移);明细/单据列异动口径 `movement_*`(异动日期/数量/仓库列与匹配创建参数 `movement_date_from/to`、序列化键、Excel 表头随行更名,无兼容层);异动档自然键扩为 8 成分(+箱号/批号,三份真实 WMS 文件实测塌缩归零)+「异动日期非空才落档」过滤(`date_skipped`,未完成/已取消行不入档);解析规则 purpose 三枚举 onhand/inbound/outbound(迁移 tt15 值迁移);入站配置绑定校验 inbound 专用(`SHIPPING.INBOUND_PROFILE_INVALID`),出站绑定 `SHIPPING.OUTBOUND_PROFILE_INVALID`(2026-10-19 出站全栈);解析规则退役守卫补查入站/出站配置绑定;API 路由 `/sources/inbound-files`、`/runs/{run_no}/inbound-files` 与错误码/审计事件 inbound 化;出站 RPA 与调拨 sink 见 [superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md](superpowers/specs/2026-10-19-freight-rpa-outbound-and-rename-design.md);2026-10-15 设计见 [superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md](superpowers/specs/2026-10-15-inbound-outbound-idempotency-rename-design.md),运维手册 technical.md §12 |
|
||||
| 待匹配桶清空并重新解析(2026-10-15) | 已下线(2026-10-22) | 原入口会重放该来源保留期内全部归档,一次执行可把历史行整批灌进待匹配。界面与 `GET/POST /backlog/pending-match/reparse*` 已移除。重解析只保留来源卡「重新解析」(当天最新一份,不删行)。 |
|
||||
| 首页待匹配桶与 file_current 改锚(2026-10-14) | 已实现 | 待办看板新增「待匹配」桶(已落档但从未匹配的外部记录只读可见+去匹配引导,不可勾选执行),四队列卡数据源改档+最近执行状态联查;file_current 门禁改锚档记录 file_version(==来源最新可用文件 sha 即当前) |
|
||||
|
||||
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user