dsh-data-dashboard 0.0.0-stage → 0.1.5

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 (71) hide show
  1. package/README.md +35 -2
  2. package/assets/theater-board.svg +1 -0
  3. package/backend/incremental/flow.mjs +492 -0
  4. package/backend/incremental/jobs.mjs +58 -0
  5. package/backend/incremental/xlsx-rows.mjs +145 -0
  6. package/backend/job-worker.mjs +22 -0
  7. package/backend/modules/banquet/index.mjs +46 -0
  8. package/backend/modules/inventory/index.mjs +45 -0
  9. package/backend/modules/inventory/legacy-fields.mjs +83 -0
  10. package/backend/modules/invoice/index.mjs +72 -0
  11. package/backend/modules/movement/index.mjs +68 -0
  12. package/backend/modules/opening/index.mjs +48 -0
  13. package/backend/modules/target/index.mjs +45 -0
  14. package/backend/modules/terminal/index.mjs +114 -0
  15. package/backend/modules.mjs +12 -0
  16. package/backend/public/admin.css +220 -0
  17. package/backend/public/admin.js +772 -0
  18. package/backend/public/board.css +70 -0
  19. package/backend/public/board.html +50 -0
  20. package/backend/public/board.js +153 -0
  21. package/backend/public/index.html +113 -0
  22. package/backend/public/org-mapping.js +49 -0
  23. package/backend/public/review.css +5 -0
  24. package/backend/public/review.js +452 -0
  25. package/backend/real-data/generate-dashboard.mjs +137 -0
  26. package/backend/real-data/inventory-history.mjs +316 -0
  27. package/backend/real-data/organization-mapping.mjs +166 -0
  28. package/backend/real-data/source-payload.mjs +459 -0
  29. package/backend/real-data/terminal-components.mjs +280 -0
  30. package/backend/real-data/terminal-structure.css +105 -0
  31. package/backend/real-data/terminal-structure.mjs +276 -0
  32. package/backend/real-data/v10-components.mjs +112 -0
  33. package/backend/real-data/v10-details.css +18 -0
  34. package/backend/real-data/v10-details.mjs +251 -0
  35. package/backend/real-data/v10-layout.css +27 -0
  36. package/backend/real-data/v10-model.mjs +568 -0
  37. package/backend/real-data/v10-overview-data.mjs +253 -0
  38. package/backend/real-data/v10-overview.css +370 -0
  39. package/backend/real-data/v10-overview.mjs +340 -0
  40. package/backend/real-data/v10-presentation.mjs +354 -0
  41. package/backend/real-data/v10-shell.html +1097 -0
  42. package/backend/real-data/v10-template.mjs +353 -0
  43. package/backend/recognition/fingerprint.mjs +32 -0
  44. package/backend/recognition/headers.mjs +2 -0
  45. package/backend/recognition/module-definition.mjs +4 -0
  46. package/backend/recognition/result.mjs +29 -0
  47. package/backend/recognition/upload-limits.mjs +14 -0
  48. package/backend/review-engine.mjs +364 -0
  49. package/backend/review-service.mjs +182 -0
  50. package/backend/server.mjs +569 -0
  51. package/backend/store.mjs +68 -0
  52. package/backend/target-template.mjs +47 -0
  53. package/backend/validate-workbook.mjs +251 -0
  54. package/backend/web-sync/README.md +37 -0
  55. package/backend/web-sync/client.mjs +63 -0
  56. package/backend/web-sync/exporter.mjs +260 -0
  57. package/backend/web-sync/local.html +34 -0
  58. package/backend/web-sync/server.mjs +147 -0
  59. package/build-manifest.json +80 -0
  60. package/client.js +54 -0
  61. package/cordis.patch.yml +3 -0
  62. package/index.js +117 -0
  63. package/lib/dist-manifest.mjs +19 -0
  64. package/lib/market-index.mjs +56 -0
  65. package/lib/package-audit.mjs +34 -0
  66. package/lib/settings.mjs +71 -0
  67. package/lib/tool-definitions.mjs +56 -0
  68. package/lib/tools.mjs +255 -0
  69. package/locale/en.json +6 -0
  70. package/locale/zh.json +6 -0
  71. package/package.json +71 -4
@@ -0,0 +1,459 @@
1
+ import { readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
2
+ import { resolve, sep } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { promisify } from 'node:util';
5
+ import { gunzip, gzip } from 'node:zlib';
6
+ import ExcelJS from 'exceljs';
7
+ import { validateWorkbook } from '../validate-workbook.mjs';
8
+ import { normalizeHeader, moduleById } from '../modules.mjs';
9
+ import { applyOrganizationMapping, buildDecisionContract } from './organization-mapping.mjs';
10
+ import { processInventoryHistory } from './inventory-history.mjs';
11
+ import { targetColumns } from '../modules/target/index.mjs';
12
+ import { inspectRows, resolveInspection, applyDuplicateDecisions, applyOrganizationRules } from '../review-engine.mjs';
13
+ import { lineageShas } from '../incremental/flow.mjs';
14
+
15
+ const MODULES = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet', 'target'];
16
+ const PENDING = {
17
+ invoice: ['invoiceTarget', 'invoiceQuantityConversion'],
18
+ movement: ['invoiceMovementRelationship'],
19
+ opening: ['openingMovementConversion', 'banquetOpeningOverlap'],
20
+ terminal: ['crossTableTerminalIdentity'],
21
+ inventory: ['inventoryHistory', 'inventoryValuationBasis', 'inventorySellableMonthsEstimate'],
22
+ banquet: ['rewardAdditivity', 'banquetOpeningOverlap'],
23
+ target: [],
24
+ };
25
+ const metric = (value, unit, status = 'available', reason) => ({ value, status, unit, ...(reason ? { reason } : {}) });
26
+ const text = value => value === null || value === undefined ? '' : String(value).trim();
27
+ function scalar(value) {
28
+ if (value === null || value === undefined) return null;
29
+ if (value instanceof Date) return value.toISOString();
30
+ if (typeof value !== 'object') return value;
31
+ if ('formula' in value || 'sharedFormula' in value) return scalar(value.result);
32
+ if (value.richText) return value.richText.map(part => part.text).join('');
33
+ if ('text' in value) return value.text;
34
+ return null;
35
+ }
36
+ function number(value) {
37
+ if (value === null || value === undefined || text(value) === '') return null;
38
+ if (typeof value === 'boolean') return null;
39
+ const raw = text(value);
40
+ if (raw.includes(',') && !/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/.test(raw)) return null;
41
+ const source = raw.replaceAll(',', '');
42
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(source)) return null;
43
+ const result = Number(source);
44
+ return Number.isFinite(result) ? result : null;
45
+ }
46
+ // Sum decimal source values exactly before returning JSON numbers. This avoids
47
+ // accumulated binary floating-point noise in currency and keeps source signs.
48
+ function sum(values) {
49
+ let total = 0n, scale = 0;
50
+ for (const value of values) {
51
+ if (value === null || value === undefined) continue;
52
+ const match = String(value).match(/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i);
53
+ if (!match) continue;
54
+ let digits = BigInt(`${match[1]}${match[2]}${match[3] ?? ''}`);
55
+ let nextScale = (match[3]?.length ?? 0) - Number(match[4] ?? 0);
56
+ if (nextScale < 0) { digits *= 10n ** BigInt(-nextScale); nextScale = 0; }
57
+ if (nextScale > scale) { total *= 10n ** BigInt(nextScale - scale); scale = nextScale; }
58
+ total += digits * 10n ** BigInt(scale - nextScale);
59
+ }
60
+ return Number(total) / 10 ** scale;
61
+ }
62
+ function date(value, date1904 = false) {
63
+ if (typeof value === 'number' && value > 0 && value < 100000) {
64
+ value = new Date(Date.UTC(date1904 ? 1904 : 1899, date1904 ? 0 : 11, date1904 ? 1 : 30) + Math.floor(value) * 86400000).toISOString();
65
+ }
66
+ const match = text(value).match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[ T].*)?$/);
67
+ if (!match) return null;
68
+ const result = `${match[1]}-${match[2].padStart(2, '0')}-${match[3].padStart(2, '0')}`;
69
+ const parsed = new Date(`${result}T00:00:00Z`);
70
+ return Number.isFinite(parsed.valueOf()) && parsed.toISOString().slice(0, 10) === result ? result : null;
71
+ }
72
+ function fieldAccess(headers, values) {
73
+ const columns = new Map(headers.map((header, index) => [normalizeHeader(header), index]));
74
+ return (...names) => {
75
+ for (const name of names) {
76
+ const index = columns.get(normalizeHeader(name));
77
+ if (index !== undefined) return values[index];
78
+ }
79
+ return null;
80
+ };
81
+ }
82
+ function organization(get, moduleId) {
83
+ const headers = {
84
+ invoice: ['销售大区', '办事处', '客户主任单元'],
85
+ movement: ['大区名称', '办事处名称', '主任单元名称'],
86
+ opening: ['产品所属-大区', '产品所属-办事处', '产品所属-主任单元'],
87
+ terminal: ['大区', '办事处', '主任单元'],
88
+ inventory: ['大区名称', '办事处名称', '单元名称'],
89
+ banquet: ['大区', '办事处', '主任单元'],
90
+ target: ['大区', '办事处', '主任单元'],
91
+ }[moduleId];
92
+ const org = {
93
+ marketingCompany: text(get('营销公司名称')), businessUnit: text(get('事业部名称', '事业部')),
94
+ theater: text(get('战区名称')), region: text(get(headers[0])), office: text(get(headers[1])), unit: text(get(headers[2])),
95
+ };
96
+ return { org, orgPath: Object.values(org), orgKey: JSON.stringify(Object.values(org)) };
97
+ }
98
+ function normalizedRecord(moduleId, row, workbook) {
99
+ const get = row.get;
100
+ const common = { sourceRef: { sheet: row.sheet, row: row.row }, ...organization(get, moduleId), date: null };
101
+ const product = () => ({ productCode: text(get('产品编码')), productName: text(get('产品名称')), brand: text(get('品牌', '品牌名称')) || null, category: text(get('品类', '品类名称')) || null });
102
+ const dealer = () => ({ dealerCode: text(get('经销商编码', '签约经销商编码')), dealerName: text(get('经销商名称', '签约经销商')), dealerType: text(get('经销商类型')) });
103
+ const parseDate = value => date(value, workbook.properties.date1904);
104
+ if (moduleId === 'invoice') return { ...common, ...product(), ...dealer(), date: parseDate(get('业务日期')), amount: number(get('发票金额')), quantity: number(get('计价数量')), quantityUnit: text(get('计价单位')), documentType: text(get('单据类型')), documentCode: text(get('单据编码')), documentLine: text(get('单据行号')), grade: text(get('经销商分级')) };
105
+ if (moduleId === 'movement') {
106
+ const quantityUnit = text(get('单品单位')), quantity = number(get('扫码数量(瓶)'));
107
+ return { ...common, ...product(), ...dealer(), variety: text(get('品种名称')), date: parseDate(get('扫码日期')), amount: number(get('扫码金额')), quantity, quantityUnit, bottles: quantityUnit === '瓶' ? quantity : null, boxes: quantityUnit === '盒' ? quantity : null, cases: number(get('扫码件数')), terminalCode: text(get('售点编码')), terminalName: text(get('售点名称')), channel: text(get('渠道类型')), movementType: text(get('出入库名称')), orderCode: text(get('订单编码')) };
108
+ }
109
+ if (moduleId === 'opening') return { ...common, date: parseDate(get('抽奖日期')), bottles: number(get('开瓶瓶数')), amount: number(get('开瓶金额')), city: text(get('开瓶城市')), amountMeaning: '现金红包奖励', amountUnit: '元' };
110
+ if (moduleId === 'terminal') return { ...common, ...dealer(), date: parseDate(get('签约日期')), signDate: parseDate(get('签约日期')), startDate: parseDate(get('协议开始日期')), endDate: parseDate(get('协议结束日期')), agreementId: text(get('协议编号')), terminalCode: text(get('网点编号')), terminalName: text(get('网点名称')), type: text(get('网点类型')), series: text(get('协议名称')), star: text(get('星级')), signLevel: text(get('签约等级')), signVariety: text(get('签约品种')), manualClosed: text(get('是否手工关闭')), approvalStatus: text(get('审批状态')), signingStatus: text(get('签约状态')) };
111
+ if (moduleId === 'inventory') {
112
+ const counted = number(get('库存瓶数(盘点)')), system = number(get('提交时实时库存数(系统)'));
113
+ const signedVariance = counted === null || system === null ? null : sum([counted, -system]);
114
+ return { ...common, ...product(), ...dealer(), date: parseDate(get('提交时间')), submittedAt: get('提交时间'), stocktakeCode: text(get('盘点编码')), counted, system, countAmount: number(get('盘点库存金额')), stockAmount: number(get('盘点库存金额')), systemAmount: number(get('提交时实时库存数金额')), sourceVariance: number(get('偏差数量')), absoluteVariance: signedVariance === null ? null : Math.abs(signedVariance), signedVariance, varianceFlag: text(get('是否存在盘点偏差')), safety: text(get('安全库存')) };
115
+ }
116
+ return { ...common, events: number(get('执行场次')), bottles: number(get('开瓶数量')), reward: number(get('售点推荐奖励')) };
117
+ }
118
+ // One target record per filled target cell (wide layout) or per row (long layout).
119
+ function targetRecords(row, headers, workbook) {
120
+ const common = { sourceRef: { sheet: row.sheet, row: row.row }, ...organization(row.get, 'target'), date: null };
121
+ const date1904 = workbook.properties.date1904, columns = targetColumns(headers);
122
+ const records = columns.map(column => ({ ...common, sourceColumn: column.header, ...targetFields(row.get('年月'), column.label, row.values[column.index], date1904) }));
123
+ if (row.get('指标') !== null || row.get('目标值') !== null) records.push({ ...common, ...targetFields(row.get('年月'), row.get('指标'), row.get('目标值'), date1904) });
124
+ return records;
125
+ }
126
+ const TARGET_METRICS = [['发票金额', 'invoice', 'amount', '元'], ['动销金额', 'movement', 'amount', '元'], ['开瓶瓶数', 'opening', 'bottles', '瓶']];
127
+ export function targetMonth(value, date1904 = false) {
128
+ if (typeof value === 'number' && value > 0 && value < 100000) return date(value, date1904)?.slice(0, 7) ?? null;
129
+ const raw = text(value).replace(/\s+/g, '');
130
+ const iso = raw.match(/^(\d{4})-(\d{2})-(\d{2})T/);
131
+ if (iso) return date(raw)?.slice(0, 7) ?? null;
132
+ const match = raw.match(/^(\d{4})(?:[-/.年]?)(\d{1,2})(?:月)?(?:[-/.](\d{1,2})日?)?$/);
133
+ if (!match) return null;
134
+ const month = Number(match[2]);
135
+ return month >= 1 && month <= 12 ? `${match[1]}-${String(month).padStart(2, '0')}` : null;
136
+ }
137
+ export function targetFields(monthValue, metricValue, amountValue, date1904 = false) {
138
+ const label = text(metricValue).replace(/\s+/g, '').replace(/[()]/g, match => match === '(' ? '(' : ')');
139
+ const unitMatch = label.match(/((元|万元|瓶))$/), name = unitMatch ? label.slice(0, unitMatch.index) : label;
140
+ const known = TARGET_METRICS.find(([title]) => title === name);
141
+ const unit = unitMatch?.[1] ?? known?.[3] ?? null, raw = number(amountValue);
142
+ const valid = known && (known[3] === '瓶' ? unit === '瓶' : ['元', '万元'].includes(unit));
143
+ const value = raw === null || !valid ? null : unit === '万元' ? Math.round(raw * 10000 * 100) / 100 : raw;
144
+ const month = targetMonth(monthValue, date1904);
145
+ return { month, date: month ? `${month}-01` : null, metric: valid ? known[1] : null, metricLabel: text(metricValue), field: valid ? known[2] : null, value,
146
+ issue: text(amountValue) === '' ? '目标值为空' : !month ? '年月无法识别' : !known ? '指标名称不在可选范围' : !valid ? '指标单位不受支持' : raw === null ? '目标值不是有效数字' : raw < 0 ? '目标值为负数' : null };
147
+ }
148
+ function totals(records, field, unit) {
149
+ const missing = records.filter(row => row[field] === null).length;
150
+ return missing ? metric(null, unit, 'missing', `${missing} 行缺少可计算的源值;不补零`) : metric(sum(records.map(row => row[field])), unit);
151
+ }
152
+ function computeMetrics(moduleId, records) {
153
+ const result = { records: metric(records.length, '行') };
154
+ const fields = {
155
+ invoice: { amount: '元' }, movement: { amount: '元', cases: '源件数' }, opening: { bottles: '瓶', amount: '元(现金红包)' },
156
+ terminal: {}, target: {}, inventory: { counted: '瓶(本次导出记录合计)', system: '瓶(本次导出记录合计)', countAmount: '元', systemAmount: '元', absoluteVariance: '瓶' }, banquet: { events: '场', bottles: '瓶' },
157
+ }[moduleId];
158
+ for (const [field, unit] of Object.entries(fields)) result[field] = totals(records, field, unit);
159
+ if (moduleId === 'invoice' || moduleId === 'movement') {
160
+ const complete = records.every(row => row.amount !== null);
161
+ result.positiveAmount = metric(complete ? sum(records.filter(row => row.amount > 0).map(row => row.amount)) : null, '元', complete ? 'available' : 'missing');
162
+ result.negativeAmount = metric(complete ? sum(records.filter(row => row.amount < 0).map(row => row.amount)) : null, '元', complete ? 'available' : 'missing');
163
+ }
164
+ if (moduleId === 'movement') {
165
+ for (const [key, unit] of [['bottles', '瓶'], ['boxes', '盒']]) result[key] = totals(records.filter(row => row.quantityUnit === unit), key, unit);
166
+ result.unknownUnitRows = metric(records.filter(row => !['瓶', '盒'].includes(row.quantityUnit)).length, '行');
167
+ }
168
+ if (moduleId === 'terminal') {
169
+ const missingCode = records.some(row => !row.terminalCode);
170
+ result.terminalCount = metric(missingCode ? null : new Set(records.map(row => row.terminalCode)).size, '终端', missingCode ? 'missing' : 'available');
171
+ result.agreementCount = metric(records.length, '协议');
172
+ }
173
+ if (moduleId === 'banquet') result.reward = metric(null, '元', 'pending', '奖励字段的可加总含义尚未确认');
174
+ if (moduleId === 'target') {
175
+ result.invalidRows = metric(records.filter(row => row.issue).length, '行');
176
+ for (const [, id] of TARGET_METRICS) result[`${id}Rows`] = metric(records.filter(row => !row.issue && row.metric === id).length, '行');
177
+ }
178
+ return result;
179
+ }
180
+ function coverage(moduleId, records, decisions, sha256) {
181
+ if (moduleId === 'banquet') {
182
+ const decision = decisions?.banquet;
183
+ const start = date(decision?.start ?? decision?.period?.start), end = date(decision?.end ?? decision?.period?.end);
184
+ const confirmed = decision?.sourceSha256 === sha256 && start && end && start <= end;
185
+ return { start: confirmed ? start : null, end: confirmed ? end : null, semantics: 'fixed-source-period', status: confirmed ? 'confirmed' : 'pending', productFilter: false };
186
+ }
187
+ const dates = records.map(row => row.date).filter(Boolean).sort();
188
+ return { start: dates[0] ?? null, end: dates.at(-1) ?? null, semantics: ({ target: 'target-month', invoice: 'business-date', movement: 'scan-date', opening: 'draw-date', terminal: 'signed-date-not-historical-validity', inventory: 'stocktake-record-date-not-historical-stock' })[moduleId], status: dates.length === records.length ? 'observed' : 'partial', productFilter: ['invoice', 'movement', 'inventory'].includes(moduleId) };
189
+ }
190
+ function comparable(value, expected) {
191
+ if (typeof expected === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(expected)) return date(value) === expected;
192
+ if (number(value) !== null && number(expected) !== null) return number(value) === number(expected);
193
+ return text(value) === text(expected);
194
+ }
195
+ function invoiceRows(rows, decisions, sha256, sheet) {
196
+ const decision = decisions?.invoice ?? decisions;
197
+ if (!decision || decision.sourceSha256 !== sha256 || decision.sheet !== sheet || !Array.isArray(decision.duplicateDisposition?.groups)) {
198
+ // A new ordinary export does not need an empty file-specific decision.
199
+ // This key only detects candidates requiring review; it never deduplicates
200
+ // a new file or transfers an old row-number exclusion to new bytes.
201
+ const seen = new Set();
202
+ for (const row of rows) {
203
+ const parts = ['单据类型', '单据编码', '单据行号'].map(field => text(row.get(field)));
204
+ if (parts.some(value => !value)) throw new Error('新发票来源有单据类型、编码或行号缺失,无法核对重复候选;请核实后重新上传。');
205
+ const key = JSON.stringify(parts);
206
+ if (seen.has(key)) throw new Error('当前发票版本存在重复候选,且没有匹配当前文件的处置决定;请确认保留记录后重新生成,旧文件的行号规则未套用。');
207
+ seen.add(key);
208
+ }
209
+ return { rows, excludedRows: [], checks: [], policy: 'unique-document-candidates-source-values' };
210
+ }
211
+ const excluded = new Set(), kept = new Set(), checks = [];
212
+ for (const group of decision.duplicateDisposition.groups) {
213
+ const keep = group.keep, remove = group.excludeInFutureProcessedResult;
214
+ for (const item of [keep, remove]) {
215
+ const row = rows.find(row => row.row === item?.row);
216
+ if (!row || !item.values || !Object.entries(item.values).every(([key, value]) => comparable(row.get(key), value))) throw new Error('发票来源绑定决定与具体行字段不一致,已停止该板块计算。');
217
+ }
218
+ if (keep.row === remove.row || excluded.has(keep.row) || kept.has(remove.row) || excluded.has(remove.row)) throw new Error('发票去重决定相互冲突,已停止该板块计算。');
219
+ kept.add(keep.row); excluded.add(remove.row); checks.push({ keptRow: keep.row, excludedRow: remove.row });
220
+ }
221
+ return { rows: rows.filter(row => !excluded.has(row.row)), excludedRows: [...excluded], checks };
222
+ }
223
+ function terminalRows(rows, headers, decisions, sha256, sheet) {
224
+ const idColumn = headers.findIndex(header => normalizeHeader(header) === normalizeHeader('协议编号'));
225
+ const groups = new Map(), excluded = new Set();
226
+ for (const row of rows) {
227
+ const key = JSON.stringify(row.values.filter((_, index) => index !== idColumn));
228
+ const group = groups.get(key) ?? []; group.push(row); groups.set(key, group);
229
+ }
230
+ for (const group of groups.values()) {
231
+ if (group.length < 2) continue;
232
+ const ids = group.map(row => text(row.values[idColumn]));
233
+ const decision = decisions?.terminal;
234
+ const reviewed = decision?.sourceSha256 === sha256 && decision.sheet === sheet && decision.duplicateGroups?.some(entry => Array.isArray(entry.agreementIds) && JSON.stringify([...entry.agreementIds].sort()) === JSON.stringify([...ids].sort()));
235
+ if (!reviewed) throw new Error('当前签约版本存在 A–AJ 重复候选,且没有匹配该文件的处置决定;请核实后重新生成,旧来源的重复规则未套用。');
236
+ if (!ids.every(id => /^SD\d{13}$/.test(id)) || new Set(ids).size !== ids.length) throw new Error('重复协议编号不可按已确认的 SD 加 13 位数字规则比较,已停止生成。');
237
+ const winner = group.reduce((best, row) => BigInt(text(row.values[idColumn]).slice(2)) > BigInt(text(best.values[idColumn]).slice(2)) ? row : best);
238
+ for (const row of group) if (row !== winner) excluded.add(row.row);
239
+ }
240
+ return { rows: rows.filter(row => !excluded.has(row.row)), excludedRows: [...excluded] };
241
+ }
242
+ function diagnostics(payload) {
243
+ const records = id => payload.modules[id].records;
244
+ const organizationAliases = new Map();
245
+ for (const id of MODULES) for (const row of records(id)) {
246
+ const shortened = row.orgPath.map(value => value.replace(/(舍得虚拟)/g, ''));
247
+ const key = JSON.stringify(shortened), current = organizationAliases.get(key) ?? new Map();
248
+ current.set(row.orgKey, row.orgPath); organizationAliases.set(key, current);
249
+ }
250
+ const collisions = [...organizationAliases.values()].filter(group => group.size > 1).map(group => [...group.values()]);
251
+ const siteOrgs = new Map(), outletOrgs = new Map();
252
+ for (const [id, target] of [['terminal', siteOrgs], ['movement', outletOrgs]]) for (const row of records(id)) {
253
+ if (!row.terminalCode) continue;
254
+ const orgs = target.get(row.terminalCode) ?? new Set(); orgs.add(row.orgKey); target.set(row.terminalCode, orgs);
255
+ }
256
+ const overlap = [...siteOrgs.keys()].filter(code => outletOrgs.has(code));
257
+ const inconsistent = overlap.filter(code => [...siteOrgs.get(code)].some(org => !outletOrgs.get(code).has(org)) || [...outletOrgs.get(code)].some(org => !siteOrgs.get(code).has(org)));
258
+ const productMap = new Map();
259
+ for (const id of ['invoice', 'movement']) for (const row of records(id)) {
260
+ if (!row.productCode || !row.brand || !row.category) continue;
261
+ const values = productMap.get(row.productCode) ?? new Map(); values.set(JSON.stringify([row.brand, row.category]), { brand: row.brand, category: row.category }); productMap.set(row.productCode, values);
262
+ }
263
+ let unmapped = 0, conflicted = 0, mapped = 0;
264
+ for (const row of records('inventory')) {
265
+ const candidates = productMap.get(row.productCode);
266
+ if (candidates?.size === 1) { Object.assign(row, [...candidates.values()][0]); row.classificationStatus = 'unique-product-code'; mapped++; }
267
+ else { row.brand = null; row.category = null; row.classificationStatus = candidates?.size > 1 ? 'conflict' : 'unmapped'; if (candidates?.size > 1) conflicted++; else unmapped++; }
268
+ }
269
+ return { organizationAliases: { collisionCount: collisions.length, candidates: collisions }, terminalIdentity: { siteCodes: siteOrgs.size, outletCodes: outletOrgs.size, intersectionCount: overlap.length, organizationInconsistentCount: inconsistent.length, inconsistentCodes: inconsistent, status: 'diagnostic-only-not-an-identity-confirmation' }, productClassification: { mappedRows: mapped, unmappedRows: unmapped, conflictRows: conflicted, conflictingCodes: [...productMap].filter(([, values]) => values.size > 1).map(([code]) => code) } };
270
+ }
271
+
272
+ /** Read an immutable active-upload snapshot without changing the source store.
273
+ * Decisions are external: either the original invoice decision object, or
274
+ * { invoice: <object>, banquet: { sourceSha256, start, end, includeOrganizationPlaceholders: true } }.
275
+ * Internal records retain provenance; the HTML exporter must project only the
276
+ * fields needed by the UI and must not publish this local diagnostic report.
277
+ */
278
+ // Parsed source rows are cached beside each upload, keyed by the file SHA-256, the
279
+ // module's validation contract and this parser's own source, so an unchanged
280
+ // source is not read from Excel again. Values are the same scalar() results.
281
+ const ROW_CACHE_FILE = 'rows-cache.json.gz';
282
+ const ROW_CACHE_VERSION = 1;
283
+ let parserSourceSha;
284
+ const gzipAsync = promisify(gzip), gunzipAsync = promisify(gunzip);
285
+ async function rowCacheKey(moduleId, sha256) {
286
+ parserSourceSha ??= createHash('sha256').update(await readFile(new URL(import.meta.url))).digest('hex');
287
+ const { validationFingerprint } = await import('../recognition/fingerprint.mjs');
288
+ return createHash('sha256').update(JSON.stringify([ROW_CACHE_VERSION, moduleId, sha256, await validationFingerprint(moduleId), parserSourceSha])).digest('hex');
289
+ }
290
+ // JSON cannot carry -0; every other scalar() value (string, finite number, boolean, null) round-trips exactly.
291
+ const encodeValue = value => Object.is(value, -0) ? { negativeZero: true } : value;
292
+ const decodeValue = value => value !== null && typeof value === 'object' ? (value.negativeZero ? -0 : null) : value;
293
+ async function readSourceRows({ file, buffer, moduleId, sha256, cacheFile }) {
294
+ // Only the backend's own generation opts in; previews and exports never write to the data directory.
295
+ const key = cacheFile ? await rowCacheKey(moduleId, sha256) : null;
296
+ if (cacheFile) try {
297
+ const cached = JSON.parse((await gunzipAsync(await readFile(cacheFile))).toString('utf8'));
298
+ if (cached.key === key && cached.sha256 === sha256 && Array.isArray(cached.headers) && Array.isArray(cached.rows)) {
299
+ const { headers } = cached;
300
+ const rows = cached.rows.map(([row, encoded]) => { const values = encoded.map(decodeValue); return { row, sheet: cached.sheetName, values, get: fieldAccess(headers, values) }; });
301
+ return { validation: cached.validation, sheetName: cached.sheetName, date1904: cached.date1904, headers, rows, cached: true };
302
+ }
303
+ } catch {}
304
+ const validation = await validateWorkbook(file, moduleId);
305
+ if (!validation.ok) return { validation, rows: [], headers: [] };
306
+ const workbook = new ExcelJS.Workbook(); await workbook.xlsx.load(buffer);
307
+ const sheet = workbook.getWorksheet(validation.sheet);
308
+ if (!sheet) throw new Error('已验证的主工作表不可读取。');
309
+ const headers = Array.from({ length: Math.min(sheet.columnCount, moduleById.get(moduleId).sourceColumnLimit ?? sheet.columnCount) }, (_, index) => text(scalar(sheet.getRow(1).getCell(index + 1).value)));
310
+ const rows = [];
311
+ sheet.eachRow({ includeEmpty: false }, (row, index) => {
312
+ if (index <= 1) return;
313
+ const values = headers.map((_, column) => scalar(row.getCell(column + 1).value));
314
+ if (!values.some(value => text(value) !== '')) return;
315
+ rows.push({ row: index, sheet: sheet.name, values, get: fieldAccess(headers, values) });
316
+ });
317
+ const result = { validation, sheetName: sheet.name, date1904: workbook.properties.date1904, headers, rows };
318
+ if (!cacheFile) return result;
319
+ // Best effort and atomic: a failed write only means the next generation reads Excel again.
320
+ const temp = `${cacheFile}.${process.pid}.${Date.now()}.tmp`;
321
+ try {
322
+ await writeFile(temp, await gzipAsync(JSON.stringify({ key, sha256, validation, sheetName: result.sheetName, date1904: result.date1904, headers, rows: rows.map(row => [row.row, row.values.map(encodeValue)]) }), { level: 6 }), { mode: 0o600 });
323
+ await rename(temp, cacheFile);
324
+ } catch { await rm(temp, { force: true }).catch(() => {}); }
325
+ return result;
326
+ }
327
+
328
+ export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersions, allowPending = false, rowCache = false } = {}) {
329
+ if (!dataDir) throw new Error('必须提供后台数据目录。');
330
+ const root = await realpath(resolve(dataDir));
331
+ const state = JSON.parse(await readFile(resolve(root, 'state.json'), 'utf8'));
332
+ if (state.schemaVersion !== 1 || !Array.isArray(state.uploads) || !state.active || typeof state.active !== 'object') throw new Error('后台 state 格式不受支持。');
333
+ let decisions = null, decisionError = null;
334
+ if (decisionsFile) { try { decisions = JSON.parse(await readFile(decisionsFile, 'utf8')); } catch { decisionError = '决定文件无法读取或不是有效 JSON。'; } }
335
+ const payload = { schemaVersion: 1, processingVersion: 8, mode: 'real-preview', generatedAt: new Date().toISOString(), sources: {}, coverage: {}, modules: {}, pendingDecisions: [...new Set(Object.values(PENDING).flat())] };
336
+ const report = { schemaVersion: 1, generatedAt: payload.generatedAt, decisionError, modules: {}, diagnostics: {}, originalStoreModified: false };
337
+ for (const moduleId of MODULES) {
338
+ const output = { state: 'unavailable', records: [], metrics: {}, unavailable: [...PENDING[moduleId]], warnings: [] };
339
+ payload.modules[moduleId] = output;
340
+ const detail = { sourceRows: 0, includedRows: 0, excludedRows: [], errors: [], warnings: [] }; report.modules[moduleId] = detail;
341
+ try {
342
+ const uploadId = sourceVersions ? sourceVersions[moduleId]?.uploadId : state.active[moduleId];
343
+ if (!uploadId) throw new Error('未选择有效上传版本。');
344
+ if (typeof uploadId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(uploadId)) throw new Error('上传版本标识无效。');
345
+ const upload = state.uploads.find(item => item.id === uploadId && item.moduleId === moduleId);
346
+ if (!upload || !/^[a-f0-9]{64}$/i.test(upload.sha256 ?? '')) throw new Error('上传版本或 SHA 记录不完整。');
347
+ const file = await realpath(resolve(root, 'uploads', uploadId, 'source.xlsx'));
348
+ if (!file.startsWith(`${resolve(root, 'uploads')}${sep}`)) throw new Error('上传文件路径越出后台 uploads 目录。');
349
+ const buffer = await readFile(file), sha256 = createHash('sha256').update(buffer).digest('hex');
350
+ if (sha256 !== upload.sha256.toLowerCase()) throw new Error('源文件 SHA 与有效上传记录不一致,已停止该板块计算。');
351
+ const { validation, sheetName, date1904, headers, rows } = await readSourceRows({ file, buffer, moduleId, sha256, cacheFile: rowCache ? resolve(root, 'uploads', uploadId, ROW_CACHE_FILE) : null });
352
+ if (!validation.ok) throw new Error(`工作簿结构校验失败:${validation.errors.map(error => typeof error === 'string' ? error : error.message).join(';')}`);
353
+ // Later steps only read the sheet name and the workbook date system.
354
+ const workbook = { properties: { date1904 } }, sheet = { name: sheetName };
355
+ payload.sources[moduleId] = { uploadId, sha256, originalName: upload.filename ?? null, sheet: sheet.name, validationVersion: validation.validationVersion };
356
+ detail.sourceRows = rows.length;
357
+ let included = rows;
358
+ if (state.review) {
359
+ const inspection = inspectRows({ moduleId, headers, rows, sheet: sheet.name, sha256, date1904: workbook.properties.date1904, sourceFormat: validation.sourceFormat });
360
+ inspection.lineage = lineageShas(state, uploadId);
361
+ payload.sources[moduleId].lineage = inspection.lineage;
362
+ const reviewed = resolveInspection(inspection, state.review, decisions);
363
+ payload.sources[moduleId].formatKey = inspection.formatKey;
364
+ detail.review = { pendingCount: reviewed.pendingCount, errors: reviewed.errors, groups: reviewed.groups.map(group => ({ key: group.key, status: group.status, decisionId: group.decisionId, reused: group.reused, keptRows: group.rows.filter(row => group.keepKeys.includes(row.key)).map(row => row.row), excludedRows: group.status === 'resolved' ? group.rows.filter(row => !group.keepKeys.includes(row.key)).map(row => row.row) : [] })) };
365
+ if (reviewed.pendingCount || reviewed.errors.length) {
366
+ detail.reviewPending = true;
367
+ payload.coverage[moduleId] = { ...inspection.coverage, status: 'pending', semantics: 'source-requires-review' };
368
+ throw new Error(`待确认:${reviewed.pendingCount ? `${reviewed.pendingCount} 组重复候选;` : ''}${reviewed.errors.join(';')}请返回本机导入检查处理。`);
369
+ }
370
+ const applied = applyDuplicateDecisions(rows, inspection, reviewed);
371
+ included = applied.rows; detail.excludedRows = applied.excludedRows; detail.processingPolicy = 'reviewed-business-group-decisions';
372
+ } else {
373
+ if (moduleId === 'invoice') { const applied = invoiceRows(rows, decisions, sha256, sheet.name); included = applied.rows; detail.excludedRows = applied.excludedRows; detail.decisionChecks = applied.checks; detail.processingPolicy = applied.policy ?? 'source-bound-reviewed-exclusions'; }
374
+ if (moduleId === 'terminal') { const applied = terminalRows(rows, headers, decisions, sha256, sheet.name); included = applied.rows; detail.excludedRows = applied.excludedRows; }
375
+ }
376
+ const visitInventory = moduleId === 'inventory' && validation.sourceFormat === 'visit-history';
377
+ if (visitInventory) {
378
+ const prepared = processInventoryHistory(rows, { date1904: workbook.properties.date1904 });
379
+ output.records = prepared.records;
380
+ output.inventoryMode = 'visit-history';
381
+ output.uncertaintyGroups = prepared.uncertaintyGroups ?? [];
382
+ output.inventoryStats = { sourceRows: rows.length, compressedRows: prepared.records.length,
383
+ groupCount: new Set(prepared.latestRecords.map(row => row.inventoryGroupKey)).size,
384
+ missingDealerCodes: rows.filter(row => !text(row.get('经销商编码'))).length,
385
+ invalidDates: prepared.diagnostics.invalidDates ?? 0, invalidNumbers: prepared.diagnostics.invalidNumbers ?? 0 };
386
+ output.metrics = computeMetrics(moduleId, prepared.latestRecords);
387
+ output.metrics.countAmount = metric(null, '元', 'missing', '拜访采集表没有盘点库存金额,不能用系统金额或假定单价替代');
388
+ if (prepared.latestRecords.some(row => row.inventoryConflict || row.inventoryDateUncertain) || output.uncertaintyGroups.length) {
389
+ for (const field of ['counted', 'system', 'systemAmount', 'absoluteVariance']) output.metrics[field] = metric(null, field === 'systemAmount' ? '元' : '瓶', 'missing', '最近盘点存在同时间候选或无效时间,不能确定唯一库存');
390
+ }
391
+ payload.coverage[moduleId] = { ...prepared.coverage, semantics: 'latest-known-stocktake-before-month-end', productFilter: false };
392
+ detail.inventoryHistory = prepared.diagnostics;
393
+ detail.includedRows = prepared.latestRecords.length;
394
+ detail.historyCandidates = prepared.records.length;
395
+ detail.processingPolicy = 'latest-by-exact-dealer-and-full-product-name-before-month-end';
396
+ detail.warnings.push(...prepared.warnings);
397
+ detail.warnings.push('新来源没有盘点金额和产品编码;金额差额、可销月份、品牌品类联动及安全库存判断不可用。最近盘点不代表统一时点实时库存。');
398
+ output.unavailable = ['inventoryCountAmount', 'inventoryAmountDifference', 'inventorySellableMonthsEstimate', 'inventoryProductMapping', 'inventorySafetyStock'];
399
+ } else {
400
+ output.records = moduleId === 'target' ? included.flatMap(row => targetRecords(row, headers, workbook)) : included.map(row => normalizedRecord(moduleId, row, workbook));
401
+ output.metrics = computeMetrics(moduleId, output.records);
402
+ payload.coverage[moduleId] = coverage(moduleId, output.records, decisions, sha256);
403
+ detail.includedRows = included.length;
404
+ }
405
+ if (moduleId === 'target') {
406
+ const invalid = output.records.filter(row => row.issue && row.issue !== '目标值为空');
407
+ if (invalid.length) detail.warnings.push(`${invalid.length} 个目标无法使用(${[...new Set(invalid.map(row => row.issue))].join('、')}),不计入;例如原表第 ${[...new Set(invalid.map(row => row.sourceRef.row))].slice(0, 5).join('、')} 行。`);
408
+ const seen = new Map();
409
+ for (const row of output.records.filter(item => !item.issue)) { const key = JSON.stringify([row.month, row.metric, row.org.region, row.org.office, row.org.unit]); seen.set(key, (seen.get(key) || 0) + 1); }
410
+ const duplicated = [...seen.values()].filter(count => count > 1).length;
411
+ if (duplicated) detail.warnings.push(`${duplicated} 组目标在同一年月、组织、指标下重复,相关达成率显示待确认,不自动相加。`);
412
+ }
413
+ detail.missingDates = ['banquet', 'target'].includes(moduleId) ? null : output.records.filter(row => row.date === null).length;
414
+ if (detail.missingDates) detail.warnings.push(`${detail.missingDates} 行日期无法确认,不归入任何月份。`);
415
+ if (moduleId === 'movement' && output.metrics.unknownUnitRows.value) detail.warnings.push('存在未确认单品单位,金额保留,数量不归为瓶或盒。');
416
+ if (moduleId === 'banquet' && payload.coverage[moduleId].status !== 'confirmed') { output.unavailable.push('banquetSourcePeriod'); detail.warnings.push('当前来源固定期间未确认,不伪造日期。'); }
417
+ if (moduleId === 'banquet' && !(decisions?.banquet?.sourceSha256 === sha256 && decisions.banquet.includeOrganizationPlaceholders === true)) {
418
+ for (const [field, unit] of [['events', '场'], ['bottles', '瓶']]) output.metrics[field] = metric(null, unit, 'pending', '新来源的组织占位和汇总行粒度尚未核对,保留原值但不直接累加');
419
+ output.unavailable.push('banquetSourceGrain'); detail.warnings.push('宴席汇总粒度确认必须绑定当前来源 SHA。');
420
+ }
421
+ if (moduleId === 'inventory' && !visitInventory) {
422
+ detail.sourceVarianceNullRows = output.records.filter(row => row.sourceVariance === null).length;
423
+ detail.sourceVarianceMismatchRows = output.records.filter(row => row.sourceVariance !== null && row.absoluteVariance !== null && row.sourceVariance !== row.absoluteVariance).length;
424
+ if (detail.sourceVarianceMismatchRows) detail.warnings.push(`${detail.sourceVarianceMismatchRows} 行源偏差与已确认绝对差公式不一致;源值单独保留,未改写。`);
425
+ }
426
+ output.warnings = detail.warnings;
427
+ output.state = detail.warnings.length || Object.values(output.metrics).some(item => item.status === 'missing') ? 'partial' : 'ready';
428
+ } catch (error) {
429
+ detail.errors.push(error.message); output.reason = error.message; output.records = []; output.metrics = {};
430
+ if (detail.reviewPending) { output.reviewPending = true; output.reviewReason = error.message.slice(0, 1000); }
431
+ payload.coverage[moduleId] ??= { start: null, end: null, status: 'unavailable', semantics: null };
432
+ }
433
+ }
434
+ report.organizationMapping = applyOrganizationMapping(payload, decisions?.organizationMapping);
435
+ if (state.review) {
436
+ report.reviewOrganizations = applyOrganizationRules(payload, state.review);
437
+ for (const id of new Set(report.reviewOrganizations.conflicts.map(item => item.moduleId))) {
438
+ report.modules[id].reviewPending = true;
439
+ Object.assign(payload.modules[id], { state: 'unavailable', records: [], metrics: {}, reviewPending: true, reviewReason: '组织对应关系缺少日期依据或存在冲突,请返回导入检查处理。', reason: '待确认:组织对应关系存在冲突,请返回导入检查处理。' });
440
+ }
441
+ }
442
+ payload.decisionContract = buildDecisionContract(payload, decisions, report.organizationMapping);
443
+ const resolved = new Set();
444
+ if (payload.decisionContract.terminalIdentity.status === 'confirmed') { resolved.add('crossTableTerminalIdentity'); delete payload.modules.terminal.metrics.movementCoverage; }
445
+ if (payload.decisionContract.crossTableMetrics.status === 'confirmed') {
446
+ resolved.add('invoiceMovementRelationship'); resolved.add('openingMovementConversion');
447
+ if (payload.modules.inventory.inventoryMode !== 'visit-history') resolved.add('inventorySellableMonthsEstimate');
448
+ }
449
+ if (payload.decisionContract.banquetOpeningSubset.status === 'not-guaranteed') resolved.add('banquetOpeningOverlap');
450
+ payload.pendingDecisions = payload.pendingDecisions.filter(item => !resolved.has(item));
451
+ for (const module of Object.values(payload.modules)) module.unavailable = module.unavailable.filter(item => !resolved.has(item));
452
+ report.decisionContract = payload.decisionContract;
453
+ report.diagnostics = diagnostics(payload);
454
+ report.summary = Object.fromEntries(MODULES.map(id => [id, { state: payload.modules[id].state, ...payload.modules[id].metrics }]));
455
+ const finalState = JSON.parse(await readFile(resolve(root, 'state.json'), 'utf8'));
456
+ report.activeChangedDuringRead = sourceVersions ? false : MODULES.some(id => finalState.active?.[id] !== state.active[id]);
457
+ if (report.activeChangedDuringRead) report.warning = '读取期间有效版本发生变化;本结果仍绑定开始时的上传 ID 与 SHA,不代表最新选择。';
458
+ return { payload, report };
459
+ }