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
|
@@ -32,7 +32,9 @@ export function createV10Presentation(model) {
|
|
|
32
32
|
const inventoryVisit = kind === 'inventory' && m.inventoryMode === 'visit-history';
|
|
33
33
|
const unknownDate = kind !== 'banquet' && scoped.some(row => !validDate(row.date));
|
|
34
34
|
const unavailable = source.state === 'unavailable';
|
|
35
|
+
const add = kind === 'movement' ? (records, field) => records.every(row => finite(row[field])) ? model.sumDecimal(records.map(row => row[field])) : null : sum;
|
|
35
36
|
const guard = (field, label, unit, selected = rows) => {
|
|
37
|
+
if (m.scopeIssue) return pending(label, unit, m.scopeIssue);
|
|
36
38
|
if (unavailable) return pending(label, unit, '未接入有效来源', 'missing');
|
|
37
39
|
if (unknownDate) return pending(label, unit, '存在缺失或无效日期,无法完整分期');
|
|
38
40
|
if (inventoryVisit && field !== 'records' && m.inventoryStats?.uncertainGroups) return pending(label, unit, '组内存在无法确认的提交时间,不能判定实际最新库存', 'unavailable');
|
|
@@ -44,7 +46,7 @@ export function createV10Presentation(model) {
|
|
|
44
46
|
const measure = (selected, field, label, unit, note = '') => {
|
|
45
47
|
const blocked = guard(field, label, unit, selected);
|
|
46
48
|
if (blocked) return { ...blocked, note };
|
|
47
|
-
const value = field === 'records' ? selected.length :
|
|
49
|
+
const value = field === 'records' ? selected.length : add(selected, field);
|
|
48
50
|
return value === null ? pending(label, unit, '存在缺失或不可用源值', inventoryVisit ? 'unavailable' : 'pending', note)
|
|
49
51
|
: { label, unit, value, state: 'available', reason: null, note };
|
|
50
52
|
};
|
|
@@ -104,7 +106,7 @@ export function createV10Presentation(model) {
|
|
|
104
106
|
}
|
|
105
107
|
}
|
|
106
108
|
if (!organizations.length) organizations.push(...emptySection(`${kind}-organizations-empty`, '组织来源汇总', guard('records', '组织来源汇总', m.main.unit) || pending('组织来源汇总', m.main.unit, '当前范围无来源记录', 'missing')));
|
|
107
|
-
let dayChanges = [], ranking = { title: '来源排行', items: [], concentration: [] },
|
|
109
|
+
let dayChanges = [], ranking = { title: '来源排行', items: [], concentration: [] }, cities = [], health = [], deviations = [], efficiency = [], invalidMetrics = [], inventoryReviewSummary = '';
|
|
108
110
|
let kpis = [copy(m.main), ...(m.extra || []).map(item => copy(item))];
|
|
109
111
|
const targetKpi = (item, label) => item ? copy(item, { label, displayPrecision: item.unit === '%' ? 1 : item.unit === '瓶' ? 0 : undefined, note: item.note || (item.target?.note ?? '') })
|
|
110
112
|
: pending(label, '%', '未上传经营目标', 'missing');
|
|
@@ -142,7 +144,7 @@ export function createV10Presentation(model) {
|
|
|
142
144
|
trend.monthly = (m.monthly || []).filter(inWindow).map(item => {
|
|
143
145
|
const selected = (inventoryVisit ? rows : scoped).filter(row => row.month === item.month);
|
|
144
146
|
const metric = kind === 'inventory' || kind === 'opening' ? measure(selected, field, kind === 'opening' ? '开瓶金额' : item.month, unit) : copy(item);
|
|
145
|
-
const negative = metric.state === 'available' && field === 'amount' && kind !== 'opening' ?
|
|
147
|
+
const negative = metric.state === 'available' && field === 'amount' && kind !== 'opening' ? add(selected.filter(row => row.amount < 0), 'amount') : null;
|
|
146
148
|
return { ...metric, key: item.month, month: item.month, label: item.month, negative, comparison: null,
|
|
147
149
|
...(kind === 'opening' ? { bottles: measure(selected, 'bottles', '开瓶瓶数', '瓶', `${item.month};与本柱开瓶金额使用相同组织和月份范围。`) } : {}) };
|
|
148
150
|
});
|
|
@@ -152,14 +154,31 @@ export function createV10Presentation(model) {
|
|
|
152
154
|
const start = [coverage.start, p.mode === 'range' ? p.start : `${f.month}-01`].sort().at(-1), end = [coverage.end, monthEnd].sort()[0];
|
|
153
155
|
for (let day = start; day <= end; day = new Date(Date.parse(`${day}T00:00:00Z`) + 86400000).toISOString().slice(0, 10)) dates.push(day);
|
|
154
156
|
}
|
|
157
|
+
const byDay = new Map();
|
|
158
|
+
for (const row of rows) {
|
|
159
|
+
const entries = byDay.get(row.date) ?? [];
|
|
160
|
+
entries.push(row);
|
|
161
|
+
byDay.set(row.date, entries);
|
|
162
|
+
}
|
|
155
163
|
trend.daily = dates.map(date => {
|
|
156
|
-
const selected =
|
|
157
|
-
return { ...metric, key: date, date, label: date, negative: metric.state === 'available' && field === 'amount' && kind !== 'opening' ?
|
|
164
|
+
const selected = byDay.get(date) ?? [], metric = measure(selected, field, date, unit);
|
|
165
|
+
return { ...metric, key: date, date, label: date, negative: metric.state === 'available' && field === 'amount' && kind !== 'opening' ? add(selected.filter(row => row.amount < 0), 'amount') : null, comparison: null };
|
|
158
166
|
});
|
|
159
167
|
let accumulated = 0, negativeTotal = 0, known = true;
|
|
168
|
+
const movementSum = kind === 'movement' ? model.createDecimalSum() : null;
|
|
169
|
+
const movementNegative = movementSum ? model.createDecimalSum() : null;
|
|
160
170
|
trend.cumulative = trend.daily.map(item => {
|
|
161
171
|
known = known && item.state === 'available';
|
|
162
|
-
if (known) {
|
|
172
|
+
if (known) {
|
|
173
|
+
if (movementSum) {
|
|
174
|
+
for (const row of byDay.get(item.date)) {
|
|
175
|
+
movementSum.add(row.amount);
|
|
176
|
+
if (row.amount < 0) movementNegative.add(row.amount);
|
|
177
|
+
}
|
|
178
|
+
accumulated = movementSum.value(); negativeTotal = movementNegative.value();
|
|
179
|
+
} else { accumulated += item.value; negativeTotal += item.negative || 0; }
|
|
180
|
+
known = finite(accumulated) && finite(negativeTotal);
|
|
181
|
+
}
|
|
163
182
|
return { ...item, value: known ? accumulated : null, negative: known && field === 'amount' ? negativeTotal : null,
|
|
164
183
|
state: known ? 'available' : item.state === 'missing' ? 'missing' : 'pending', reason: known ? null : '此前或当日缺少来源记录或值,无法完整累计', note: '按所选月与来源覆盖期间的交集累计;遇到缺日或缺值保持未知,不补零。' };
|
|
165
184
|
});
|
|
@@ -182,19 +201,13 @@ export function createV10Presentation(model) {
|
|
|
182
201
|
if (m.targets?.available) kpis.push(targetKpi(m.targets.ytdAttainment, '年累计目标达成率'), targetKpi(m.targets.month, p.mode === 'range' ? '区间目标' : '当月目标'), targetKpi(m.targets.ytd, '年累计目标'));
|
|
183
202
|
}
|
|
184
203
|
if (kind === 'movement') {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
ranking.concentration = concentration(ranking.items, '当前范围扫码净额合计', [10, 50, 100]);
|
|
188
|
-
channels = group(rows, row => row.channel, row => row.channel, 'amount', '元', '来源渠道净额', row => text(row.channel));
|
|
189
|
-
kpis = [copy(m.main), existing('扫码数量(瓶单位记录)', '瓶'), existing('负金额合计', '元'), existing('当年截至所选月来源金额', '元'),
|
|
190
|
-
distinct(rows, 'terminalCode', '来源扫码终端数'), cross('invoiceMovementYtdRatio', '年累计动销 / 开票', '%')];
|
|
204
|
+
kpis = [copy(m.main), existing('动销件数', '件'), existing('负金额合计', '元'), existing('当年截至所选月来源金额', '元'),
|
|
205
|
+
cross('invoiceMovementYtdRatio', '年累计动销 / 开票', '%')];
|
|
191
206
|
kpis.push(...cumulativeKpis());
|
|
192
207
|
if (m.targets?.available) kpis.push(targetKpi(m.targets.attainment, '目标达成率'), targetKpi(m.targets.ytdAttainment, '年累计目标达成率'), targetKpi(m.targets.month, p.mode === 'range' ? '区间目标' : '当月目标'));
|
|
193
|
-
notes.push(...['扫码数量(盒单位记录)', '来源扫码件数'].map(label => { const metric = existing(label); return `${label}:${model.formatMetric(metric)}${metric.state === 'available' ? ` ${metric.unit}` : ''}。`; }));
|
|
194
|
-
notes.push('负金额合计只按源金额符号汇总,不将所有负金额推定为退货出库。');
|
|
195
208
|
const rule = model.payload.decisionContract?.crossTableMetrics, deps = ['invoice', 'movement'];
|
|
196
209
|
const confirmed = model.payload.decisionContract?.version === 1 && rule?.status === 'confirmed'
|
|
197
|
-
&&
|
|
210
|
+
&& ['invoice', ...model.movementShaIds].every(id => rule.sources?.[id] && rule.sources[id] === model.payload.sources[id]?.sha256);
|
|
198
211
|
const completeSource = confirmed && deps.every(id => model.payload.modules[id].state !== 'unavailable'
|
|
199
212
|
&& model.payload.coverage[id]?.start && model.payload.coverage[id]?.end
|
|
200
213
|
&& model.payload.modules[id].metrics?.amount?.status !== 'pending'
|
|
@@ -225,7 +238,7 @@ export function createV10Presentation(model) {
|
|
|
225
238
|
// 2026-11-27:开瓶金额为主(万元显示),去掉“较昨日”。
|
|
226
239
|
kpis = [copy(existing('开瓶金额', '元'), { label: p.mode === 'range' ? '区间开瓶金额' : '当月开瓶金额' }), copy(m.main), existing('瓶均开瓶金额', '元/瓶'),
|
|
227
240
|
measure(yearRows, 'amount', '当年截至所选月开瓶金额', '元', '只累计当前上传中已有的当年记录,不推断未提供月份。'),
|
|
228
|
-
distinct(rows, 'city', '来源开瓶城市', '个')
|
|
241
|
+
distinct(rows, 'city', '来源开瓶城市', '个')];
|
|
229
242
|
if (m.targets?.available) kpis.push(targetKpi(m.targets.attainment, '目标达成率'), targetKpi(m.targets.ytdAttainment, '年累计目标达成率'), targetKpi(m.targets.month, p.mode === 'range' ? '区间目标' : '当月目标'));
|
|
230
243
|
notes.push('宴席开瓶与消费者开瓶的包含关系不保证,不计算宴席开瓶占比。', '城市只按来源城市字段分组,不推定城市编码或消费者身份。');
|
|
231
244
|
}
|
|
@@ -258,7 +271,7 @@ export function createV10Presentation(model) {
|
|
|
258
271
|
invalidMetrics = [
|
|
259
272
|
pending('盘点库存金额', '元', '新表没有盘点库存金额,不能用系统金额或假定单价替代', 'unavailable'),
|
|
260
273
|
pending('金额差额', '元', '缺盘点库存金额;两类金额估值关系也未确认', 'unavailable'),
|
|
261
|
-
pending('可销月份', '月', '
|
|
274
|
+
pending('可销月份', '月', '缺盘点库存金额和产品编码关联,无法计算库存金额与动销金额比', 'unavailable'),
|
|
262
275
|
pending('品牌/品类筛选与金额构成', '', '新表没有产品编码、品牌和品类;库存不随统一品牌/品类筛选', 'unavailable'),
|
|
263
276
|
pending('跨板块组织联动', '', '新旧来源完整组织路径存在事业部层级差异,尚未确认映射;按源完整路径独立筛选,不按同名组织合并', 'unavailable'),
|
|
264
277
|
pending('安全库存与健康分类', '', '源“差异”不是安全库存阈值,不能据此判定低于安全库存', 'unavailable'),
|
|
@@ -309,8 +322,10 @@ export function createV10Presentation(model) {
|
|
|
309
322
|
copy(ranking.concentration.find(item => item.n === 5), { label: 'Top 5 单元场次占比' })];
|
|
310
323
|
notes.push('按执行月份统计;自定义区间按覆盖到的整月计入。不计算宴席占消费者开瓶比例。');
|
|
311
324
|
}
|
|
312
|
-
const
|
|
313
|
-
|
|
325
|
+
const movementHas = ['dealer', 'distributor'].filter(id => data.payload?.movementSources?.[id] ?? model.payload?.movementSources?.[id]);
|
|
326
|
+
const movementBasis = movementHas.length === 1 ? `当前仅含${movementHas[0] === 'dealer' ? '经销商' : '分销商'}动销明细(未传${movementHas[0] === 'dealer' ? '分销商' : '经销商'})` : '经销商 + 分销商动销明细';
|
|
327
|
+
const primaryNotes = p.mode === 'range' ? { invoice: `按业务日期净计 ${p.label} 源金额。`, movement: `${movementBasis},所选区间含退货净额。`, opening: `按抽奖日期统计 ${p.label} 开瓶金额。`,
|
|
328
|
+
inventory: inventoryVisit ? `截至 ${p.end},每个经销商与完整产品名称的最近一次已知盘点;不是当天实时库存。` : `当前上传导出中截至 ${p.end} 的盘点记录。`, banquet: `按执行月份汇总 ${p.start.slice(0, 7)} 至 ${p.end.slice(0, 7)} 整月。`, terminal: `按签约日期截至 ${p.end};遵循最新矩阵规则。` } : { invoice: '按业务日期净计当月源金额。', movement: `${movementBasis},当月含退货净额。`, opening: '按抽奖日期统计当月开瓶金额。',
|
|
314
329
|
inventory: inventoryVisit ? '截至所选月,每个经销商与完整产品名称的最近一次已知盘点;不是当天实时库存。' : '当前上传导出中截至所选月的盘点记录。', banquet: '按执行月份汇总所选月。', terminal: '按签约日期截至所选月末;遵循最新矩阵规则。' };
|
|
315
330
|
for (let index = 0; index < kpis.length; index++) {
|
|
316
331
|
const item = kpis[index];
|
|
@@ -318,15 +333,16 @@ export function createV10Presentation(model) {
|
|
|
318
333
|
if (item.label === '正金额合计') item.note = '正数源金额合计。';
|
|
319
334
|
if (item.label === '负金额合计') item.note = '已计入净额,不重新改变符号。';
|
|
320
335
|
if (item.label.startsWith('当年截至所选月')) item.note = '当前上传中当年截至所选月的来源记录;缺月不补零。';
|
|
321
|
-
if (
|
|
322
|
-
if (item.key === 'inventorySellableMonths') item.note = '库存金额 ÷
|
|
323
|
-
if (item.key === '
|
|
324
|
-
if (item.key === 'invoiceMovementYtdRatio') item.note = '同组织、同产品、同期间的累计扫码净额 ÷ 发票净额。';
|
|
336
|
+
if (item.label === '来源经销商数') item.note = '按当前范围来源编码去重;缺编码保持待确认。';
|
|
337
|
+
if (item.key === 'inventorySellableMonths') item.note = '库存金额 ÷ 近三月月均动销金额;未折算全月。';
|
|
338
|
+
if (item.key === 'invoiceMovementYtdRatio') item.note = '同组织、同产品、同期间的累计动销净额 ÷ 发票净额。';
|
|
325
339
|
if (item.label === '场均开瓶') item.note = '宴席开瓶瓶数 ÷ 执行场次。';
|
|
326
340
|
if (item.label === 'Top 5 单元场次占比') item.note = '按完整单元路径汇总执行场次占比。';
|
|
327
341
|
}
|
|
328
342
|
if (p.mode === 'range') for (const item of kpis) if (item.label?.startsWith('当年截至所选月')) {
|
|
329
|
-
|
|
343
|
+
const end = kind === 'movement' ? model.payload.coverage.movement?.end && [p.end, model.payload.coverage.movement.end].sort()[0] : p.end;
|
|
344
|
+
item.label = item.label.replace('所选月', '区间末日');
|
|
345
|
+
item.note = end && end.slice(0, 4) === f.month.slice(0, 4) ? `当年 1 月 1 日至 ${end} 的来源记录;缺月不补零。` : '动销来源尚未覆盖所选年度。';
|
|
330
346
|
}
|
|
331
347
|
const sourceRows = rows.map((row, index) => {
|
|
332
348
|
const displayed = { ...row, key: `${kind}-row-${index}`, organization: parts(row).map(value => value || '未提供').join(' / ') };
|
|
@@ -353,12 +369,17 @@ export function createV10Presentation(model) {
|
|
|
353
369
|
}
|
|
354
370
|
return displayed;
|
|
355
371
|
});
|
|
356
|
-
//
|
|
372
|
+
// 来源构成随所选组织、产品及期间计算。
|
|
357
373
|
const total = kind === 'invoice' && available(m.main) ? m.main.value : null;
|
|
358
374
|
const platformSources = kind === 'invoice' ? (m.platformSources || []).map(item => ({ ...item, name: item.label, share: finite(total) && total !== 0 && available(item) ? item.value / total : null,
|
|
359
375
|
shareText: finite(total) && total !== 0 && available(item) ? `占发票 ${model.format(item.value / total * 100, 1, 1)}%` : '', note: item.key === 'company' ? '公司发票系统(销售收入明细)' : `${item.label}订单,已并入发票合计` })) : [];
|
|
360
|
-
const
|
|
361
|
-
const
|
|
376
|
+
const movementTotal = kind === 'movement' && available(m.main) ? m.main.value : null;
|
|
377
|
+
const movementSources = kind === 'movement' ? (m.movementSources || []).map(item => ({ ...item, name: item.label,
|
|
378
|
+
share: finite(movementTotal) && movementTotal > 0 && available(item) && item.value >= 0 ? item.value / movementTotal : null,
|
|
379
|
+
shareText: finite(movementTotal) && movementTotal > 0 && available(item) && item.value >= 0 ? `占动销 ${model.format(item.value / movementTotal * 100, 1, 1)}%` : '',
|
|
380
|
+
subtitle: item.reason === '未上传有效来源' ? '尚未上传(不补零)'
|
|
381
|
+
: `${available(item.cases) ? `${model.format(item.cases.value, 0, 6)} 件` : `件数 ${item.cases.reason || '待确认'}`} · 数据截至 ${item.coverage?.end || '未提供'}` })) : [];
|
|
382
|
+
const result = { kpis, dayChanges: [], trend, organizations, brands, products, ranking, cities, health, deviations, efficiency, platformSources, movementSources, ...(inventoryVisit ? { invalidMetrics, inventoryMode: 'visit-history', inventoryReviewSummary } : {}),
|
|
362
383
|
rows: sourceRows, notes: [...new Set(notes)] };
|
|
363
384
|
if (!byKind) { byKind = new Map(); cache.set(supplied, byKind); }
|
|
364
385
|
byKind.set(cacheKey, result);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { createDecimalSum, sumDecimal } from './decimal-sum.mjs';
|
|
3
4
|
import { createV10Model } from './v10-model.mjs';
|
|
4
5
|
import { createV10Components } from './v10-components.mjs';
|
|
5
6
|
import { buildTerminalStructure } from './terminal-structure.mjs';
|
|
@@ -12,17 +13,17 @@ import { createV10Overview } from './v10-overview.mjs';
|
|
|
12
13
|
export { createV10Model } from './v10-model.mjs';
|
|
13
14
|
export const V10_TEMPLATE_SHA256 = 'b58e609411d0b9ab2d77d7079ea580e8210d11946999a8c11cea1fc34bf9b886';
|
|
14
15
|
export const V10_SCRIPT_SHA256 = 'd11a689940d80a4010c5f45786ac2da7d3106cb8309216b4df2d55c8dac4599c';
|
|
15
|
-
export const V10_RENDERER_VERSION =
|
|
16
|
+
export const V10_RENDERER_VERSION = 24;
|
|
16
17
|
export const V10_SHELL_SHA256 = 'd5118e6e2ec447cc22992c348e18ae719bfbda959a2b694352843c120522a5f1';
|
|
17
18
|
const APPLICATION_MARKER = '/*__V10_APPLICATION__*/';
|
|
18
19
|
const IDS = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet'];
|
|
19
20
|
const ORG = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
|
|
20
21
|
const NUMERIC = {
|
|
21
|
-
invoice: ['amount'], movement: ['amount', '
|
|
22
|
+
invoice: ['amount'], movement: ['amount', 'cases'], scan: ['cases'], opening: ['bottles', 'amount'],
|
|
22
23
|
terminal: [], inventory: ['counted', 'system', 'countAmount', 'systemAmount', 'absoluteVariance', 'signedVariance', 'sourceVariance'], banquet: ['events', 'bottles'],
|
|
23
24
|
};
|
|
24
|
-
const TEXT = { invoice: ['brand', 'category', 'dealerCode', 'dealerName', 'productCode', 'productName', 'platform'], movement: ['brand', 'category', '
|
|
25
|
-
const OPTIONAL_DISPLAY_TEXT = new Set(['productCode', 'productName', 'variety', 'terminalName', '
|
|
25
|
+
const TEXT = { invoice: ['brand', 'category', 'dealerCode', 'dealerName', 'productCode', 'productName', 'platform'], movement: ['brand', 'category', 'source', 'productCode', 'productName', 'dealerCode', 'dealerName'], scan: ['terminalCode', 'category', 'productName', 'variety'], opening: ['city'], terminal: ['terminalCode', 'terminalName', 'star', 'agreementId', 'type', 'series', 'signLevel', 'signVariety'], inventory: ['brand', 'category', 'safety', 'dealerCode', 'dealerName', 'productCode', 'productName'], banquet: [] };
|
|
26
|
+
const OPTIONAL_DISPLAY_TEXT = new Set(['productCode', 'productName', 'variety', 'terminalName', 'agreementId', 'type', 'series', 'signLevel', 'signVariety', 'platform', 'source']);
|
|
26
27
|
const PLATFORMS = ['zang10', 'tunzhihu'];
|
|
27
28
|
const hash = text => createHash('sha256').update(text).digest('hex');
|
|
28
29
|
const isObject = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
@@ -58,7 +59,7 @@ export function sanitizeV10Payload(input) {
|
|
|
58
59
|
for (const field of ['sources', 'appliedSources']) if (rule[field]) {
|
|
59
60
|
if (!isObject(rule[field])) fail(`规则 ${key} 来源绑定无效`);
|
|
60
61
|
clean[field] = Object.fromEntries(Object.entries(rule[field]).map(([id, sha]) => {
|
|
61
|
-
if (!IDS.includes(id) || typeof sha !== 'string' || !/^[a-f0-9]{64}$/i.test(sha)) fail(`规则 ${key} 来源指纹无效`);
|
|
62
|
+
if (![...IDS, 'scan', 'distributor'].includes(id) || typeof sha !== 'string' || !/^[a-f0-9]{64}$/i.test(sha)) fail(`规则 ${key} 来源指纹无效`);
|
|
62
63
|
return [id, sha.toLowerCase()];
|
|
63
64
|
}));
|
|
64
65
|
}
|
|
@@ -70,12 +71,14 @@ export function sanitizeV10Payload(input) {
|
|
|
70
71
|
result.decisionContract[key] = clean;
|
|
71
72
|
}
|
|
72
73
|
}
|
|
73
|
-
|
|
74
|
+
const moduleIds = input.modules.scan ? [...IDS, 'scan'] : IDS;
|
|
75
|
+
for (const id of moduleIds) {
|
|
74
76
|
const module = input.modules[id];
|
|
75
77
|
if (!isObject(module) || !['ready', 'partial', 'unavailable'].includes(module.state) || !Array.isArray(module.records) || !isObject(module.metrics) || !Array.isArray(module.unavailable)) fail(`${id} 模块合同不完整`);
|
|
76
78
|
if (module.state === 'unavailable' && module.records.length) fail(`${id} 不可用模块不能带可展示记录`);
|
|
77
79
|
const source = input.sources[id];
|
|
78
|
-
|
|
80
|
+
// 动销只有分销商一边时,锁定来源是 sources.distributor(下面单独校验)。
|
|
81
|
+
if (module.state !== 'unavailable' && !source && !(id === 'movement' && input.sources.distributor && module.records.every(row => row.source === 'distributor'))) fail(`${id} 缺少锁定来源`);
|
|
79
82
|
if (source) {
|
|
80
83
|
if (!isObject(source) || typeof source.sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(source.sha256)) fail(`${id} SHA-256 无效`);
|
|
81
84
|
const name = source.originalName === null ? '未提供文件名' : string(source.originalName, `${id}.originalName`);
|
|
@@ -100,6 +103,7 @@ export function sanitizeV10Payload(input) {
|
|
|
100
103
|
}));
|
|
101
104
|
if (row.date !== null && !validDate(row.date)) fail(`${where}.date 无效`);
|
|
102
105
|
if (id === 'invoice' && row.platform && !PLATFORMS.includes(row.platform)) fail(`${where}.platform 无效`);
|
|
106
|
+
if (id === 'movement' && row.source != null && !['dealer', 'distributor'].includes(row.source)) fail(`${where}.source 无效`);
|
|
103
107
|
const clean = { org, orgPath, date: row.date };
|
|
104
108
|
for (const key of NUMERIC[id]) {
|
|
105
109
|
if (!(key in row)) fail(`${where}.${key} 缺失,不能静默补零`);
|
|
@@ -190,90 +194,112 @@ export function sanitizeV10Payload(input) {
|
|
|
190
194
|
originalName: item.source?.originalName ? string(item.source.originalName, `${id}.originalName`).replaceAll('\\', '/').split('/').at(-1) : null };
|
|
191
195
|
}
|
|
192
196
|
}
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
197
|
+
if (isObject(input.movementSources)) {
|
|
198
|
+
result.movementSources = {};
|
|
199
|
+
for (const key of ['dealer', 'distributor']) {
|
|
200
|
+
const item = input.movementSources[key];
|
|
201
|
+
if (!isObject(item)) continue;
|
|
202
|
+
const cover = item.coverage ?? {};
|
|
203
|
+
for (const date of [cover.start, cover.end]) if (date != null && !validDate(date)) fail(`${key} 动销来源期间无效`);
|
|
204
|
+
const originalName = item.originalName == null ? null : string(item.originalName, `${key}.originalName`).replaceAll('\\', '/').split('/').at(-1);
|
|
205
|
+
result.movementSources[key] = { rows: Number.isSafeInteger(item.rows) ? item.rows : 0, coverage: { start: cover.start ?? null, end: cover.end ?? null }, originalName };
|
|
206
|
+
if (isObject(item.scopeLimits)) {
|
|
207
|
+
const { organization, product, invalidTemplate, scopedOrganization } = item.scopeLimits;
|
|
208
|
+
result.movementSources[key].scopeLimits = {
|
|
209
|
+
...(Number.isSafeInteger(organization) && organization > 0 ? { organization } : {}),
|
|
210
|
+
...(Number.isSafeInteger(product) && product > 0 ? { product } : {}),
|
|
211
|
+
...(invalidTemplate ? { invalidTemplate: string(invalidTemplate, `${key}.scopeLimits.invalidTemplate`) } : {}),
|
|
212
|
+
...(scopedOrganization === true ? { scopedOrganization } : {}),
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (input.sources.distributor) {
|
|
218
|
+
const source = input.sources.distributor;
|
|
219
|
+
if (!isObject(source) || typeof source.sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(source.sha256)) fail('分销商动销 SHA-256 无效');
|
|
220
|
+
result.sources.distributor = { uploadId: string(source.uploadId, 'distributor.uploadId'), sha256: source.sha256.toLowerCase(),
|
|
221
|
+
originalName: result.movementSources?.distributor?.originalName ?? '未提供文件名' };
|
|
208
222
|
}
|
|
209
223
|
if (!IDS.some(id => result.modules[id].state !== 'unavailable' && result.modules[id].records.length) && !IDS.some(id => result.modules[id].reviewPending)) fail('零有效来源不能生成真实数据看板');
|
|
210
224
|
return result;
|
|
211
225
|
}
|
|
212
226
|
|
|
213
227
|
const literal = value => JSON.stringify(value).replaceAll('<', '\\u003c').replaceAll('\u2028', '\\u2028').replaceAll('\u2029', '\\u2029');
|
|
214
|
-
|
|
228
|
+
function packColumns(records, encoding) {
|
|
229
|
+
if (!records.length) return records;
|
|
230
|
+
const fields = Object.keys(records[0]);
|
|
231
|
+
if (!records.every(row => Object.keys(row).length === fields.length && fields.every(field => Object.hasOwn(row, field)))) return records;
|
|
232
|
+
|
|
233
|
+
const legacy = encoding === 'inventory-columns-v1';
|
|
234
|
+
const columns = fields.map(field => {
|
|
235
|
+
const values = records.map(row => row[field]);
|
|
236
|
+
// JSON serializes -0 as 0. Retain its positions for the offline round trip.
|
|
237
|
+
const signedZeros = [];
|
|
238
|
+
if (!legacy) values.forEach((value, i) => { if (Object.is(value, -0)) signedZeros.push(i); });
|
|
239
|
+
if (values.every(value => Object.is(value, values[0]))) {
|
|
240
|
+
return signedZeros.length ? { value: 0, negativeZero: true } : { value: values[0] };
|
|
241
|
+
}
|
|
242
|
+
if (signedZeros.length) return { values, signedZeros };
|
|
243
|
+
const plain = { values };
|
|
244
|
+
if (!values.every(value => value === null || typeof value === 'string')) return plain;
|
|
245
|
+
const dictionary = [], indexes = [], lookup = new Map();
|
|
246
|
+
for (const value of values) {
|
|
247
|
+
if (!lookup.has(value)) { lookup.set(value, dictionary.length); dictionary.push(value); }
|
|
248
|
+
indexes.push(lookup.get(value));
|
|
249
|
+
}
|
|
250
|
+
const encoded = { dictionary, indexes };
|
|
251
|
+
const size = legacy ? value => JSON.stringify(value).length : value => Buffer.byteLength(JSON.stringify(value));
|
|
252
|
+
return size(encoded) < size(plain) ? encoded : plain;
|
|
253
|
+
});
|
|
254
|
+
return { encoding, length: records.length, fields, columns };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function packV10Payload(payload, { columns = true } = {}) {
|
|
215
258
|
const paths = [], keys = new Map();
|
|
216
|
-
|
|
217
|
-
const
|
|
218
|
-
let records = module.records.map(({ org, orgPath, ...row }) => {
|
|
259
|
+
function packModule(module, encoding) {
|
|
260
|
+
const rows = module.records.map(({ org, orgPath, ...row }) => {
|
|
219
261
|
const key = JSON.stringify(orgPath);
|
|
220
262
|
if (!keys.has(key)) { keys.set(key, paths.length); paths.push(orgPath); }
|
|
221
263
|
return { ...row, orgIndex: keys.get(key) };
|
|
222
264
|
});
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
if (values.every(value => Object.is(value, values[0]))) return { value: values[0] };
|
|
231
|
-
const plain = { values };
|
|
232
|
-
if (values.every(value => value === null || typeof value === 'string')) {
|
|
233
|
-
const dictionary = [], indexes = [], lookup = new Map();
|
|
234
|
-
for (const value of values) {
|
|
235
|
-
if (!lookup.has(value)) { lookup.set(value, dictionary.length); dictionary.push(value); }
|
|
236
|
-
indexes.push(lookup.get(value));
|
|
237
|
-
}
|
|
238
|
-
const encoded = { dictionary, indexes };
|
|
239
|
-
if (JSON.stringify(encoded).length < JSON.stringify(plain).length) return encoded;
|
|
240
|
-
}
|
|
241
|
-
return plain;
|
|
242
|
-
});
|
|
243
|
-
records = { encoding: 'inventory-columns-v1', length: records.length, fields, columns };
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
return [id, { ...module, records }];
|
|
265
|
+
return { ...module, records: encoding ? packColumns(rows, encoding) : rows };
|
|
266
|
+
}
|
|
267
|
+
const modules = Object.fromEntries((columns ? Object.keys(payload.modules) : [...IDS, ...(payload.modules.scan ? ['scan'] : [])]).map(id => {
|
|
268
|
+
const module = payload.modules[id];
|
|
269
|
+
const legacyInventory = id === 'inventory' && module.inventoryMode === 'visit-history';
|
|
270
|
+
const encoding = columns ? 'records-columns-v1' : legacyInventory && 'inventory-columns-v1';
|
|
271
|
+
return [id, packModule(module, encoding)];
|
|
247
272
|
}));
|
|
248
273
|
const packed = { ...payload, organizationPaths: paths, modules };
|
|
249
|
-
if (payload.distributor) packed.distributor =
|
|
250
|
-
const key = JSON.stringify(orgPath);
|
|
251
|
-
if (!keys.has(key)) { keys.set(key, paths.length); paths.push(orgPath); }
|
|
252
|
-
return { ...row, orgIndex: keys.get(key) };
|
|
253
|
-
}) };
|
|
274
|
+
if (payload.distributor) packed.distributor = packModule(payload.distributor, columns && 'records-columns-v1');
|
|
254
275
|
return packed;
|
|
255
276
|
}
|
|
256
|
-
//
|
|
257
|
-
// full six-level organization hundreds of thousands of times. Keep this function
|
|
258
|
-
// self-contained: its source is embedded directly into the offline HTML.
|
|
277
|
+
// Keep this function self-contained: its source is embedded directly into the offline HTML.
|
|
259
278
|
export function unpackV10Payload(payload) {
|
|
279
|
+
const { organizationPaths, ...rest } = payload;
|
|
260
280
|
const fields = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
|
|
261
|
-
const orgs =
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
281
|
+
const orgs = organizationPaths.map(path => Object.fromEntries(fields.map((field, index) => [field, path[index]])));
|
|
282
|
+
function unpackModule(module) {
|
|
283
|
+
const packed = module.records;
|
|
284
|
+
const restoreOrg = ({ orgIndex, ...row }) => ({ ...row, org: orgs[orgIndex], orgPath: organizationPaths[orgIndex] });
|
|
285
|
+
if (Array.isArray(packed)) return { ...module, records: packed.map(restoreOrg) };
|
|
286
|
+
if (!['inventory-columns-v1', 'records-columns-v1'].includes(packed.encoding)) throw new Error('未知记录编码');
|
|
287
|
+
const records = Array.from({ length: packed.length }, (_, index) => {
|
|
288
|
+
const row = Object.fromEntries(packed.fields.map((field, columnIndex) => {
|
|
267
289
|
const column = packed.columns[columnIndex];
|
|
268
290
|
const value = Object.prototype.hasOwnProperty.call(column, 'value') ? column.value
|
|
269
291
|
: column.dictionary ? column.dictionary[column.indexes[index]] : column.values[index];
|
|
270
|
-
return [field, value];
|
|
271
|
-
}))
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
292
|
+
return [field, column.negativeZero ? -0 : value];
|
|
293
|
+
}));
|
|
294
|
+
return restoreOrg(row);
|
|
295
|
+
});
|
|
296
|
+
packed.columns.forEach((column, i) => {
|
|
297
|
+
for (const index of column.signedZeros || []) records[index][packed.fields[i]] = -0;
|
|
298
|
+
});
|
|
299
|
+
return { ...module, records };
|
|
300
|
+
}
|
|
301
|
+
const modules = Object.fromEntries(Object.entries(payload.modules).map(([id, module]) => [id, unpackModule(module)]));
|
|
302
|
+
if (payload.distributor) rest.distributor = unpackModule(payload.distributor);
|
|
277
303
|
return { ...rest, modules };
|
|
278
304
|
}
|
|
279
305
|
function once(source, search, replacement) {
|
|
@@ -329,6 +355,8 @@ function renderShell(shell, input, { mode, templateSha256 }) {
|
|
|
329
355
|
const V10_PAYLOAD=(${unpackV10Payload.toString()})(${literal(packV10Payload(payload))});
|
|
330
356
|
const V10_PRESENTATION=${literal(presentation)};
|
|
331
357
|
const buildTerminalStructure=(${buildTerminalStructure.toString()});
|
|
358
|
+
const createDecimalSum=(${createDecimalSum.toString()});
|
|
359
|
+
const sumDecimal=(${sumDecimal.toString()});
|
|
332
360
|
const createTerminalComponents=(${createTerminalComponents.toString()});
|
|
333
361
|
const createV10Presentation=(${createV10Presentation.toString()});
|
|
334
362
|
const createV10Details=(${createV10Details.toString()});
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { readFile } from 'node:fs/promises';
|
|
3
|
-
import
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { hashWorkbook, streamValidatedRows } from './incremental/xlsx-rows.mjs';
|
|
5
|
+
import { isLegacyScanUpload } from './modules/scan/legacy.mjs';
|
|
4
6
|
import { moduleById, normalizeHeader } from './modules.mjs';
|
|
5
7
|
import { validateWorkbook } from './validate-workbook.mjs';
|
|
6
8
|
|
|
@@ -8,7 +10,7 @@ import { validateWorkbook } from './validate-workbook.mjs';
|
|
|
8
10
|
// promotion remain the server's responsibility; original workbooks are never edited.
|
|
9
11
|
const VERSION = 1;
|
|
10
12
|
const ORG_FIELDS = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
|
|
11
|
-
const DATE_MODULES = new Set(['invoice', 'movement', 'opening']);
|
|
13
|
+
const DATE_MODULES = new Set(['invoice', 'movement', 'scan', 'opening', 'distributor']);
|
|
12
14
|
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
13
15
|
const text = value => value === null || value === undefined ? '' : String(value).trim();
|
|
14
16
|
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
@@ -99,7 +101,7 @@ function visitOrganization(row) {
|
|
|
99
101
|
function organization(moduleId, row, sourceFormat) {
|
|
100
102
|
if (moduleId === 'inventory' && sourceFormat === 'visit-history') return visitOrganization(row);
|
|
101
103
|
const headers = {
|
|
102
|
-
invoice: ['销售大区', '办事处', '客户主任单元'], movement: ['大区名称', '办事处名称', '主任单元名称'],
|
|
104
|
+
invoice: ['销售大区', '办事处', '客户主任单元'], movement: ['大区', '办事处', '主任单元'], scan: ['大区名称', '办事处名称', '主任单元名称'],
|
|
103
105
|
opening: ['产品所属-大区', '产品所属-办事处', '产品所属-主任单元'], terminal: ['大区', '办事处', '主任单元'],
|
|
104
106
|
inventory: ['大区名称', '办事处名称', '单元名称'], banquet: ['大区', '办事处', '主任单元'], target: ['大区', '办事处', '主任单元'],
|
|
105
107
|
zang10: ['大区', '办事处', '客户主任单元'], tunzhihu: ['大区', '办事处', '主任单元'], distributor: ['大区', '办事处', '客户主任单元'],
|
|
@@ -109,7 +111,7 @@ function organization(moduleId, row, sourceFormat) {
|
|
|
109
111
|
|
|
110
112
|
function recordDate(moduleId, row, date1904) {
|
|
111
113
|
if (moduleId === 'zang10' || moduleId === 'banquet') return monthDay(moduleId === 'zang10' ? row.get('订单归属年月') : row.get('执行时间(月)'), date1904);
|
|
112
|
-
const header = { invoice: '业务日期', movement: '扫码日期', opening: '抽奖日期', terminal: '签约日期', inventory: '提交时间', tunzhihu: '业务日期', distributor: '动销日期 (日)' }[moduleId];
|
|
114
|
+
const header = { invoice: '业务日期', movement: '数据日期', scan: '扫码日期', opening: '抽奖日期', terminal: '签约日期', inventory: '提交时间', tunzhihu: '业务日期', distributor: '动销日期 (日)' }[moduleId];
|
|
113
115
|
return header ? sourceDate(row.get(header), date1904) : null;
|
|
114
116
|
}
|
|
115
117
|
/** Month-only source values (202307, 2023-07, 2023/7, 2023年7月, Excel date) → first day of that month. */
|
|
@@ -126,37 +128,62 @@ export async function inspectWorkbook({ file, moduleId, sha256, validation }) {
|
|
|
126
128
|
if (!moduleById.has(moduleId)) throw new Error('没有这个资料入口。');
|
|
127
129
|
validation ??= await validateWorkbook(file, moduleId);
|
|
128
130
|
if (!validation.ok) throw new Error('工作簿结构校验未通过,不能检查业务记录。');
|
|
129
|
-
const
|
|
130
|
-
const actualSha = createHash('sha256').update(bytes).digest('hex');
|
|
131
|
+
const actualSha = await hashWorkbook(file);
|
|
131
132
|
if (sha256 && actualSha !== sha256.toLowerCase()) throw new Error('检查时文件内容已变化,请重新上传。');
|
|
132
|
-
|
|
133
|
-
await
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
const count = Math.min(sheet.columnCount, moduleById.get(moduleId).sourceColumnLimit ?? sheet.columnCount);
|
|
138
|
-
const headers = Array.from({ length: count }, (_, index) => text(scalar(sheet.getRow(headerRow).getCell(index + 1).value)));
|
|
139
|
-
const rows = [];
|
|
140
|
-
sheet.eachRow({ includeEmpty: false }, (source, row) => {
|
|
141
|
-
if (row <= headerRow) return;
|
|
142
|
-
const values = headers.map((_, index) => scalar(source.getCell(index + 1).value));
|
|
143
|
-
if (values.some(value => text(value) !== '')) rows.push({ row, sheet: sheet.name, values });
|
|
144
|
-
});
|
|
145
|
-
return inspectRows({ moduleId, headers, rows, sheet: sheet.name, sha256: actualSha, date1904: workbook.properties.date1904, sourceFormat: validation.sourceFormat });
|
|
133
|
+
let inspector;
|
|
134
|
+
await streamValidatedRows(file, validation, moduleById.get(moduleId).sourceColumnLimit,
|
|
135
|
+
(headers, date1904) => { inspector = rowInspector({ moduleId, headers, sheet: validation.sheet, sha256: actualSha, date1904, sourceFormat: validation.sourceFormat }); },
|
|
136
|
+
row => inspector.row(row), { preserveMerges: moduleId === 'scan' });
|
|
137
|
+
return inspector.result();
|
|
146
138
|
}
|
|
147
139
|
|
|
148
|
-
export function inspectRows({
|
|
140
|
+
export function inspectRows({ rows, ...options }) {
|
|
141
|
+
const inspector = rowInspector(options);
|
|
142
|
+
for (const row of rows) inspector.row(row);
|
|
143
|
+
return inspector.result();
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const inspectionFormatKey = (id, sheet, format, normalizedHeaders) =>
|
|
147
|
+
hash([VERSION, id, sheet, format ?? '', [...normalizedHeaders].sort()]);
|
|
148
|
+
|
|
149
|
+
export async function legacyScanRuleFormats(state, dataDir) {
|
|
150
|
+
const oldFormats = new Map();
|
|
151
|
+
if (!state.review?.organizationRules?.some(rule => rule.moduleId === 'movement')) return oldFormats;
|
|
152
|
+
for (const upload of state.uploads) if (isLegacyScanUpload(upload) && /^[A-Za-z0-9_-]+$/.test(upload.id)) {
|
|
153
|
+
try {
|
|
154
|
+
const saved = JSON.parse(await readFile(resolve(dataDir, 'uploads', upload.id, 'inspection.json'), 'utf8'));
|
|
155
|
+
if (saved.version !== VERSION || saved.moduleId !== 'movement' || saved.sha256 !== upload.sha256 || !/^[a-f0-9]{64}$/.test(saved.formatKey)) continue;
|
|
156
|
+
const shas = oldFormats.get(saved.formatKey) ?? new Set();
|
|
157
|
+
shas.add(saved.sha256);
|
|
158
|
+
oldFormats.set(saved.formatKey, shas);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return oldFormats;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function reviewForSourceTemplates(review, oldFormats, scan) {
|
|
167
|
+
if (!review || !oldFormats.size) return review;
|
|
168
|
+
return { ...review, organizationRules: review.organizationRules.map(rule =>
|
|
169
|
+
rule.moduleId === 'movement' && oldFormats.has(rule.formatKey)
|
|
170
|
+
? { ...rule, moduleId: 'scan', formatKey: scan && (scan.legacyFormatKey === rule.formatKey || oldFormats.get(rule.formatKey).has(scan.sha256)) ? scan.formatKey : rule.formatKey }
|
|
171
|
+
: rule) };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function rowInspector({ moduleId, headers, sheet, sha256, date1904 = false, sourceFormat }) {
|
|
149
175
|
if (!moduleById.has(moduleId)) throw new Error('未知板块,无法检查。');
|
|
150
176
|
const limited = headers.slice(0, moduleById.get(moduleId).sourceColumnLimit ?? headers.length);
|
|
151
177
|
const normalized = limited.map(header => normalizeHeader(header));
|
|
152
178
|
const positions = new Map(normalized.map((header, index) => [header, index]));
|
|
153
|
-
const
|
|
154
|
-
const formatKey = hash([VERSION, moduleId, sheet, sourceFormat ?? '', sortedHeaders]);
|
|
179
|
+
const formatKey = inspectionFormatKey(moduleId, sheet, sourceFormat, normalized);
|
|
155
180
|
const inspected = { version: VERSION, moduleId, sha256, sheet, formatKey, sourceFormat: sourceFormat ?? null,
|
|
156
|
-
rowCount:
|
|
181
|
+
rowCount: 0, coverage: { start: null, end: null }, groups: [], organizations: [], errors: [] };
|
|
182
|
+
if (moduleId === 'scan') inspected.legacyFormatKey = inspectionFormatKey('movement', sheet, sourceFormat, normalized);
|
|
157
183
|
const candidates = new Map(), organizations = new Map(), occurrences = new Map(), missingIdentityRows = [];
|
|
158
184
|
const duplicatesAllowed = moduleId === 'invoice' || moduleId === 'terminal';
|
|
159
|
-
|
|
185
|
+
function addRow(source) {
|
|
186
|
+
inspected.rowCount++;
|
|
160
187
|
const row = { ...source, sheet: source.sheet ?? sheet, get: fieldAccess(limited, source.values, positions) };
|
|
161
188
|
const date = recordDate(moduleId, row, date1904);
|
|
162
189
|
if (date) {
|
|
@@ -170,13 +197,13 @@ export function inspectRows({ moduleId, headers, rows, sheet, sha256, date1904 =
|
|
|
170
197
|
if (date) { if (!org.start || date < org.start) org.start = date; if (!org.end || date > org.end) org.end = date; }
|
|
171
198
|
else org.missingDates++;
|
|
172
199
|
organizations.set(orgKey, org);
|
|
173
|
-
if (!duplicatesAllowed)
|
|
200
|
+
if (!duplicatesAllowed) return;
|
|
174
201
|
const values = Object.fromEntries(limited.map((header, index) => [header, scalar(row.values[index])]));
|
|
175
202
|
const canonicalFields = normalized.map((header, index) => [header, canonical(header, row.values[index], date1904)]).sort((a, b) => a[0].localeCompare(b[0]));
|
|
176
203
|
let identity;
|
|
177
204
|
if (moduleId === 'invoice') {
|
|
178
205
|
const fields = ['单据类型', '单据编码', '单据行号'].map(field => text(row.get(field)));
|
|
179
|
-
if (fields.some(value => !value)) { missingIdentityRows.push(row.row);
|
|
206
|
+
if (fields.some(value => !value)) { missingIdentityRows.push(row.row); return; }
|
|
180
207
|
identity = JSON.stringify(fields);
|
|
181
208
|
} else identity = JSON.stringify(canonicalFields.filter(([header]) => header !== normalizeHeader('协议编号')));
|
|
182
209
|
const fingerprint = hash([formatKey, canonicalFields]);
|
|
@@ -187,15 +214,18 @@ export function inspectRows({ moduleId, headers, rows, sheet, sha256, date1904 =
|
|
|
187
214
|
const group = candidates.get(identity) ?? [];
|
|
188
215
|
group.push(evidence); candidates.set(identity, group);
|
|
189
216
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
217
|
+
function result() {
|
|
218
|
+
if (missingIdentityRows.length) inspected.errors.push(`${missingIdentityRows.length} 行缺少单据类型、编码或行号,无法核对身份;Excel 行号:${missingIdentityRows.slice(0, 30).join('、')}${missingIdentityRows.length > 30 ? '等' : ''}。请补充来源后重新上传。`);
|
|
219
|
+
for (const [identity, members] of candidates) {
|
|
220
|
+
if (members.length < 2) continue;
|
|
221
|
+
const key = hash([VERSION, moduleId, formatKey, identity, members.map(member => member.key).sort()]);
|
|
222
|
+
inspected.groups.push({ id: key, key, reason: moduleId === 'invoice' ? '单据类型、单据编码和单据行号相同,需要确认哪些记录计入。' : '前 36 列除协议编号外内容相同,需要确认哪些协议计入。',
|
|
223
|
+
rows: members, differentFields: limited.filter(header => new Set(members.map(member => JSON.stringify(canonical(normalizeHeader(header), member.values[header], date1904)))).size > 1) });
|
|
224
|
+
}
|
|
225
|
+
inspected.organizations = [...organizations.values()].sort((a, b) => pathKey(a.path).localeCompare(pathKey(b.path)));
|
|
226
|
+
return inspected;
|
|
196
227
|
}
|
|
197
|
-
|
|
198
|
-
return inspected;
|
|
228
|
+
return { row: addRow, result };
|
|
199
229
|
}
|
|
200
230
|
|
|
201
231
|
function legacySelection(inspection, group, legacy) {
|