dsh-data-dashboard 0.1.7 → 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 +121 -32
- package/backend/incremental/jobs.mjs +19 -12
- 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 +27 -18
- 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
|
@@ -2,8 +2,9 @@ import { readFile } from 'node:fs/promises';
|
|
|
2
2
|
import { resolve } from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { atomicJson } from './store.mjs';
|
|
5
|
+
import { uploadForModule, isLegacyScanUpload } from './modules/scan/legacy.mjs';
|
|
5
6
|
import { moduleDefinitions } from './modules.mjs';
|
|
6
|
-
import { resolveInspection, validateDecision, validateOrganizationRule } from './review-engine.mjs';
|
|
7
|
+
import { legacyScanRuleFormats, reviewForSourceTemplates, resolveInspection, validateDecision, validateOrganizationRule } from './review-engine.mjs';
|
|
7
8
|
import { lineageShas } from './incremental/flow.mjs';
|
|
8
9
|
|
|
9
10
|
export const emptyReview = () => ({ version: 1, revision: 0, decisions: [], organizationRules: [], history: [] });
|
|
@@ -45,17 +46,23 @@ export function createReviewService({ store, dataDir, scan }) {
|
|
|
45
46
|
const result = await scan({ file: resolve(dataDir, 'uploads', upload.id, 'source.xlsx'), moduleId: upload.moduleId, sha256: upload.sha256, validation: upload.validation });
|
|
46
47
|
await saveInspection(upload, result); return result;
|
|
47
48
|
}
|
|
48
|
-
const selected = (state, id) => state
|
|
49
|
+
const selected = (state, id) => uploadForModule(state, id, state.candidates?.[id] || state.active[id]);
|
|
50
|
+
async function rulesFor(state) {
|
|
51
|
+
const current = selected(state, 'scan');
|
|
52
|
+
const oldFormats = await legacyScanRuleFormats(state, dataDir);
|
|
53
|
+
const scan = oldFormats.size && current && !isLegacyScanUpload(current) ? await inspection(current) : null;
|
|
54
|
+
return reviewForSourceTemplates(state.review, oldFormats, scan) ?? emptyReview();
|
|
55
|
+
}
|
|
49
56
|
async function view() {
|
|
50
|
-
const rules
|
|
57
|
+
const [rules, old] = await Promise.all([rulesFor(store.state), legacy()]);
|
|
51
58
|
const modules = [];
|
|
52
59
|
for (const module of moduleDefinitions) {
|
|
53
60
|
const upload = selected(store.state, module.id);
|
|
54
|
-
const raw = await inspection(upload);
|
|
61
|
+
const raw = isLegacyScanUpload(upload) ? null : await inspection(upload);
|
|
55
62
|
const result = raw ? resolveCurrent({ ...raw, lineage: lineageShas(store.state, upload.id) }, rules, old) : null;
|
|
56
63
|
modules.push({ id: module.id, title: module.title, uploadId: upload?.id ?? null, filename: upload?.filename ?? null,
|
|
57
64
|
sha256: upload?.sha256 ?? null, activeUploadId: store.state.active[module.id] ?? null,
|
|
58
|
-
status: !upload ? 'missing' : !result ? 'unchecked' : result.errors.length ? 'error' : result.pendingCount ? 'pending' : 'ready', inspection: result });
|
|
65
|
+
status: !upload ? 'missing' : isLegacyScanUpload(upload) ? (module.id === 'scan' ? 'ready' : 'missing') : !result ? 'unchecked' : result.errors.length ? 'error' : result.pendingCount ? 'pending' : 'ready', inspection: result });
|
|
59
66
|
}
|
|
60
67
|
return { revision: rules.revision, modules, decisions: rules.decisions, organizationRules: rules.organizationRules, history: rules.history };
|
|
61
68
|
}
|
|
@@ -68,11 +75,13 @@ export function createReviewService({ store, dataDir, scan }) {
|
|
|
68
75
|
});
|
|
69
76
|
}
|
|
70
77
|
async function promote(next) {
|
|
71
|
-
const old = await legacy();
|
|
78
|
+
const [old, rules] = await Promise.all([legacy(), rulesFor(next)]);
|
|
72
79
|
for (const module of moduleDefinitions) {
|
|
73
|
-
const upload = selected(next, module.id)
|
|
80
|
+
const upload = selected(next, module.id);
|
|
81
|
+
if (isLegacyScanUpload(upload)) continue;
|
|
82
|
+
const raw = await inspection(upload);
|
|
74
83
|
if (!raw) continue;
|
|
75
|
-
const result = resolveCurrent({ ...raw, lineage: lineageShas(next, upload.id) },
|
|
84
|
+
const result = resolveCurrent({ ...raw, lineage: lineageShas(next, upload.id) }, rules, old);
|
|
76
85
|
upload.reviewStatus = result.errors.length ? 'error' : result.pendingCount ? 'pending' : 'ready';
|
|
77
86
|
if (!result.pendingCount && !result.errors.length) {
|
|
78
87
|
next.active[module.id] = upload.id; delete next.candidates[module.id];
|
|
@@ -83,7 +92,7 @@ export function createReviewService({ store, dataDir, scan }) {
|
|
|
83
92
|
// Continue checking independent sources even when another source cannot be read.
|
|
84
93
|
for (const module of moduleDefinitions) {
|
|
85
94
|
const upload = selected(store.state, module.id);
|
|
86
|
-
if (!upload) continue;
|
|
95
|
+
if (!upload || isLegacyScanUpload(upload)) continue;
|
|
87
96
|
try { await inspect(upload); }
|
|
88
97
|
catch (e) {
|
|
89
98
|
await saveInspection(upload, { version: 1, moduleId: module.id, sha256: upload.sha256, sheet: upload.validation?.sheet ?? '', formatKey: '', rowCount: upload.validation?.rowCount ?? 0, coverage: { start: null, end: null }, groups: [], organizations: [], errors: [e.message] });
|
|
@@ -135,10 +144,16 @@ export function createReviewService({ store, dataDir, scan }) {
|
|
|
135
144
|
await promote(next);
|
|
136
145
|
}, 'revoke', { recordId: body.id });
|
|
137
146
|
} else if (action === 'select') {
|
|
138
|
-
const upload = store.state
|
|
139
|
-
if (!upload) throw error('
|
|
140
|
-
if (
|
|
141
|
-
|
|
147
|
+
const upload = uploadForModule(store.state, body.moduleId, body.uploadId);
|
|
148
|
+
if (!upload || body.moduleId === 'movement' && isLegacyScanUpload(upload)) throw error('该入口没有此版本。', 404);
|
|
149
|
+
if (isLegacyScanUpload(upload)) {
|
|
150
|
+
await update(next => {
|
|
151
|
+
next.active.scan = upload.id; delete next.candidates.scan;
|
|
152
|
+
}, 'select', { uploadId: upload.id, moduleId: 'scan' });
|
|
153
|
+
} else {
|
|
154
|
+
if (!await inspection(upload)) await inspect(upload);
|
|
155
|
+
await update(async next => { next.candidates[body.moduleId] = upload.id; await promote(next); }, 'select', { uploadId: upload.id, moduleId: upload.moduleId });
|
|
156
|
+
}
|
|
142
157
|
} else if (action === 'restore') {
|
|
143
158
|
const backup = body.backup;
|
|
144
159
|
if (!backup || backup.kind !== 'theater-review-settings' || backup.version !== 1 || !Array.isArray(backup.decisions) || !Array.isArray(backup.organizationRules) || backup.decisions.length + backup.organizationRules.length > 20000) throw error('不是受支持的处理设置备份。');
|
package/backend/server.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { createHash, randomUUID, randomBytes } from 'node:crypto';
|
|
|
7
7
|
import { dirname, resolve } from 'node:path';
|
|
8
8
|
import { fileURLToPath } from 'node:url';
|
|
9
9
|
import { Worker } from 'node:worker_threads';
|
|
10
|
+
import { uploadForModule, isLegacyScanUpload } from './modules/scan/legacy.mjs';
|
|
10
11
|
import { moduleDefinitions } from './modules.mjs';
|
|
11
12
|
import { identifyWorkbook } from './validate-workbook.mjs';
|
|
12
13
|
import { validationFingerprint } from './recognition/fingerprint.mjs';
|
|
@@ -25,7 +26,7 @@ const MAX_BYTES = uploadLimits.fileBytes;
|
|
|
25
26
|
const knownModules = new Set(moduleDefinitions.map(m => m.id));
|
|
26
27
|
// How often each board is expected to be refreshed. Only used for reminders.
|
|
27
28
|
const CYCLES = ['daily', 'weekly', 'monthly', 'irregular'];
|
|
28
|
-
export const DEFAULT_CYCLES = { invoice: 'daily', movement: 'daily', opening: 'daily', terminal: 'weekly', inventory: 'monthly', banquet: 'monthly', target: 'monthly', zang10: 'monthly', tunzhihu: 'monthly', distributor: 'weekly' };
|
|
29
|
+
export const DEFAULT_CYCLES = { invoice: 'daily', movement: 'daily', opening: 'daily', terminal: 'weekly', inventory: 'monthly', banquet: 'monthly', target: 'monthly', zang10: 'monthly', tunzhihu: 'monthly', distributor: 'weekly', scan: 'weekly' };
|
|
29
30
|
const publicFiles = new Map([['/', ['board.html', 'text/html; charset=utf-8']], ['/board', ['board.html', 'text/html; charset=utf-8']], ['/admin', ['index.html', 'text/html; charset=utf-8']], ['/board.js', ['board.js', 'text/javascript; charset=utf-8']], ['/board.css', ['board.css', 'text/css; charset=utf-8']], ['/admin.js', ['admin.js', 'text/javascript; charset=utf-8']], ['/admin.css', ['admin.css', 'text/css; charset=utf-8']]]);
|
|
30
31
|
for (const [file, type] of [['review.js', 'text/javascript'], ['review.css', 'text/css'], ['org-mapping.js', 'text/javascript']]) publicFiles.set(`/${file}`, [file, `${type}; charset=utf-8`]);
|
|
31
32
|
|
|
@@ -125,8 +126,9 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
125
126
|
// Data start/end for uploads saved before coverage was recorded (§11.5). Cached
|
|
126
127
|
// beside each upload; the upload records in state.json are not rewritten.
|
|
127
128
|
const coverageCache = new Map();
|
|
128
|
-
const COVERAGE_MODULES = new Set(['invoice', 'movement', 'opening', 'terminal', 'inventory']);
|
|
129
|
+
const COVERAGE_MODULES = new Set(['invoice', 'movement', 'scan', 'opening', 'terminal', 'inventory']);
|
|
129
130
|
const withCoverage = upload => !upload || upload.coverage?.start || !coverageCache.has(upload.id) ? upload : { ...upload, coverage: coverageCache.get(upload.id), coverageComputed: true };
|
|
131
|
+
const publicUpload = upload => isLegacyScanUpload(upload) ? { ...withCoverage(upload), moduleId: 'scan' } : withCoverage(upload);
|
|
130
132
|
let coverageRun = null;
|
|
131
133
|
async function fillCoverage() {
|
|
132
134
|
const ids = new Set([...Object.values(store.state.active || {}), ...Object.values(store.state.candidates || {})]);
|
|
@@ -143,7 +145,7 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
143
145
|
if (aggregate.sha256 === upload.sha256 && aggregate.aggregate?.start) { coverageCache.set(upload.id, { start: aggregate.aggregate.start, end: aggregate.aggregate.end }); continue; }
|
|
144
146
|
} catch {}
|
|
145
147
|
try {
|
|
146
|
-
const result = await workerJob({ kind: 'coverage', file: resolve(directory, 'source.xlsx'), validation: upload.validation, moduleId: upload.moduleId }, () => {}, log);
|
|
148
|
+
const result = await workerJob({ kind: 'coverage', file: resolve(directory, 'source.xlsx'), validation: upload.validation, moduleId: isLegacyScanUpload(upload) ? 'scan' : upload.moduleId }, () => {}, log);
|
|
147
149
|
// Write the cache file before publishing the range, so a reader that sees it can also find the file.
|
|
148
150
|
await atomicJson(resolve(directory, 'coverage.json'), { sha256: upload.sha256, start: result.start, end: result.end }).catch(log);
|
|
149
151
|
coverageCache.set(upload.id, { start: result.start, end: result.end });
|
|
@@ -178,11 +180,17 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
178
180
|
app: { id: APP_ID, name: '战区看板后台', version: '0.3.0', mode: 'real', dataDir },
|
|
179
181
|
token,
|
|
180
182
|
uploadLimits,
|
|
181
|
-
modules: moduleDefinitions.map(m =>
|
|
182
|
-
|
|
183
|
-
|
|
183
|
+
modules: moduleDefinitions.map(m => {
|
|
184
|
+
const upload = uploadForModule(store.state, m.id, store.state.active[m.id]);
|
|
185
|
+
const oldTemplate = m.id === 'movement' && isLegacyScanUpload(upload);
|
|
186
|
+
return { ...m, flow: isFlowModule(m.id), updatable: isUpdatable(m.id), modes: modesFor(m.id),
|
|
187
|
+
activeUpload: oldTemplate ? null : publicUpload(upload) ?? null,
|
|
188
|
+
candidateUpload: withCoverage(store.state.uploads.find(u => u.id === store.state.candidates?.[m.id])) ?? null,
|
|
189
|
+
reviewStatus: oldTemplate ? 'unchecked' : store.state.uploads.find(u => u.id === (store.state.candidates?.[m.id] || store.state.active[m.id]))?.reviewStatus ?? 'unchecked',
|
|
190
|
+
...(oldTemplate ? { outdatedBase: true } : {}) };
|
|
191
|
+
}),
|
|
184
192
|
reviewRevision: store.state.review?.revision ?? 0,
|
|
185
|
-
uploads: [...store.state.uploads].reverse().map(
|
|
193
|
+
uploads: [...store.state.uploads].reverse().map(publicUpload),
|
|
186
194
|
generations: [...store.state.generations].reverse().map(withLegacyMapping).map(job => ({ ...job, ...(job.status === 'completed' ? { viewUrl: `/api/generations/${job.id}/view`, downloadUrl: `/api/generations/${job.id}/download` } : {}) })),
|
|
187
195
|
busy,
|
|
188
196
|
settings: { cycles: { ...DEFAULT_CYCLES, ...(store.state.settings?.cycles || {}) } },
|
|
@@ -209,10 +217,10 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
209
217
|
}
|
|
210
218
|
function reserve(kind, moduleId) {
|
|
211
219
|
if (busy) throw new RequestError(409, '另一项上传或生成正在进行,请等待完成后再试。');
|
|
212
|
-
busy = { kind, ...(moduleId ? { moduleId } : {}), stage: kind === 'upload' ? '
|
|
220
|
+
busy = { kind, ...(moduleId ? { moduleId } : {}), stage: kind === 'upload' ? '正在读取上传文件' : '正在确认各板块资料' };
|
|
213
221
|
}
|
|
214
222
|
|
|
215
|
-
const selectedUpload = (state, moduleId) => state
|
|
223
|
+
const selectedUpload = (state, moduleId) => uploadForModule(state, moduleId, state.candidates?.[moduleId] || state.active[moduleId]) ?? null;
|
|
216
224
|
|
|
217
225
|
/** Validate, inspect and install a received workbook as the module's newest source. */
|
|
218
226
|
async function install({ moduleId, filename, temp, info, extra = {} }) {
|
|
@@ -223,14 +231,14 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
223
231
|
const current = selectedUpload(store.state, moduleId);
|
|
224
232
|
// Exact current bytes are idempotent; older versions may be chosen again as a fresh upload.
|
|
225
233
|
if (current?.sha256 === info.sha256 && current.validationContract === validationContract) return { record: current, duplicate: true };
|
|
226
|
-
busy.stage = '
|
|
234
|
+
busy.stage = '正在核对表头和数据';
|
|
227
235
|
let validation;
|
|
228
236
|
try { validation = await workerJob({ kind: 'upload', file: temp, moduleId }, () => {}, log); }
|
|
229
237
|
catch (error) { throw new RequestError(422, error.message); }
|
|
230
238
|
if (!validation.ok) throw new RequestError(422, '文件结构校验未通过,原有效资料已保留。', { validation });
|
|
231
239
|
const checkedContract = await validationFingerprint(moduleId);
|
|
232
240
|
if (checkedContract !== validationContract) throw new RequestError(409, '校验期间规则发生修改,请重新上传。');
|
|
233
|
-
busy.stage = '
|
|
241
|
+
busy.stage = '正在检查重复记录和组织对应';
|
|
234
242
|
const inspection = await workerJob({ kind: 'inspect', file: temp, moduleId, sha256: info.sha256, validation }, () => {}, log);
|
|
235
243
|
const directory = resolve(dataDir, 'uploads', id);
|
|
236
244
|
await mkdir(directory, { mode: 0o700 });
|
|
@@ -289,6 +297,7 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
289
297
|
function alreadyApplied(state, moduleId, sha256) {
|
|
290
298
|
const current = selectedUpload(state, moduleId);
|
|
291
299
|
if (!current) return false;
|
|
300
|
+
if (moduleId === 'movement' && isLegacyScanUpload(current)) return false;
|
|
292
301
|
if (current.sha256 === sha256 || lineageShas(state, current.id).includes(sha256)) return true;
|
|
293
302
|
for (let item = current, guard = 0; item && guard < 5000; guard++) {
|
|
294
303
|
if (item.composition?.partSha256 === sha256) return true;
|
|
@@ -303,7 +312,7 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
303
312
|
if (!isUpdatable(moduleId)) throw new RequestError(400, '经营目标暂不支持核对更新,请按原方式整份上传。');
|
|
304
313
|
const filename = filenameFrom(request);
|
|
305
314
|
if (request.headers['content-type'] !== 'application/octet-stream') throw new RequestError(415, '上传格式无效,请从后台选择文件。');
|
|
306
|
-
reserve('upload', moduleId); busy.stage = '
|
|
315
|
+
reserve('upload', moduleId); busy.stage = '正在读取文件并核对表头';
|
|
307
316
|
const id = randomUUID(), directory = resolve(dataDir, 'temp', `staged-${id}`);
|
|
308
317
|
let kept = false;
|
|
309
318
|
try {
|
|
@@ -320,7 +329,7 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
320
329
|
busy.stage = '正在对比现有数据';
|
|
321
330
|
const analysis = await workerJob({ kind: 'analyze', moduleId, partFile: file, partValidation: validation,
|
|
322
331
|
baseFile: base ? resolve(dataDir, 'uploads', base.id, 'source.xlsx') : null, baseValidation: base?.validation, baseAggregate: cached }, () => {}, log);
|
|
323
|
-
if (base && !cached && analysis.base && isFlowModule(moduleId)) await atomicJson(resolve(dataDir, 'uploads', base.id, 'aggregate.json'), { version: AGGREGATE_VERSION, sha256: base.sha256, aggregate: analysis.base }).catch(log);
|
|
332
|
+
if (base && !cached && analysis.base && !analysis.base.outdated && isFlowModule(moduleId)) await atomicJson(resolve(dataDir, 'uploads', base.id, 'aggregate.json'), { version: AGGREGATE_VERSION, sha256: base.sha256, aggregate: analysis.base }).catch(log);
|
|
324
333
|
const suggestion = suggestMode(analysis.base, analysis.part);
|
|
325
334
|
const meta = { id, moduleId, filename, ...info, validation, createdAt: new Date().toISOString(), baseUploadId: base?.id ?? null, base: analysis.base, part: analysis.part, existingByDate: analysis.existingByDate, suggestion };
|
|
326
335
|
await atomicJson(resolve(directory, 'meta.json'), meta);
|
|
@@ -363,7 +372,7 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
363
372
|
refuse(checked);
|
|
364
373
|
if (options.mode === 'full' || !base) {
|
|
365
374
|
// Check again from the files themselves (the range / incremental path rechecks while composing).
|
|
366
|
-
busy.stage = '
|
|
375
|
+
busy.stage = '正在复核文件内容';
|
|
367
376
|
const cached = isFlowModule(meta.moduleId) ? await baseAggregate(base) : null;
|
|
368
377
|
const fresh = await workerJob({ kind: 'analyze', moduleId: meta.moduleId, partFile, partValidation: meta.validation,
|
|
369
378
|
baseFile: base ? resolve(dataDir, 'uploads', base.id, 'source.xlsx') : null, baseValidation: base?.validation, baseAggregate: cached }, () => {}, log);
|
|
@@ -378,7 +387,7 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
378
387
|
result = await install({ moduleId: meta.moduleId, filename: meta.filename, temp: partFile, info: { bytes: meta.bytes, sha256: meta.sha256 },
|
|
379
388
|
extra: { composition: { mode: 'full', step: 0, partId, partSha256: meta.sha256, partFilename: meta.filename, partRows: meta.part.rows, appliedAt } } });
|
|
380
389
|
} else {
|
|
381
|
-
busy.stage = '
|
|
390
|
+
busy.stage = '正在合并到现有数据';
|
|
382
391
|
let composed;
|
|
383
392
|
try {
|
|
384
393
|
composed = await workerJob({ kind: 'compose', moduleId: meta.moduleId, mode: options.mode, start: checked.start, end: checked.end, confirmMissing: options.confirmMissing,
|
|
@@ -451,7 +460,7 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
451
460
|
}
|
|
452
461
|
if (request.method === 'POST' && path.startsWith('/api/review/')) {
|
|
453
462
|
const body = await readJson(request, path === '/api/review/restore' ? 32 * 1048576 + 1024 : 8 * 1048576);
|
|
454
|
-
reserve('review'); busy.stage = '
|
|
463
|
+
reserve('review'); busy.stage = '正在保存检查和处理结果';
|
|
455
464
|
try {
|
|
456
465
|
const action = path.slice('/api/review/'.length);
|
|
457
466
|
const result = action === 'check' ? await review.check() : await review.mutate(action, body);
|
|
@@ -519,9 +528,9 @@ export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DI
|
|
|
519
528
|
if (request.method === 'GET' && path === '/api/target-template') {
|
|
520
529
|
// Organization names come from source inspections; scan any active source
|
|
521
530
|
// that has not been inspected yet so the template is not left blank.
|
|
522
|
-
for (const id of ['invoice', 'movement', 'opening']) {
|
|
531
|
+
for (const id of ['invoice', 'movement', 'distributor', 'opening']) {
|
|
523
532
|
const upload = store.state.uploads.find(item => item.id === store.state.active[id] && item.moduleId === id);
|
|
524
|
-
if (upload && !(await review.inspection(upload).catch(() => null))) await review.inspect(upload).catch(log);
|
|
533
|
+
if (upload && !isLegacyScanUpload(upload) && !(await review.inspection(upload).catch(() => null))) await review.inspect(upload).catch(log);
|
|
525
534
|
}
|
|
526
535
|
const content = await buildTargetTemplate({ organizations: await targetOrganizations(dataDir, store.state) });
|
|
527
536
|
response.writeHead(200, { 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Length': content.length,
|
package/backend/store.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { mkdir, readFile, writeFile, rename, unlink, open, rmdir } from 'node:fs/promises';
|
|
2
2
|
import { resolve } from 'node:path';
|
|
3
|
+
import { legacyScanId } from './modules/scan/legacy.mjs';
|
|
3
4
|
import { randomUUID } from 'node:crypto';
|
|
4
5
|
|
|
5
6
|
export async function atomicJson(file, value) {
|
|
@@ -61,6 +62,8 @@ export async function openStore(dataDir) {
|
|
|
61
62
|
return pending;
|
|
62
63
|
}
|
|
63
64
|
await update(next => {
|
|
65
|
+
const legacy = legacyScanId(next);
|
|
66
|
+
if (legacy && !next.active.scan) next.active.scan = legacy;
|
|
64
67
|
for (const job of next.generations) if (job.status === 'running') Object.assign(job, { status: 'failed', stage: '生成中断', error: '上次后台退出时任务尚未完成,请重新生成。', finishedAt: new Date().toISOString() });
|
|
65
68
|
});
|
|
66
69
|
return { get state() { return state; }, update, release };
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { isLegacyScanUpload } from './modules/scan/legacy.mjs';
|
|
1
2
|
import { readFile } from 'node:fs/promises';
|
|
2
3
|
import { resolve } from 'node:path';
|
|
3
4
|
import ExcelJS from 'exceljs';
|
|
4
5
|
|
|
5
|
-
const SOURCES = ['invoice', 'movement', 'opening'];
|
|
6
|
+
const SOURCES = ['invoice', 'movement', 'distributor', 'opening'];
|
|
6
7
|
|
|
7
8
|
// Prefill organization names already seen in the active sources. Business
|
|
8
9
|
// values stay blank: the template never suggests or copies a target amount.
|
|
@@ -11,6 +12,7 @@ export async function targetOrganizations(dataDir, state) {
|
|
|
11
12
|
for (const id of SOURCES) {
|
|
12
13
|
const uploadId = state.active?.[id];
|
|
13
14
|
if (typeof uploadId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(uploadId)) continue;
|
|
15
|
+
if (isLegacyScanUpload(state.uploads?.find(upload => upload.id === uploadId))) continue;
|
|
14
16
|
try {
|
|
15
17
|
const inspection = JSON.parse(await readFile(resolve(dataDir, 'uploads', uploadId, 'inspection.json'), 'utf8'));
|
|
16
18
|
for (const org of inspection.organizations || []) {
|
|
@@ -41,7 +43,7 @@ export async function buildTargetTemplate({ organizations = [], month = new Date
|
|
|
41
43
|
'主任单元留空 = 目标填在办事处层级;办事处也留空 = 大区层级;三级都留空 = 全战区目标。上级目标不会自动拆分到下级,可以只填大区或部分办事处。',
|
|
42
44
|
'大区、办事处、主任单元名称需与经营来源中的名称一致,对不上的目标不会计入。',
|
|
43
45
|
'某一列留空表示该组织当月没有这项目标;整行都没填的可以保留也可以删除。同一年月、组织请只填一行;重复时该目标显示待确认。',
|
|
44
|
-
'
|
|
46
|
+
'已预填的组织名称来自当前已上传的发票、经销商动销、分销商动销、开瓶资料,目标值需自行填写。',
|
|
45
47
|
]) guide.addRow([line]);
|
|
46
48
|
return Buffer.from(await workbook.xlsx.writeBuffer());
|
|
47
49
|
}
|
|
@@ -128,7 +128,7 @@ async function readStructure(filePath, module) {
|
|
|
128
128
|
for (const sheet of sheets) {
|
|
129
129
|
const path = relationships.get(sheet.relId);
|
|
130
130
|
if (!path) continue; // Chart sheets have no business rows.
|
|
131
|
-
const result = { sheet: sheet.name, headers: [], rowCount: 0 };
|
|
131
|
+
const result = { sheet: sheet.name, headers: [], rowCount: 0, columnCount: 0 };
|
|
132
132
|
const format = sourceFormats(module).find(format => acceptsSheet(format, sheet.name));
|
|
133
133
|
const isMain = Boolean(format);
|
|
134
134
|
const sourceColumnLimit = format?.sourceColumnLimit ?? module.sourceColumnLimit;
|
|
@@ -175,7 +175,10 @@ async function readStructure(filePath, module) {
|
|
|
175
175
|
}
|
|
176
176
|
cell = null;
|
|
177
177
|
}
|
|
178
|
-
if (name === 'row' &&
|
|
178
|
+
if (name === 'row' && nonempty) {
|
|
179
|
+
result.columnCount = Math.max(result.columnCount, previousCol);
|
|
180
|
+
if (rowNumber > 1) result.rowCount++;
|
|
181
|
+
}
|
|
179
182
|
},
|
|
180
183
|
});
|
|
181
184
|
output.push(result);
|
|
@@ -2,8 +2,10 @@ import { readFile, writeFile, mkdir, realpath, rm } from 'node:fs/promises';
|
|
|
2
2
|
import { resolve, sep } from 'node:path';
|
|
3
3
|
import { createHash, randomUUID } from 'node:crypto';
|
|
4
4
|
import { gzipSync } from 'node:zlib';
|
|
5
|
+
import { hashWorkbook } from '../incremental/xlsx-rows.mjs';
|
|
5
6
|
import { buildSourcePayload } from '../real-data/source-payload.mjs';
|
|
6
|
-
import { applyOrganizationMapping, buildDecisionContract } from '../real-data/organization-mapping.mjs';
|
|
7
|
+
import { applyOrganizationMapping, buildDecisionContract, organizationMappingForSourceTemplates } from '../real-data/organization-mapping.mjs';
|
|
8
|
+
import { applyOrganizationRules, legacyScanRuleFormats, reviewForSourceTemplates } from '../review-engine.mjs';
|
|
7
9
|
import { packV10Payload, sanitizeV10Payload } from '../real-data/v10-template.mjs';
|
|
8
10
|
|
|
9
11
|
const IDS = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet'];
|
|
@@ -52,26 +54,39 @@ function scopeSanitizedPayload(input, scopePath) {
|
|
|
52
54
|
const clean = { ...input, sources: Object.fromEntries(Object.entries(input.sources).map(([id, value]) => [id, { ...value }])),
|
|
53
55
|
modules: { ...input.modules }, ...(input.decisionContract ? { decisionContract: clone(input.decisionContract) } : {}) };
|
|
54
56
|
if (scopePath.length) {
|
|
55
|
-
const
|
|
57
|
+
const allScans = clean.modules.scan?.records ?? [];
|
|
56
58
|
const allModules = clean.modules;
|
|
57
|
-
clean.modules = Object.fromEntries(
|
|
59
|
+
clean.modules = Object.fromEntries(Object.keys(allModules).map(id => [id, {
|
|
58
60
|
...allModules[id], records: allModules[id].records.filter(row => websiteScopeMatches(row.orgPath, scopePath)),
|
|
59
61
|
}]));
|
|
60
62
|
const terminalCodes = new Set(clean.modules.terminal.records.map(row => row.terminalCode).filter(Boolean));
|
|
61
63
|
// The existing terminal builder treats missing scan identity as unknown.
|
|
62
64
|
// Filtering away that evidence must not make a scoped effective count zero.
|
|
63
|
-
const uncertainIdentity =
|
|
65
|
+
const uncertainIdentity = allScans.some(row => !row.terminalCode
|
|
64
66
|
|| !fullPath(row.orgPath) && terminalCodes.has(row.terminalCode));
|
|
65
67
|
if (uncertainIdentity && clean.decisionContract?.terminalIdentity) {
|
|
66
68
|
clean.decisionContract.terminalIdentity = { status: 'pending', key: 'original-code' };
|
|
67
69
|
}
|
|
68
70
|
// Whole-source missing dates can invalidate common-period calculations.
|
|
69
71
|
// Preserve that gate when its evidence is outside the authorized payload.
|
|
70
|
-
if (['invoice', 'movement', '
|
|
72
|
+
if (['invoice', 'movement', 'inventory'].some(id => allModules[id].records.some(row => !row.date))
|
|
71
73
|
&& clean.decisionContract?.crossTableMetrics) {
|
|
72
74
|
clean.decisionContract.crossTableMetrics = { status: 'pending' };
|
|
73
75
|
}
|
|
74
76
|
}
|
|
77
|
+
if (clean.movementSources) clean.movementSources = Object.fromEntries(Object.entries(clean.movementSources).map(([id, item]) => {
|
|
78
|
+
const source = { ...item, originalName: null, rows: clean.modules.movement.records.filter(row => row.source === id).length };
|
|
79
|
+
if (scopePath.length && item.scopeLimits) {
|
|
80
|
+
const { organization, product, invalidTemplate } = item.scopeLimits;
|
|
81
|
+
// The default “all” is already scoped. Preserve uncertainty without publishing global counts.
|
|
82
|
+
source.scopeLimits = {
|
|
83
|
+
...(organization ? { organization: 1, scopedOrganization: true } : {}),
|
|
84
|
+
...(product ? { product: 1 } : {}),
|
|
85
|
+
...(invalidTemplate ? { invalidTemplate } : {}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
return [id, source];
|
|
89
|
+
}));
|
|
75
90
|
for (const source of Object.values(clean.sources)) source.originalName = '已授权数据来源';
|
|
76
91
|
return clean;
|
|
77
92
|
}
|
|
@@ -100,27 +115,39 @@ function refreshInventoryClassification(payload) {
|
|
|
100
115
|
/** Merge only successful candidate modules; all fallback provenance is local.
|
|
101
116
|
* Reapply current source-bound mappings/rules to the resulting combination.
|
|
102
117
|
*/
|
|
103
|
-
export function mergeWebsiteModules(candidate, previous, decisions = {}, previousManifest = null) {
|
|
118
|
+
export function mergeWebsiteModules(candidate, previous, decisions = {}, previousManifest = null, { uploads = [], scanReview } = {}) {
|
|
104
119
|
const payload = clone(candidate), modules = {}, localFailures = {};
|
|
105
120
|
payload.mode = 'real';
|
|
121
|
+
const sourceFor = (value, id) => value?.sources?.[id] ?? (id === 'movement' ? value?.sources?.distributor : null);
|
|
122
|
+
const sameSource = (a, b) => a?.sha256 === b?.sha256 && a?.uploadId === b?.uploadId;
|
|
106
123
|
for (const id of IDS) {
|
|
107
124
|
const next = payload.modules[id];
|
|
108
125
|
const failed = !ready(next);
|
|
109
126
|
if (failed) {
|
|
110
127
|
localFailures[id] = next?.reason || '该板块没有通过校验和计算。';
|
|
111
|
-
|
|
128
|
+
const canRetain = ready(previous?.modules?.[id]) && sourceFor(previous, id)
|
|
129
|
+
&& (id !== 'movement' || previous.movementSources && previous.modules.movement.records.every(row => ['dealer', 'distributor'].includes(row.source)));
|
|
130
|
+
if (canRetain) {
|
|
112
131
|
payload.modules[id] = clone(previous.modules[id]);
|
|
113
|
-
payload.sources[id] = clone(previous.sources[id]);
|
|
132
|
+
if (previous.sources[id]) payload.sources[id] = clone(previous.sources[id]);
|
|
133
|
+
else delete payload.sources[id];
|
|
114
134
|
payload.coverage[id] = clone(previous.coverage[id]);
|
|
135
|
+
if (id === 'movement') {
|
|
136
|
+
payload.movementSources = clone(previous.movementSources);
|
|
137
|
+
if (previous.sources.distributor) {
|
|
138
|
+
payload.sources.distributor = clone(previous.sources.distributor);
|
|
139
|
+
payload.modules.distributor = clone(previous.modules.distributor);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
115
142
|
} else {
|
|
116
143
|
delete payload.sources[id];
|
|
117
144
|
payload.modules[id] = { state: 'unavailable', records: [], metrics: {}, unavailable: [], warnings: [] };
|
|
118
145
|
payload.coverage[id] = { start: null, end: null, semantics: null };
|
|
119
146
|
}
|
|
120
147
|
}
|
|
121
|
-
const source = payload
|
|
122
|
-
const same = source && previous?.sources?.[id]
|
|
123
|
-
&& previous.sources
|
|
148
|
+
const source = sourceFor(payload, id);
|
|
149
|
+
const same = source && sameSource(previous?.sources?.[id], payload.sources[id])
|
|
150
|
+
&& (id !== 'movement' || sameSource(previous?.sources?.distributor, payload.sources.distributor));
|
|
124
151
|
modules[id] = {
|
|
125
152
|
status: !source || !ready(payload.modules[id]) ? 'unavailable' : failed || same ? 'retained' : 'updated',
|
|
126
153
|
uploadId: source?.uploadId ?? null,
|
|
@@ -129,15 +156,21 @@ export function mergeWebsiteModules(candidate, previous, decisions = {}, previou
|
|
|
129
156
|
};
|
|
130
157
|
}
|
|
131
158
|
// Remove a previous source-bound mapping before reevaluating the mixed set.
|
|
132
|
-
for (const id of IDS) for (const row of payload.modules[id]
|
|
159
|
+
for (const id of [...IDS, 'scan']) for (const row of payload.modules[id]?.records ?? []) {
|
|
133
160
|
if (Array.isArray(row.originalOrgPath)) {
|
|
134
161
|
row.orgPath = [...row.originalOrgPath];
|
|
135
162
|
row.org = Object.fromEntries(ORG.map((key, index) => [key, row.orgPath[index]]));
|
|
136
163
|
row.orgKey = JSON.stringify(row.orgPath);
|
|
137
164
|
}
|
|
138
165
|
delete row.organizationMapping;
|
|
166
|
+
delete row.reviewOrganization;
|
|
167
|
+
}
|
|
168
|
+
const mapping = organizationMappingForSourceTemplates(decisions?.organizationMapping, uploads);
|
|
169
|
+
const organizationMapping = applyOrganizationMapping(payload, mapping);
|
|
170
|
+
if (scanReview && payload.modules.scan) {
|
|
171
|
+
const report = applyOrganizationRules({ modules: { scan: payload.modules.scan }, sources: payload.sources }, scanReview);
|
|
172
|
+
if (report.conflicts.length) Object.assign(payload.modules.scan, { state: 'unavailable', records: [] });
|
|
139
173
|
}
|
|
140
|
-
const organizationMapping = applyOrganizationMapping(payload, decisions?.organizationMapping);
|
|
141
174
|
payload.decisionContract = buildDecisionContract(payload, decisions, organizationMapping);
|
|
142
175
|
refreshInventoryClassification(payload);
|
|
143
176
|
if (!IDS.some(id => ready(payload.modules[id]) && payload.modules[id].records.length)) {
|
|
@@ -179,11 +212,13 @@ export async function prepareWebsiteRelease({ dataDir, outputDir, previousReleas
|
|
|
179
212
|
onStage('正在读取各板块最新上传并独立校验、计算');
|
|
180
213
|
const built = await buildSourcePayload({ dataDir, decisionsFile: decisionBefore ? decisionsFile : undefined });
|
|
181
214
|
if (built.report.activeChangedDuringRead || built.report.decisionError) throw new Error('读取期间来源或业务决定发生变化,请重新准备网站版本。');
|
|
182
|
-
const
|
|
215
|
+
const sourceState = JSON.parse(stateBefore);
|
|
216
|
+
const oldFormats = await legacyScanRuleFormats(sourceState, dataDir);
|
|
217
|
+
const scanReview = reviewForSourceTemplates(sourceState.review, oldFormats, built.payload.sources.scan);
|
|
218
|
+
const merged = mergeWebsiteModules(built.payload, previous?.payload, decisions, previous?.manifest, { uploads: sourceState.uploads, scanReview });
|
|
183
219
|
// The original upload server records successful installations only. The
|
|
184
220
|
// website controller supplies its latest per-module attempt, so an invalid
|
|
185
221
|
// upload that left active unchanged is still visible as a retained version.
|
|
186
|
-
const sourceState = JSON.parse(stateBefore);
|
|
187
222
|
const uploadFailures = {};
|
|
188
223
|
for (const id of IDS) {
|
|
189
224
|
const attempt = uploadAttempts[id];
|
|
@@ -199,21 +234,20 @@ export async function prepareWebsiteRelease({ dataDir, outputDir, previousReleas
|
|
|
199
234
|
merged.payload.generatedAt = generatedAt;
|
|
200
235
|
const snapshot = () => {
|
|
201
236
|
const state = JSON.parse(stateBefore);
|
|
202
|
-
return JSON.stringify({ active: state.active, uploads: state.uploads.map(({ id, moduleId, sha256, validationContract }) => ({ id, moduleId, sha256, validationContract })) });
|
|
237
|
+
return JSON.stringify({ active: state.active, review: state.review, uploads: state.uploads.map(({ id, moduleId, sha256, validationContract }) => ({ id, moduleId, sha256, validationContract })) });
|
|
203
238
|
};
|
|
204
239
|
const expectedSnapshot = snapshot();
|
|
205
240
|
const verify = async () => {
|
|
206
241
|
const state = JSON.parse(await readFile(stateFile, 'utf8'));
|
|
207
|
-
const current = JSON.stringify({ active: state.active, uploads: state.uploads.map(({ id, moduleId, sha256, validationContract }) => ({ id, moduleId, sha256, validationContract })) });
|
|
242
|
+
const current = JSON.stringify({ active: state.active, review: state.review, uploads: state.uploads.map(({ id, moduleId, sha256, validationContract }) => ({ id, moduleId, sha256, validationContract })) });
|
|
208
243
|
if (current !== expectedSnapshot) throw new Error('准备网站版本期间上传资料发生变化,未生成可同步版本。');
|
|
209
244
|
const now = await optionalBytes(decisionsFile);
|
|
210
245
|
if ((now ? sha(now) : null) !== (decisionBefore ? sha(decisionBefore) : null)) throw new Error('准备网站版本期间业务决定发生变化,未生成可同步版本。');
|
|
211
246
|
// Recheck successfully-read new bytes. Cached retained modules have already
|
|
212
247
|
// been verified as a prior accepted local release and need no old-file read.
|
|
213
|
-
for (const id of
|
|
214
|
-
const source = built.payload.sources[id];
|
|
248
|
+
for (const [id, source] of Object.entries(built.payload.sources)) if (ready(built.payload.modules[id])) {
|
|
215
249
|
const file = await realpath(resolve(dataDir, 'uploads', source.uploadId, 'source.xlsx'));
|
|
216
|
-
if (!file.startsWith(`${resolve(dataDir, 'uploads')}${sep}`) ||
|
|
250
|
+
if (!file.startsWith(`${resolve(dataDir, 'uploads')}${sep}`) || await hashWorkbook(file) !== source.sha256) throw new Error('准备网站版本期间来源文件发生变化,未生成可同步版本。');
|
|
217
251
|
}
|
|
218
252
|
};
|
|
219
253
|
await verify();
|
|
@@ -230,7 +264,7 @@ export async function prepareWebsiteRelease({ dataDir, outputDir, previousReleas
|
|
|
230
264
|
const scope = scopes[index];
|
|
231
265
|
onStage(`正在生成授权范围数据 ${index + 1}/${scopes.length}`);
|
|
232
266
|
const scoped = scopeSanitizedPayload(sanitized, scope.path);
|
|
233
|
-
const bytes = gzipSync(Buffer.from(JSON.stringify(packV10Payload(scoped))), { level: 6 });
|
|
267
|
+
const bytes = gzipSync(Buffer.from(JSON.stringify(packV10Payload(scoped, { columns: false }))), { level: 6 });
|
|
234
268
|
if (bytes.length > 64 * 1024 * 1024) throw new Error('单个授权范围数据超过网站同步上限,请缩小数据范围。');
|
|
235
269
|
const info = { ...scope, sha256: sha(bytes), bytes: bytes.length };
|
|
236
270
|
const file = resolve(outputDir, 'objects', `${scope.id}.json.gz`);
|