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.
Files changed (38) hide show
  1. package/backend/incremental/flow.mjs +105 -34
  2. package/backend/incremental/jobs.mjs +11 -11
  3. package/backend/incremental/xlsx-rows.mjs +74 -3
  4. package/backend/modules/distributor/index.mjs +9 -6
  5. package/backend/modules/movement/index.mjs +17 -64
  6. package/backend/modules/scan/index.mjs +62 -0
  7. package/backend/modules/scan/legacy.mjs +21 -0
  8. package/backend/modules.mjs +2 -1
  9. package/backend/public/admin.css +9 -2
  10. package/backend/public/admin.js +74 -21
  11. package/backend/public/board.html +1 -1
  12. package/backend/public/board.js +2 -2
  13. package/backend/public/index.html +10 -10
  14. package/backend/real-data/decimal-sum.mjs +22 -0
  15. package/backend/real-data/generate-dashboard.mjs +18 -11
  16. package/backend/real-data/organization-mapping.mjs +31 -11
  17. package/backend/real-data/source-payload.mjs +163 -86
  18. package/backend/real-data/terminal-components.mjs +7 -7
  19. package/backend/real-data/terminal-structure.mjs +5 -5
  20. package/backend/real-data/v10-components.mjs +2 -2
  21. package/backend/real-data/v10-details.mjs +7 -62
  22. package/backend/real-data/v10-model.mjs +74 -71
  23. package/backend/real-data/v10-overview-data.mjs +14 -20
  24. package/backend/real-data/v10-overview.mjs +16 -6
  25. package/backend/real-data/v10-presentation.mjs +48 -27
  26. package/backend/real-data/v10-template.mjs +99 -71
  27. package/backend/review-engine.mjs +65 -35
  28. package/backend/review-service.mjs +28 -13
  29. package/backend/server.mjs +26 -17
  30. package/backend/store.mjs +3 -0
  31. package/backend/target-template.mjs +4 -2
  32. package/backend/validate-workbook.mjs +5 -2
  33. package/backend/web-sync/exporter.mjs +55 -21
  34. package/build-manifest.json +41 -38
  35. package/index.js +1 -1
  36. package/lib/tool-definitions.mjs +33 -15
  37. package/lib/tools.mjs +318 -85
  38. package/package.json +1 -1
@@ -3,6 +3,8 @@ import { resolve, relative, sep } from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { buildSourcePayload } from './source-payload.mjs';
5
5
  import { summarizeOrganizationMapping } from './organization-mapping.mjs';
6
+ import { hashWorkbook } from '../incremental/xlsx-rows.mjs';
7
+ import { uploadForModule, activeUploadId } from '../modules/scan/legacy.mjs';
6
8
  import { moduleDefinitions } from '../modules.mjs';
7
9
 
8
10
  const sha = value => createHash('sha256').update(value).digest('hex');
@@ -12,10 +14,11 @@ const titles = Object.fromEntries(moduleDefinitions.map(module => [module.id, mo
12
14
  export function captureSourceSnapshot(state, { includeCandidates = false } = {}) {
13
15
  if (!state?.active || Array.isArray(state.active) || !Array.isArray(state.uploads)) throw new Error('后台上传版本记录格式无效。');
14
16
  if (Object.keys(state.active).some(id => !ids.includes(id))) throw new Error('后台存在未知板块的有效版本记录。');
15
- const selected = includeCandidates ? { ...state.active, ...state.candidates } : state.active;
17
+ const selected = { ...state.active, ...(includeCandidates ? state.candidates : {}) };
18
+ selected.scan ??= activeUploadId(state, 'scan');
16
19
  return Object.fromEntries(ids.filter(id => selected[id]).map(id => {
17
20
  const uploadId = selected[id];
18
- const source = state.uploads.find(item => item.id === uploadId && item.moduleId === id);
21
+ const source = uploadForModule(state, id, uploadId);
19
22
  if (typeof uploadId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(uploadId) || !source || !/^[a-f0-9]{64}$/i.test(source.sha256 ?? '')) throw new Error(`${titles[id]}的有效上传版本记录不完整,请重新上传。`);
20
23
  return [id, { uploadId, sha256: source.sha256.toLowerCase(), validationContract: source.validationContract ?? null }];
21
24
  }));
@@ -31,7 +34,7 @@ export async function verifySourceSnapshot(dataDir, snapshot, { verifyFiles = tr
31
34
  const uploads = await realpath(resolve(dataDir, 'uploads'));
32
35
  for (const [id, source] of Object.entries(snapshot)) {
33
36
  const file = await realpath(resolve(uploads, source.uploadId, 'source.xlsx'));
34
- if (!file.startsWith(`${uploads}${sep}`) || sha(await readFile(file)) !== source.sha256) throw new Error(`${titles[id]}的上传文件与锁定来源不一致,请重新上传后生成。`);
37
+ if (!file.startsWith(`${uploads}${sep}`) || await hashWorkbook(file) !== source.sha256) throw new Error(`${titles[id]}的上传文件与锁定来源不一致,请重新上传后生成。`);
35
38
  }
36
39
  }
37
40
  await checkState();
@@ -91,7 +94,7 @@ export async function generateDashboard({ project, dataDir, sourceVersions, outp
91
94
  const verifyInputs = () => verifyGenerationSnapshot({ project, dataDir, sourceVersions, selection, codeSha256, decisionsSha256, reviewSha256 });
92
95
  if (!Object.keys(sourceVersions).length) throw new Error('请先上传并校验至少一个板块的真实资料。');
93
96
  await verifyInputs();
94
- onStage('正在读取最新有效上传并计算真实数据');
97
+ onStage('正在读取各板块数据并计算');
95
98
  const build = dependencies.buildSourcePayload ?? buildSourcePayload;
96
99
  const { payload, report } = await build({ dataDir, decisionsFile: decisionBefore ? decisionsFile : undefined, sourceVersions, allowPending, rowCache: true });
97
100
  if (!payload?.sources || !payload?.modules || report?.activeChangedDuringRead) throw new Error('有效上传版本读取不完整或已发生变化,请重新生成。');
@@ -100,9 +103,13 @@ export async function generateDashboard({ project, dataDir, sourceVersions, outp
100
103
  const skippedModules = [];
101
104
  for (const [id, expected] of Object.entries(sourceVersions)) {
102
105
  const source = payload.sources[id], module = payload.modules[id];
103
- if (!source && module?.state === 'unavailable' && /^工作簿结构校验失败/.test(module.reason || '')) {
104
- const reason = `${module.reason.replace(/。$/, '')}。该板块模板已更新,请按新模板重新上传;本次看板不含此板块。`;
105
- Object.assign(module, { reason, records: [], metrics: {} });
106
+ const failure = module?.dealerFailure ?? (module?.state === 'unavailable' ? module.reason : '');
107
+ if (module) delete module.dealerFailure;
108
+ if (!source && /^工作簿结构校验失败/.test(failure || '')) {
109
+ // 动销只有分销商一边时,经销商表跳过但分销商部分照常显示。
110
+ const merged = id === 'movement' && module.state !== 'unavailable';
111
+ const reason = `${failure.replace(/。$/, '')}。该板块模板已更新,请按新模板重新上传;${merged ? '本次动销只含分销商动销明细' : '本次看板不含此板块'}。`;
112
+ if (!merged) Object.assign(module, { reason, records: [], metrics: {} });
106
113
  (module.warnings ||= []).push(reason);
107
114
  skippedModules.push({ moduleId: id, title: titles[id], uploadId: expected.uploadId, reason });
108
115
  continue;
@@ -112,9 +119,9 @@ export async function generateDashboard({ project, dataDir, sourceVersions, outp
112
119
  }
113
120
  if (Object.keys(payload.sources).some(id => !sourceVersions[id])) throw new Error('计算结果出现未锁定来源,已停止生成。');
114
121
  const pendingModules = Object.keys(sourceVersions).filter(id => report.modules?.[id]?.reviewPending);
115
- if (!Object.entries(payload.modules).some(([id, module]) => sourceVersions[id] && module.records?.length) && !(allowPending && pendingModules.length)) throw new Error('没有可呈现的真实记录,请检查已上传资料。');
122
+ if (!Object.entries(payload.modules).some(([id, module]) => (sourceVersions[id] || id === 'movement' && sourceVersions.distributor) && id !== 'scan' && module.records?.length) && !(allowPending && pendingModules.length)) throw new Error('没有可呈现的真实记录,请检查已上传资料。');
116
123
  payload.mode = 'real';
117
- onStage('正在生成 v10 真实数据离线看板');
124
+ onStage('正在生成看板页面');
118
125
  const render = dependencies.renderV10Dashboard ?? (await import('./v10-template.mjs')).renderV10Dashboard;
119
126
  const rendered = await render(payload);
120
127
  if (typeof rendered?.html !== 'string' || !rendered.html.includes('</html>')) throw new Error('未生成有效的离线 HTML。');
@@ -129,7 +136,7 @@ export async function generateDashboard({ project, dataDir, sourceVersions, outp
129
136
  if (pendingModules.length) rendered.html = rendered.html.replace('<title>', '<title>待确认 · ');
130
137
  }
131
138
  await verifyInputs();
132
- onStage('正在保存成品并核对来源版本');
139
+ onStage('正在保存看板并做最后检查');
133
140
  await writeFile(resolve(outputDir, 'dashboard.html'), rendered.html, { flag: 'wx', mode: 0o600 });
134
141
  await writeFile(resolve(outputDir, 'diagnostics.json'), JSON.stringify(report), { flag: 'wx', mode: 0o600 });
135
142
  await verifyInputs();
@@ -139,7 +146,7 @@ export async function generateDashboard({ project, dataDir, sourceVersions, outp
139
146
  processingVersion: payload.processingVersion, payloadVersion: payload.schemaVersion, rendererVersion: rendered.rendererVersion,
140
147
  sources: payload.sources, moduleStates: rendered.moduleStates,
141
148
  processors: Object.fromEntries(ids.map(id => [id, { version: payload.processingVersion, state: payload.modules[id].state }])),
142
- moduleSummaries: Object.fromEntries(ids.map(id => [id, { state: payload.modules[id].state, records: payload.modules[id].records.length, metrics: payload.modules[id].metrics, warnings: payload.modules[id].warnings || [], unavailable: payload.modules[id].unavailable || [] }])),
149
+ moduleSummaries: Object.fromEntries(ids.map(id => [id, { state: payload.modules[id].state, records: payload.modules[id].metrics.records?.value ?? payload.modules[id].records.length, metrics: payload.modules[id].metrics, warnings: payload.modules[id].warnings || [], unavailable: payload.modules[id].unavailable || [] }])),
143
150
  pendingDecisions: payload.pendingDecisions,
144
151
  organizationMapping: summarizeOrganizationMapping(report.organizationMapping),
145
152
  };
@@ -1,5 +1,7 @@
1
+ import { isLegacyScanUpload } from '../modules/scan/legacy.mjs';
2
+
1
3
  const ORG_FIELDS = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
2
- const MODULES = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet'];
4
+ const MODULES = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet', 'scan'];
3
5
  const validPath = path => Array.isArray(path) && path.length === 6 && path.every(value => typeof value === 'string' && value.length <= 1000);
4
6
  const fullPath = path => validPath(path) && path.every(Boolean);
5
7
  const key = path => JSON.stringify(path);
@@ -15,6 +17,14 @@ const LIST_LIMIT = 500;
15
17
  const missingParents = path => validPath(path) && path.slice(0, 3).every(value => !value) && path.slice(3).every(Boolean);
16
18
  const shaOrNull = sha => typeof sha === 'string' && SHA.test(sha) ? sha.toLowerCase() : null;
17
19
 
20
+ export function organizationMappingForSourceTemplates(mapping, uploads) {
21
+ const oldScan = mapping?.sources?.movement;
22
+ const oldSha = shaOrNull(oldScan?.sourceSha256 ?? mapping?.reviewedAgainst?.sources?.movement);
23
+ if (!oldScan || !oldSha || !uploads.some(upload => isLegacyScanUpload(upload) && shaOrNull(upload.sha256) === oldSha)) return mapping;
24
+ const { movement, ...sources } = mapping.sources;
25
+ return { ...mapping, sources: { scan: movement, ...sources } };
26
+ }
27
+
18
28
  function reviewedAgainst(decision) {
19
29
  // version 2 stores the reviewed versions explicitly; version 1 kept the same
20
30
  // facts in referenceSources / sources.*.sourceSha256 (formerly gates).
@@ -61,13 +71,14 @@ export function applyOrganizationMapping(payload, decision) {
61
71
  report.contractVersion = decision.version;
62
72
  report.reviewedAgainst = reviewedAgainst(decision);
63
73
  report.status = 'applied';
64
- const referenceList = [...referencePaths].map(path => JSON.parse(path));
65
74
  for (const [id, source] of Object.entries(decision.sources)) {
66
75
  if (!MODULES.includes(id)) { report.errors.push(`组织映射含未知板块 ${String(id).slice(0, 40)},已忽略。`); continue; }
67
76
  if (payload.sources[id]?.sha256) report.actualSources.sources[id] = payload.sources[id].sha256;
68
77
  const detail = { configured: true, mappings: 0, appliedPaths: 0, appliedRows: 0, parentCompletionPaths: 0, parentCompletionRows: 0, aliasPaths: 0, aliasRows: 0, notInSourceMappings: 0, rejected: [], rejectedCount: 0, status: 'applied' };
69
78
  report.modules[id] = detail;
70
79
  const records = payload.modules[id]?.records || [];
80
+ const eligible = id === 'scan' ? new Set([...referencePaths, ...records.filter(row => fullPath(row.originalOrgPath)).map(row => key(row.originalOrgPath))]) : referencePaths;
81
+ const referenceList = [...eligible].map(path => JSON.parse(path));
71
82
  const present = new Map(); for (const row of records) { const from = key(row.originalOrgPath); present.set(from, (present.get(from) || 0) + 1); }
72
83
  const rejectedFroms = new Set();
73
84
  const reject = (mapping, reason) => {
@@ -93,7 +104,7 @@ export function applyOrganizationMapping(payload, decision) {
93
104
  if (new Set(list.map(mapping => key(mapping.to))).size !== 1 || list.length !== 1) { for (const mapping of list) reject(mapping, 'ambiguous'); continue; }
94
105
  const [mapping] = list;
95
106
  if (!present.has(from)) { detail.notInSourceMappings++; continue; } // (a) nothing to apply in this version
96
- if (!referencePaths.has(key(mapping.to))) { reject(mapping, 'target-missing'); continue; } // (b)
107
+ if (!eligible.has(key(mapping.to))) { reject(mapping, 'target-missing'); continue; } // (b)
97
108
  if (mapping.kind === 'parent-completion') { // (c) unique among current reference paths
98
109
  let matches = 0;
99
110
  for (const candidate of referenceList) if (mapping.from.every((value, index) => !value || value === candidate[index])) matches++;
@@ -136,8 +147,7 @@ export function summarizeOrganizationMapping(report) {
136
147
  }
137
148
 
138
149
  const RULES = {
139
- terminalIdentity: { status: 'confirmed', dependencies: ['terminal', 'movement'] },
140
- crossTableMetrics: { status: 'confirmed', dependencies: ['invoice', 'movement', 'opening', 'inventory'] },
150
+ terminalIdentity: { status: 'confirmed', dependencies: ['terminal', 'scan'] },
141
151
  banquetOpeningSubset: { status: 'not-guaranteed', dependencies: ['banquet', 'opening'] },
142
152
  };
143
153
  /** Make source bindings explicit in the exported decision contract. A source
@@ -154,13 +164,23 @@ export function buildDecisionContract(payload, decisions, mappingReport) {
154
164
  };
155
165
  for (const [name, rule] of Object.entries(RULES)) {
156
166
  const configured = decisions?.businessRules?.[name];
157
- // Visit inventory has no amount/product relation. Its disabled estimate must
158
- // not invalidate unchanged invoice/movement/opening source-bound ratios.
159
- const dependencies = name === 'crossTableMetrics' && payload.modules.inventory.inventoryMode === 'visit-history'
160
- ? rule.dependencies.filter(id => id !== 'inventory') : rule.dependencies;
161
- const valid = configured?.status === rule.status && isObject(configured.sources) && dependencies.every(id => shaMatches(payload, id, configured.sources[id]));
162
- contract[name] = { status: valid ? rule.status : 'pending', sourceMatches: Object.fromEntries(dependencies.map(id => [id, shaMatches(payload, id, configured?.sources?.[id])])), sources: valid ? Object.fromEntries(dependencies.map(id => [id, configured.sources[id].toLowerCase()])) : {} };
167
+ const dependencies = rule.dependencies;
168
+ const configuredSha = id => configured?.sources?.[id] ?? (name === 'terminalIdentity' && id === 'scan' ? configured?.sources?.movement : null);
169
+ const matches = id => shaMatches(payload, id, configuredSha(id));
170
+ const valid = configured?.status === rule.status && isObject(configured.sources) && dependencies.every(matches);
171
+ contract[name] = { status: valid ? rule.status : 'pending', sourceMatches: Object.fromEntries(dependencies.map(id => [id, matches(id)])),
172
+ sources: valid ? Object.fromEntries(dependencies.map(id => [id, configuredSha(id).toLowerCase()])) : {} };
163
173
  if (name === 'terminalIdentity') contract[name].key = 'original-code';
164
174
  }
175
+ // The 2026-12-03 contract confirms the new amount relationships. Bind them
176
+ // to the current validated sources, with inventory required only for its own estimate.
177
+ const movementIds = { movement: 'dealer', distributor: 'distributor' };
178
+ const available = id => shaMatches(payload, id, payload.sources[id]?.sha256)
179
+ && (!movementIds[id] || !payload.movementSources || Boolean(payload.movementSources[movementIds[id]]))
180
+ && (id !== 'inventory' || payload.modules.inventory.inventoryMode !== 'visit-history');
181
+ const sources = Object.fromEntries(['movement', 'distributor', 'invoice', 'inventory']
182
+ .filter(available).map(id => [id, payload.sources[id].sha256]));
183
+ const confirmed = (sources.movement || sources.distributor) && (sources.invoice || sources.inventory);
184
+ contract.crossTableMetrics = { status: confirmed ? 'confirmed' : 'pending', sources: confirmed ? sources : {} };
165
185
  return contract;
166
186
  }