dsh-data-dashboard 0.1.8 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/incremental/flow.mjs +105 -34
- package/backend/incremental/jobs.mjs +11 -11
- package/backend/incremental/xlsx-rows.mjs +74 -3
- package/backend/modules/distributor/index.mjs +9 -6
- package/backend/modules/movement/index.mjs +17 -64
- package/backend/modules/scan/index.mjs +62 -0
- package/backend/modules/scan/legacy.mjs +21 -0
- package/backend/modules.mjs +2 -1
- package/backend/public/admin.css +9 -2
- package/backend/public/admin.js +74 -21
- package/backend/public/board.html +1 -1
- package/backend/public/board.js +2 -2
- package/backend/public/index.html +10 -10
- package/backend/real-data/decimal-sum.mjs +22 -0
- package/backend/real-data/generate-dashboard.mjs +18 -11
- package/backend/real-data/organization-mapping.mjs +31 -11
- package/backend/real-data/source-payload.mjs +163 -86
- package/backend/real-data/terminal-components.mjs +7 -7
- package/backend/real-data/terminal-structure.mjs +5 -5
- package/backend/real-data/v10-components.mjs +2 -2
- package/backend/real-data/v10-details.mjs +7 -62
- package/backend/real-data/v10-model.mjs +74 -71
- package/backend/real-data/v10-overview-data.mjs +14 -20
- package/backend/real-data/v10-overview.mjs +16 -6
- package/backend/real-data/v10-presentation.mjs +48 -27
- package/backend/real-data/v10-template.mjs +99 -71
- package/backend/review-engine.mjs +65 -35
- package/backend/review-service.mjs +28 -13
- package/backend/server.mjs +26 -17
- package/backend/store.mjs +3 -0
- package/backend/target-template.mjs +4 -2
- package/backend/validate-workbook.mjs +5 -2
- package/backend/web-sync/exporter.mjs +55 -21
- package/build-manifest.json +41 -38
- package/index.js +1 -1
- package/lib/tool-definitions.mjs +33 -15
- package/lib/tools.mjs +318 -85
- package/package.json +1 -1
package/lib/tools.mjs
CHANGED
|
@@ -11,34 +11,136 @@ export class BoardToolError extends Error {
|
|
|
11
11
|
constructor(code, message, detail = {}) { super(message); this.code = code; this.detail = detail; }
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
-
const
|
|
14
|
+
const periodKeys = ['month', 'start', 'end'];
|
|
15
|
+
const parentKeys = ['region', 'office'];
|
|
16
|
+
export const regionalMetrics = ['invoice', 'movement', 'opening', 'quarterInvoice', 'quarterMovement',
|
|
17
|
+
'quarterInvoiceYoY', 'quarterMovementYoY', 'quarterShare', 'invoiceQuarterAttainment', 'movementQuarterAttainment',
|
|
18
|
+
'invoiceAttainment', 'movementAttainment', 'openingTotal', 'openingYoY', 'signed', 'effectiveCount', 'effectiveRate'];
|
|
19
|
+
const MOVEMENT_RENDERER_VERSION = 24;
|
|
20
|
+
const usesLegacyMovement = version => Number(version) > 0 && Number(version) < MOVEMENT_RENDERER_VERSION;
|
|
21
|
+
const viewSources = { movement: ['invoice', 'movement'], opening: ['opening'], terminal: ['terminal'] };
|
|
22
|
+
|
|
23
|
+
function checkArgs(args, keys) {
|
|
24
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new BoardToolError('bad_argument', '参数应为对象。');
|
|
25
|
+
for (const [key, value] of Object.entries(args)) {
|
|
26
|
+
if (!keys.includes(key)) throw new BoardToolError('bad_argument', `未定义的参数:${key}。`, { allowed: keys });
|
|
27
|
+
if (typeof value !== 'string') throw new BoardToolError('bad_argument', `参数 ${key} 应为字符串。`);
|
|
28
|
+
if (!value.trim()) throw new BoardToolError(periodKeys.includes(key) ? 'bad_period' : 'bad_argument', `参数 ${key} 不能为空白。`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
15
32
|
const MONTH = /^\d{4}-\d{2}$/;
|
|
16
33
|
const DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
34
|
+
const validDay = value => DATE.test(value || '') && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
|
|
17
35
|
const finite = value => typeof value === 'number' && Number.isFinite(value);
|
|
18
36
|
const text = value => String(value ?? '').trim();
|
|
19
37
|
|
|
20
|
-
/**
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Payload literal inside a rendered dashboard (see v10-template.mjs renderShell):
|
|
40
|
+
* <script>… const V10_PAYLOAD=(<unpack function source>)(<JSON>);\nconst V10_PRESENTATION= …
|
|
41
|
+
* The embedded unpack source differs between versions, so declarations are found by the
|
|
42
|
+
* marker, and the JSON argument's end is found by scanning the JSON itself (strings and
|
|
43
|
+
* escapes aware) — never by searching for a later marker that data text could contain.
|
|
44
|
+
* Declarations inside HTML comments or outside <script> are skipped.
|
|
45
|
+
*/
|
|
46
|
+
const PAYLOAD_MARKER = 'const V10_PAYLOAD=(';
|
|
47
|
+
const PAYLOAD_TAIL = ');\nconst V10_PRESENTATION=';
|
|
48
|
+
const REQUIRED_MODULES = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet'];
|
|
49
|
+
const looksLikePayload = value => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
50
|
+
&& Array.isArray(value.organizationPaths) && value.modules !== null && typeof value.modules === 'object'
|
|
51
|
+
&& REQUIRED_MODULES.every(id => value.modules[id] && typeof value.modules[id] === 'object' && value.modules[id].records !== undefined);
|
|
52
|
+
/** Index just past the JSON value that starts with "{" at `from`, or -1. */
|
|
53
|
+
function jsonObjectEnd(text, from) {
|
|
54
|
+
let depth = 0, inString = false;
|
|
55
|
+
for (let i = from; i < text.length; i++) {
|
|
56
|
+
const c = text.charCodeAt(i);
|
|
57
|
+
if (inString) { if (c === 92) i++; else if (c === 34) inString = false; continue; }
|
|
58
|
+
if (c === 34) inString = true;
|
|
59
|
+
else if (c === 123 || c === 91) depth++;
|
|
60
|
+
else if (c === 125 || c === 93) { if (--depth === 0) return i + 1; }
|
|
61
|
+
}
|
|
62
|
+
return -1;
|
|
63
|
+
}
|
|
64
|
+
const insideComment = (html, at) => html.lastIndexOf('<!--', at) > html.lastIndexOf('-->', at);
|
|
65
|
+
const insideScript = (html, at) => html.lastIndexOf('<script', at) > html.lastIndexOf('</script', at);
|
|
66
|
+
/** Every well-formed payload declaration in a <script>, in document order. */
|
|
67
|
+
export function payloadCandidates(html, unpackSource) {
|
|
68
|
+
const found = [];
|
|
69
|
+
for (let start = html.indexOf(PAYLOAD_MARKER); start >= 0 && found.length < 5; start = html.indexOf(PAYLOAD_MARKER, start + 1)) {
|
|
70
|
+
if (insideComment(html, start) || !insideScript(html, start)) continue;
|
|
71
|
+
const exact = unpackSource ? `${PAYLOAD_MARKER}${unpackSource})(` : null;
|
|
72
|
+
const starts = [];
|
|
73
|
+
if (exact && html.startsWith(exact, start)) starts.push(start + exact.length);
|
|
74
|
+
else for (let at = html.indexOf(')({', start + PAYLOAD_MARKER.length); at >= 0 && starts.length < 20; at = html.indexOf(')({', at + 1)) starts.push(at + 2);
|
|
75
|
+
for (const from of starts) {
|
|
76
|
+
const end = jsonObjectEnd(html, from);
|
|
77
|
+
if (end < 0 || !html.startsWith(PAYLOAD_TAIL, end)) continue;
|
|
78
|
+
let value; try { value = JSON.parse(html.slice(from, end)); } catch { continue; }
|
|
79
|
+
if (looksLikePayload(value)) { found.push(value); break; }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return found;
|
|
83
|
+
}
|
|
84
|
+
/** The dashboard's payload; `accept` (optional) picks among several declarations. */
|
|
85
|
+
export function extractPayload(html, unpackSource, accept = null) {
|
|
86
|
+
const candidates = payloadCandidates(html, unpackSource);
|
|
87
|
+
return (accept ? candidates.find(accept) : candidates[0]) ?? null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// renderShell hashes the already-sanitized payload before packing. Unpacking
|
|
91
|
+
// preserves its fields, but restores org and orgPath at the end of each record.
|
|
92
|
+
function rendererPayloadHash(payload) {
|
|
93
|
+
const json = JSON.stringify(payload, (_key, value) => {
|
|
94
|
+
if (value && typeof value === 'object' && Object.hasOwn(value, 'org') && Object.hasOwn(value, 'orgPath')) {
|
|
95
|
+
return { org: value.org, orgPath: value.orgPath, ...value };
|
|
96
|
+
}
|
|
97
|
+
return value;
|
|
98
|
+
});
|
|
99
|
+
return createHash('sha256').update(json).digest('hex');
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function readBoardPayload(html, unpack, expectedHash) {
|
|
103
|
+
const candidates = payloadCandidates(html, unpack.toString());
|
|
104
|
+
if (expectedHash === null) return candidates.length ? unpack(candidates[0]) : null;
|
|
105
|
+
for (const packed of candidates) {
|
|
106
|
+
try {
|
|
107
|
+
const payload = unpack(packed);
|
|
108
|
+
if (rendererPayloadHash(payload) === expectedHash) return payload;
|
|
109
|
+
} catch { /* A malformed candidate cannot verify against the generation record. */ }
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Renderers before 24 put terminal scans in movement. Query their saved
|
|
115
|
+
// amounts as-is and give the signing calculation its original scan input.
|
|
116
|
+
function restoreLegacyScan(payload) {
|
|
117
|
+
if (payload.modules.scan || !payload.sources.movement || payload.coverage.movement?.semantics !== 'scan-date') return payload;
|
|
118
|
+
const { modules, sources, coverage, decisionContract } = payload;
|
|
119
|
+
const identity = decisionContract?.terminalIdentity;
|
|
120
|
+
return { ...payload, modules: { ...modules, scan: modules.movement }, sources: { ...sources, scan: sources.movement },
|
|
121
|
+
coverage: { ...coverage, scan: coverage.movement },
|
|
122
|
+
...(identity?.sources?.movement ? { decisionContract: { ...decisionContract,
|
|
123
|
+
terminalIdentity: { ...identity, sources: { ...identity.sources, scan: identity.sources.movement } } } } : {}) };
|
|
29
124
|
}
|
|
30
125
|
|
|
31
|
-
export function createBoardQueries({ dataDir, backendDir, port, problem = () => null }) {
|
|
126
|
+
export function createBoardQueries({ dataDir, backendDir, port, problem = () => null, now = Date.now }) {
|
|
32
127
|
let modulesPromise;
|
|
33
128
|
const code = () => modulesPromise ??= Promise.all([
|
|
34
129
|
import(pathToFileURL(resolve(backendDir, 'real-data/v10-template.mjs')).href),
|
|
35
130
|
import(pathToFileURL(resolve(backendDir, 'real-data/v10-model.mjs')).href),
|
|
36
131
|
import(pathToFileURL(resolve(backendDir, 'real-data/terminal-structure.mjs')).href),
|
|
132
|
+
import(pathToFileURL(resolve(backendDir, 'real-data/v10-presentation.mjs')).href),
|
|
133
|
+
import(pathToFileURL(resolve(backendDir, 'real-data/v10-overview-data.mjs')).href),
|
|
37
134
|
import(pathToFileURL(resolve(backendDir, 'modules.mjs')).href),
|
|
38
135
|
import(pathToFileURL(resolve(backendDir, 'server.mjs')).href),
|
|
39
|
-
|
|
40
|
-
|
|
136
|
+
import(pathToFileURL(resolve(backendDir, 'modules/scan/legacy.mjs')).href),
|
|
137
|
+
import(pathToFileURL(resolve(backendDir, 'real-data/decimal-sum.mjs')).href),
|
|
138
|
+
]).then(([template, model, terminal, presentation, overview, modules, server, scan, decimals]) => ({
|
|
139
|
+
unpack: template.unpackV10Payload, rendererVersion: template.V10_RENDERER_VERSION, sumDecimal: decimals.sumDecimal, createV10Model: model.createV10Model, buildTerminalStructure: terminal.buildTerminalStructure,
|
|
140
|
+
createDecimalSum: decimals.createDecimalSum,
|
|
141
|
+
createV10Presentation: presentation.createV10Presentation, createV10OverviewData: overview.createV10OverviewData,
|
|
41
142
|
definitions: modules.moduleDefinitions, cycles: server.DEFAULT_CYCLES,
|
|
143
|
+
activeUploadId: scan.activeUploadId, uploadForModule: scan.uploadForModule, isLegacyScanUpload: scan.isLegacyScanUpload,
|
|
42
144
|
}));
|
|
43
145
|
|
|
44
146
|
const readState = async () => {
|
|
@@ -48,42 +150,60 @@ export function createBoardQueries({ dataDir, backendDir, port, problem = () =>
|
|
|
48
150
|
throw new BoardToolError('state_unreadable', '无法读取插件数据目录中的 state.json,请在看板“更新数据”中检查后台状态。');
|
|
49
151
|
}
|
|
50
152
|
};
|
|
51
|
-
|
|
153
|
+
function selectedUpload(state, id, lib) {
|
|
154
|
+
const upload = lib.uploadForModule(state, id, state.candidates?.[id] || lib.activeUploadId(state, id));
|
|
155
|
+
return id === 'movement' && lib.isLegacyScanUpload(upload) ? null : upload;
|
|
156
|
+
}
|
|
52
157
|
const byTime = (a, b) => String(b.finishedAt || b.createdAt || '').localeCompare(String(a.finishedAt || a.createdAt || ''));
|
|
53
158
|
const latestCompleted = state => [...(state.generations || [])].filter(job => job.status === 'completed').sort(byTime)[0] || null;
|
|
54
159
|
const boardUrl = id => `http://127.0.0.1:${port}/api/generations/${id}/view`;
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
160
|
+
function newerUploads(state, job, lib) {
|
|
161
|
+
return lib.definitions.flatMap(({ id, title }) => {
|
|
162
|
+
const upload = selectedUpload(state, id, lib);
|
|
163
|
+
if (!upload) return [];
|
|
164
|
+
const legacyScan = id === 'scan' && usesLegacyMovement(job.rendererVersion) && lib.isLegacyScanUpload(upload);
|
|
165
|
+
const previousId = job.sourceVersions?.[id]?.uploadId ?? (legacyScan ? job.sourceVersions?.movement?.uploadId : null);
|
|
166
|
+
return upload.id === previousId ? [] : [{ moduleId: id, title }];
|
|
167
|
+
});
|
|
168
|
+
}
|
|
60
169
|
|
|
61
170
|
let cached = null;
|
|
62
171
|
/** Load (and cache by generation id) the latest board's model. */
|
|
63
172
|
async function board() {
|
|
64
173
|
const [state, lib] = await Promise.all([readState(), code()]);
|
|
65
|
-
const titles = Object.fromEntries(lib.definitions.map(item => [item.id, item.title]));
|
|
66
174
|
const job = latestCompleted(state);
|
|
67
175
|
if (!job) throw new BoardToolError('no_board', '还没有成功生成过看板。请在战区看板的“更新数据”中上传资料并生成看板后再查询。');
|
|
68
176
|
if (cached?.id !== job.id) {
|
|
69
177
|
let html;
|
|
70
178
|
try { html = await readFile(resolve(dataDir, 'generations', job.id, 'dashboard.html'), 'utf8'); }
|
|
71
179
|
catch { throw new BoardToolError('no_board', '最近一次生成的看板文件无法读取,请重新生成看板。'); }
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
180
|
+
const rendererVersion = Number(job.rendererVersion);
|
|
181
|
+
// Recompute only for the bundled renderer. Earlier layouts may have
|
|
182
|
+
// different serialized fields, even when their embedded data is readable.
|
|
183
|
+
const sameRenderer = rendererVersion === lib.rendererVersion;
|
|
184
|
+
const fingerprinted = sameRenderer && rendererVersion >= 23 && typeof job.payloadSha256 === 'string';
|
|
185
|
+
const legacyMovement = usesLegacyMovement(rendererVersion);
|
|
186
|
+
let unpacked = null, model = null;
|
|
187
|
+
try {
|
|
188
|
+
unpacked = readBoardPayload(html, lib.unpack, fingerprinted ? job.payloadSha256 : null);
|
|
189
|
+
model = unpacked ? lib.createV10Model(legacyMovement ? restoreLegacyScan(unpacked) : unpacked) : null;
|
|
190
|
+
} catch { model = null; }
|
|
191
|
+
if (!model) throw new BoardToolError('no_board', fingerprinted ? '最近一次生成的看板数据与生成记录对不上,请重新生成看板后再查询。' : '最近一次生成的看板格式较旧,无法读取其中的数据;请在界面中重新生成看板后再查询。');
|
|
192
|
+
const modelMatchesBoard = sameRenderer && html.includes(`const V10=(${lib.createV10Model.toString()})(V10_PAYLOAD);`)
|
|
193
|
+
&& ['buildTerminalStructure', 'createDecimalSum', 'sumDecimal', 'createV10Presentation', 'createV10OverviewData'].every(name => html.includes(`const ${name}=(${lib[name].toString()});`));
|
|
194
|
+
const presentation = lib.createV10Presentation(model);
|
|
195
|
+
cached = { id: job.id, model, presentation, overview: lib.createV10OverviewData(model, presentation), modelMatchesBoard, legacyMovement, coverage: unpacked.coverage || {} };
|
|
79
196
|
}
|
|
80
197
|
const basis = {
|
|
81
198
|
generationId: job.id, generatedAt: job.finishedAt || job.createdAt, payloadSha256: job.payloadSha256 || null,
|
|
82
|
-
modelMatchesBoard: cached.modelMatchesBoard, newerUploads: newerUploads(state, job,
|
|
83
|
-
dataEnd: Object.fromEntries(
|
|
84
|
-
...(cached.modelMatchesBoard ? {} : { warning:
|
|
199
|
+
modelMatchesBoard: cached.modelMatchesBoard, newerUploads: newerUploads(state, job, lib),
|
|
200
|
+
dataEnd: Object.fromEntries(cached.model.ids.map(id => [id, cached.coverage[id]?.end || null])),
|
|
201
|
+
...(cached.modelMatchesBoard ? {} : { warning: cached.legacyMovement
|
|
202
|
+
? '此成品使用旧终端扫码动销口径,建议重新生成看板以使用经销商和分销商明细。'
|
|
203
|
+
: '看板生成后计算代码已更新,数字可能与看板略有不同,建议重新生成。' }),
|
|
85
204
|
};
|
|
86
|
-
|
|
205
|
+
const titles = Object.fromEntries(lib.definitions.map(({ id, title }) => [id, title]));
|
|
206
|
+
return { model: cached.model, presentation: cached.presentation, overview: cached.overview, basis, state, titles, legacyMovement: cached.legacyMovement };
|
|
87
207
|
}
|
|
88
208
|
|
|
89
209
|
// ---- status ----
|
|
@@ -102,33 +222,34 @@ export function createBoardQueries({ dataDir, backendDir, port, problem = () =>
|
|
|
102
222
|
const localDay = value => { const date = new Date(value); return Number.isNaN(date.valueOf()) ? null : new Date(date.getFullYear(), date.getMonth(), date.getDate()); };
|
|
103
223
|
const cycleDays = { daily: 1, weekly: 7, monthly: 31, irregular: Infinity };
|
|
104
224
|
|
|
105
|
-
async function status(
|
|
225
|
+
async function status(args = {}) {
|
|
226
|
+
checkArgs(args, []);
|
|
227
|
+
const today = localDay(now());
|
|
106
228
|
const [state, lib] = await Promise.all([readState(), code()]);
|
|
107
229
|
const issue = problem();
|
|
108
230
|
const cycles = { ...lib.cycles, ...(state.settings?.cycles || {}) };
|
|
109
231
|
const sources = [];
|
|
110
232
|
for (const definition of lib.definitions) {
|
|
111
|
-
const
|
|
112
|
-
const
|
|
233
|
+
const { id, title, description } = definition;
|
|
234
|
+
const source = { moduleId: id, title, description }, upload = selectedUpload(state, id, lib);
|
|
113
235
|
const cycle = cycles[id] || 'irregular';
|
|
114
|
-
if (!upload) { sources.push({
|
|
236
|
+
if (!upload) { sources.push({ ...source, state: 'none', filename: null, uploadedAt: null, dataStart: null, dataEnd: null, reviewStatus: null, cycle, overdue: null }); continue; }
|
|
115
237
|
const range = await coverageOf(upload);
|
|
116
238
|
const day = localDay(upload.uploadedAt || upload.createdAt);
|
|
117
|
-
const age = day ? Math.round((
|
|
239
|
+
const age = day ? Math.round((today - day) / 86400000) : null;
|
|
118
240
|
sources.push({
|
|
119
|
-
|
|
241
|
+
...source, state: 'active', filename: upload.originalName || upload.filename || null,
|
|
120
242
|
uploadedAt: upload.uploadedAt || upload.createdAt || null, dataStart: range?.start || null, dataEnd: range?.end || null,
|
|
121
243
|
...(range ? {} : { dataRangeNote: '数据起止日尚未计算;打开插件后台后会自动补算。' }),
|
|
122
244
|
reviewStatus: upload.reviewStatus ?? 'unchecked', cycle, overdue: age === null ? null : age >= (cycleDays[cycle] ?? Infinity),
|
|
123
245
|
});
|
|
124
246
|
}
|
|
125
|
-
const titles = Object.fromEntries(lib.definitions.map(item => [item.id, item.title]));
|
|
126
247
|
const job = latestCompleted(state);
|
|
127
248
|
const failed = [...(state.generations || [])].sort(byTime)[0];
|
|
128
249
|
return {
|
|
129
250
|
backend: issue ? { state: 'problem', message: issue.message } : { state: 'running', url: `http://127.0.0.1:${port}/` },
|
|
130
251
|
sources,
|
|
131
|
-
latestBoard: job ? { generationId: job.id, generatedAt: job.finishedAt || job.createdAt, filename: job.filename || null, needsReview: Boolean(job.needsReview), url: boardUrl(job.id), newerUploads: newerUploads(state, job,
|
|
252
|
+
latestBoard: job ? { generationId: job.id, generatedAt: job.finishedAt || job.createdAt, filename: job.filename || null, needsReview: Boolean(job.needsReview), url: boardUrl(job.id), newerUploads: newerUploads(state, job, lib) } : null,
|
|
132
253
|
lastAttempt: failed && failed.status === 'failed' ? { at: failed.finishedAt || failed.createdAt, error: failed.error || '生成未完成' } : null,
|
|
133
254
|
};
|
|
134
255
|
}
|
|
@@ -141,17 +262,11 @@ export function createBoardQueries({ dataDir, backendDir, port, problem = () =>
|
|
|
141
262
|
for (const org of model.organizations) {
|
|
142
263
|
if (parentFilter && !parentFilter(org)) continue;
|
|
143
264
|
const key = org[level];
|
|
144
|
-
if (!keys.has(key)) keys.set(key, { key, name: partsOf(key).at(-1) || '未提供', fullPath: fullPath(key), label: model.label(key) });
|
|
265
|
+
if (!keys.has(key)) keys.set(key, { key, name: partsOf(key).at(-1) || '未提供', fullPath: fullPath(key), label: model.label(key), sources: new Set() });
|
|
266
|
+
for (const id of org.sources) keys.get(key).sources.add(id);
|
|
145
267
|
}
|
|
146
268
|
return [...keys.values()];
|
|
147
269
|
}
|
|
148
|
-
function sourcesOf(model, level, key) {
|
|
149
|
-
return model.ids.filter(id => model.payload.modules[id].records.some(row => {
|
|
150
|
-
const parts = row.orgPath || [];
|
|
151
|
-
const depth = { region: 4, office: 5, unit: 6 }[level];
|
|
152
|
-
return JSON.stringify(parts.slice(0, depth).map(value => value || '')) === JSON.stringify(partsOf(key).map(value => value || ''));
|
|
153
|
-
})).map(id => model.titles[id]);
|
|
154
|
-
}
|
|
155
270
|
function resolveOrg(model, { region, office, unit }) {
|
|
156
271
|
const filters = { region: 'all', office: 'all', unit: 'all' };
|
|
157
272
|
const pick = (level, name, parent) => {
|
|
@@ -179,29 +294,45 @@ export function createBoardQueries({ dataDir, backendDir, port, problem = () =>
|
|
|
179
294
|
return filters;
|
|
180
295
|
}
|
|
181
296
|
|
|
182
|
-
async function organizations(
|
|
297
|
+
async function organizations(args = {}) {
|
|
298
|
+
checkArgs(args, parentKeys);
|
|
299
|
+
const { region, office } = args;
|
|
183
300
|
const { model, basis } = await board();
|
|
184
301
|
const parentFilters = resolveOrg(model, { region, office });
|
|
185
302
|
const level = parentFilters.office !== 'all' ? 'unit' : parentFilters.region !== 'all' ? 'office' : 'region';
|
|
186
303
|
const items = levelItems(model, level, org => (parentFilters.region === 'all' || org.region === parentFilters.region) && (parentFilters.office === 'all' || org.office === parentFilters.office))
|
|
187
|
-
.map(item => ({ name: item.label, fullPath: item.fullPath, sources:
|
|
188
|
-
// Only organizations the summary can answer for (invoice / movement / opening).
|
|
189
|
-
.filter(item => item.sources.some(title => FLOW.some(id => model.titles[id] === title)));
|
|
304
|
+
.map(item => ({ name: item.label, fullPath: item.fullPath, sources: model.ids.filter(id => item.sources.has(id)).map(id => model.titles[id]) }));
|
|
190
305
|
return { basis: { generationId: basis.generationId, generatedAt: basis.generatedAt }, level, items };
|
|
191
306
|
}
|
|
192
307
|
|
|
193
308
|
// ---- summary ----
|
|
194
|
-
function shape(item, model) {
|
|
309
|
+
function shape(item, model, percentDigits = 1) {
|
|
195
310
|
if (!item) return { label: null, unit: null, value: null, display: null, state: 'missing', reason: '没有该指标' };
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
if (
|
|
199
|
-
|
|
311
|
+
const { label, unit, value } = item;
|
|
312
|
+
const info = { label, unit, ...(item.range ? { range: item.range } : {}), ...(item.note ? { note: item.note } : {}), ...(item.notes ? { notes: [...item.notes] } : {}) };
|
|
313
|
+
if (item.state !== 'available' || !finite(value)) {
|
|
314
|
+
const state = item.state === 'available' ? 'pending' : item.state || 'pending';
|
|
315
|
+
return { ...info, value: null, display: null, state, reason: item.reason || '看板未提供可用数值' };
|
|
316
|
+
}
|
|
317
|
+
const digits = item.displayPrecision ?? item.precision ?? (unit?.includes('/') || unit === '月' ? 2 : 0);
|
|
318
|
+
let display;
|
|
319
|
+
if (unit === '元') display = `${model.format(value / 10000, 2)} 万元`;
|
|
320
|
+
// 件数与看板一致:最多一位小数,整数不带 .0。
|
|
321
|
+
else if (unit === '件') display = `${model.format(value, 0, 1)} 件`;
|
|
322
|
+
else if (unit === '%') {
|
|
323
|
+
const magnitude = model.format(Math.abs(value), percentDigits);
|
|
324
|
+
if (value !== 0 && magnitude === model.format(0, percentDigits)) {
|
|
325
|
+
const step = model.format(10 ** -percentDigits, percentDigits);
|
|
326
|
+
display = value > 0 ? `<${step}%` : `>-${step}%`;
|
|
327
|
+
} else display = `${model.format(value, percentDigits)}%`;
|
|
328
|
+
}
|
|
329
|
+
else display = `${model.format(value, digits, unit === '件' ? Math.max(digits, 6) : digits)} ${unit}`;
|
|
330
|
+
return { ...info, value, display, state: 'available', reason: null };
|
|
200
331
|
}
|
|
201
332
|
|
|
202
333
|
function periodFilters(model, { month, start, end }) {
|
|
203
|
-
const hasMonth = month !== undefined
|
|
204
|
-
const hasRange =
|
|
334
|
+
const hasMonth = month !== undefined;
|
|
335
|
+
const hasRange = start !== undefined || end !== undefined;
|
|
205
336
|
if (hasMonth && hasRange) throw new BoardToolError('bad_period', 'month 与 start/end 只能二选一。');
|
|
206
337
|
const months = model.months.filter(value => MONTH.test(value));
|
|
207
338
|
if (hasMonth) {
|
|
@@ -210,7 +341,7 @@ export function createBoardQueries({ dataDir, backendDir, port, problem = () =>
|
|
|
210
341
|
return { month, period: 'month', start: null, end: null };
|
|
211
342
|
}
|
|
212
343
|
if (hasRange) {
|
|
213
|
-
if (!
|
|
344
|
+
if (!validDay(start) || !validDay(end) || start > end) throw new BoardToolError('bad_period', '区间需同时给出 start 与 end(YYYY-MM-DD),且开始不晚于结束。');
|
|
214
345
|
const bounds = model.dateBounds;
|
|
215
346
|
if (!bounds || start < bounds.min || end > bounds.max) throw new BoardToolError('bad_period', bounds ? `区间超出来源范围 ${bounds.min} 至 ${bounds.max}。` : '来源没有可用的日期范围。', { bounds });
|
|
216
347
|
return { month: end.slice(0, 7), period: 'range', start, end };
|
|
@@ -218,37 +349,139 @@ export function createBoardQueries({ dataDir, backendDir, port, problem = () =>
|
|
|
218
349
|
return { month: model.defaults.month, period: 'month', start: null, end: null };
|
|
219
350
|
}
|
|
220
351
|
|
|
221
|
-
|
|
222
|
-
|
|
352
|
+
const productLabel = item => `${item.brand} / ${item.name}`;
|
|
353
|
+
// product 只按名称(品类名或“品牌 / 品类”)匹配;productId 只按品类 ID 匹配,二者互斥,避免名称与另一品类的 ID 碰撞时选错。
|
|
354
|
+
function resolveProduct(model, name, productId) {
|
|
355
|
+
const options = model.categories;
|
|
356
|
+
if (name !== undefined && productId !== undefined) throw new BoardToolError('bad_argument', 'product 与 productId 只能二选一。');
|
|
357
|
+
if (productId !== undefined) {
|
|
358
|
+
const byId = options.find(item => item.id === productId);
|
|
359
|
+
if (!byId) throw new BoardToolError('product_not_found', `看板中没有品类 ID “${productId}”。`, { candidates: options.map(item => ({ productId: item.id, label: productLabel(item) })) });
|
|
360
|
+
return { id: byId.id, label: productLabel(byId) };
|
|
361
|
+
}
|
|
362
|
+
if (name === undefined || name === '全部产品') return { id: 'all', label: '全部产品' };
|
|
363
|
+
const matches = options.filter(item => item.name === name || productLabel(item) === name);
|
|
364
|
+
if (matches.length > 1) throw new BoardToolError('product_ambiguous', `“${name}”对应多个产品,请从候选中选一个,把它的 productId 传回 productId 参数。`, { candidates: matches.map(item => ({ productId: item.id, label: productLabel(item) })) });
|
|
365
|
+
if (!matches.length) {
|
|
366
|
+
const labels = new Set(), ambiguous = new Set(['全部产品', ...options.map(item => item.id)]);
|
|
367
|
+
for (const item of options) {
|
|
368
|
+
for (const alias of [item.name, productLabel(item)]) {
|
|
369
|
+
if (labels.has(alias)) ambiguous.add(alias);
|
|
370
|
+
labels.add(alias);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
const candidates = options.map(item => ambiguous.has(productLabel(item)) ? { productId: item.id, label: productLabel(item) } : productLabel(item));
|
|
374
|
+
throw new BoardToolError('product_not_found', `看板中没有产品“${name}”。字符串候选可传给 product,带 productId 的候选请传给 productId。`, { candidates: ['全部产品', ...candidates] });
|
|
375
|
+
}
|
|
376
|
+
return { id: matches[0].id, label: productLabel(matches[0]) };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function selection(model, args) {
|
|
223
380
|
const org = resolveOrg(model, args);
|
|
224
|
-
const
|
|
225
|
-
const
|
|
226
|
-
const
|
|
381
|
+
const product = resolveProduct(model, args.product, args.productId);
|
|
382
|
+
const filters = { ...model.defaults, ...periodFilters(model, args), ...org, product: product.id };
|
|
383
|
+
const data = model.select(filters);
|
|
384
|
+
const { mode, start, end, label } = data.period;
|
|
385
|
+
const key = [org.unit, org.office, org.region].find(key => key !== 'all');
|
|
386
|
+
return { filters, data, period: { mode, start, end, label }, product: product.label,
|
|
387
|
+
scope: { label: model.scope(org), fullPath: key ? fullPath(key) : '全战区' } };
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function targets(t, model) {
|
|
391
|
+
const output = { attainment: shape(t.attainment, model), ytdAttainment: shape(t.ytdAttainment, model),
|
|
392
|
+
target: shape(t.month, model), ytdTarget: shape(t.ytd, model) };
|
|
393
|
+
for (const kind of ['quarter', 'fiscal']) {
|
|
394
|
+
const window = t[kind];
|
|
395
|
+
if (window) output[kind] = { label: window.label, start: window.start, end: window.periodEnd,
|
|
396
|
+
actual: shape(window.actual, model), target: shape(window.target, model), attainment: shape(window.attainment, model) };
|
|
397
|
+
}
|
|
398
|
+
return output;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function comparison(item, model) {
|
|
402
|
+
return { ...shape(item, model), ...(item.current && { current: shape(item.current, model) }),
|
|
403
|
+
...(item.previous && { previous: shape(item.previous, model) }) };
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function legacyMovementMetric(metric) {
|
|
407
|
+
const label = metric.label?.replace('动销件数', '扫码净件数').replace('动销净额', '扫码净额').replace('动销 / 开票', '扫码 / 开票');
|
|
408
|
+
const note = text => text.replace(/经销商\s*\+\s*分销商动销明细|动销净额|动销金额/g, '终端扫码净额');
|
|
409
|
+
return { ...metric, label,
|
|
410
|
+
...(metric.note ? { note: note(metric.note) } : {}),
|
|
411
|
+
...(metric.notes ? { notes: metric.notes.map(note) } : {}) };
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function summary(args = {}) {
|
|
415
|
+
checkArgs(args, [...periodKeys, ...parentKeys, 'unit', 'product', 'productId']);
|
|
416
|
+
const { model, presentation, overview, basis, legacyMovement } = await board();
|
|
417
|
+
const { filters, data, scope, period, product } = selection(model, args);
|
|
418
|
+
const description = overview.describe(data, filters);
|
|
227
419
|
const modules = {};
|
|
228
|
-
for (const id of
|
|
229
|
-
const m =
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
420
|
+
for (const id of model.ids) {
|
|
421
|
+
const m = data.modules[id];
|
|
422
|
+
const kpis = presentation.describe(id, data, filters).kpis.map(item => shape(item, model, item.displayPrecision ?? 2));
|
|
423
|
+
const visitInventory = m.inventoryMode === 'visit-history';
|
|
424
|
+
const linked = id === 'invoice' || id === 'movement' || (id === 'inventory' && !visitInventory);
|
|
425
|
+
const module = { title: m.title, state: m.state, records: m.recordCount, period: m.period, notes: [...m.pending],
|
|
426
|
+
main: id === 'opening' || (id === 'inventory' && !visitInventory) ? kpis[0] : shape(m.main, model),
|
|
427
|
+
kpis, productFilter: linked ? '随产品筛选' : '不随产品筛选' };
|
|
428
|
+
if (m.targets) module.targets = targets(m.targets, model);
|
|
429
|
+
if (description.heroes[id]) {
|
|
430
|
+
const ytdLabel = period.mode === 'range' ? '当年截至区间末日来源金额' : '当年截至所选月来源金额';
|
|
431
|
+
module.ytd = kpis.find(item => item.label === ytdLabel) ?? shape(null, model);
|
|
432
|
+
module.comparisons = Object.fromEntries(['yoy', 'quarterYoY', 'ytdYoY'].map(key => [key, comparison(description.heroes[id][key], model)]));
|
|
433
|
+
}
|
|
434
|
+
if (id === 'opening') {
|
|
435
|
+
module.bottles = shape(m.main, model);
|
|
436
|
+
module.comparisons = { yoy: comparison(description.openingAmountYoY, model), mom: comparison(description.openingAmountMoM, model) };
|
|
437
|
+
}
|
|
438
|
+
if (id === 'invoice' && m.platformSources) module.sources = m.platformSources.map(item => ({
|
|
439
|
+
key: item.key, label: item.label, records: item.records, value: shape(item, model) }));
|
|
440
|
+
if (id === 'movement') {
|
|
441
|
+
module.cases = kpis.find(item => item.label === '动销件数') ?? shape(null, model);
|
|
442
|
+
if (legacyMovement) {
|
|
443
|
+
module.main = legacyMovementMetric(module.main);
|
|
444
|
+
module.cases = legacyMovementMetric(module.cases);
|
|
445
|
+
module.kpis = kpis.map(legacyMovementMetric);
|
|
446
|
+
module.notes = ['旧成品按原终端扫码日期汇总,金额和件数均取扫码明细。', ...module.notes.filter(note => !note.includes('经销商动销明细'))];
|
|
447
|
+
}
|
|
448
|
+
else module.movementSources = m.movementSources.map(item => ({
|
|
449
|
+
key: item.key, label: item.label, records: item.records, dataEnd: item.coverage?.end ?? null,
|
|
450
|
+
amount: shape(item, model), cases: shape(item.cases, model),
|
|
451
|
+
}));
|
|
452
|
+
}
|
|
453
|
+
modules[id] = module;
|
|
241
454
|
}
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
};
|
|
455
|
+
return { basis, scope, period, product, modules };
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
async function breakdown(args = {}) {
|
|
459
|
+
checkArgs(args, [...periodKeys, ...parentKeys, 'view', 'sortBy', 'order']);
|
|
460
|
+
const { view = 'movement', order = 'desc', sortBy = view === 'movement' ? 'quarterInvoice' : 'invoice' } = args;
|
|
461
|
+
if (!Object.hasOwn(viewSources, view)) throw new BoardToolError('bad_argument', '未知的区域一览视图。', { allowed: Object.keys(viewSources) });
|
|
462
|
+
if (!regionalMetrics.includes(sortBy)) throw new BoardToolError('bad_argument', '未知的排序指标。', { allowed: regionalMetrics });
|
|
463
|
+
if (!['asc', 'desc'].includes(order)) throw new BoardToolError('bad_argument', 'order 只能为 asc 或 desc。');
|
|
464
|
+
const { model, overview, basis, legacyMovement } = await board();
|
|
465
|
+
const { filters, data, scope, period } = selection(model, args);
|
|
466
|
+
const { regional, groupField } = overview.describe(data, filters);
|
|
467
|
+
const rows = regional.filter(row => row.sources.some(id => viewSources[view].includes(id)))
|
|
468
|
+
.map(row => ({ name: row.name, fullPath: row.fullName, sources: row.sources,
|
|
469
|
+
...Object.fromEntries(regionalMetrics.map(key => {
|
|
470
|
+
const metric = row[key];
|
|
471
|
+
const reachedQuarterTarget = (key === 'invoiceQuarterAttainment' || key === 'movementQuarterAttainment') && metric.value >= 100;
|
|
472
|
+
const item = shape(metric, model, reachedQuarterTarget ? 0 : 1);
|
|
473
|
+
return [key, legacyMovement && key === 'movement' ? legacyMovementMetric(item) : item];
|
|
474
|
+
})) }));
|
|
475
|
+
rows.sort((a, b) => {
|
|
476
|
+
const left = a[sortBy].value, right = b[sortBy].value;
|
|
477
|
+
if (left === null && right !== null) return 1;
|
|
478
|
+
if (right === null && left !== null) return -1;
|
|
479
|
+
return (order === 'asc' ? left - right : right - left) || a.name.localeCompare(b.name, 'zh-CN');
|
|
480
|
+
});
|
|
481
|
+
return { basis, scope, period, level: groupField, view, sortBy, order, rows };
|
|
249
482
|
}
|
|
250
483
|
|
|
251
|
-
return { status, summary, organizations, board };
|
|
484
|
+
return { status, summary, organizations, breakdown, board };
|
|
252
485
|
}
|
|
253
486
|
|
|
254
487
|
/** Stable digest of the data directory files the tools may read (for read-only tests). */
|