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,19 +3,21 @@
3
3
  // replaced as a whole but go through the same check card. The composed
4
4
  // workbook is written as an ordinary source so validation, inspection,
5
5
  // review decisions and generation keep their existing contracts.
6
+ import { createDecimalSum } from '../real-data/decimal-sum.mjs';
7
+ import { isDealerMovement } from '../modules/movement/index.mjs';
6
8
  import ExcelJS from 'exceljs';
7
- import { normalizeHeader } from '../modules.mjs';
9
+ import { moduleById, normalizeHeader } from '../modules.mjs';
8
10
  import { sourceDate, monthDay } from '../review-engine.mjs';
9
11
  import { streamSheetRows } from './xlsx-rows.mjs';
10
12
 
11
- export const AGGREGATE_VERSION = 2;
13
+ export const AGGREGATE_VERSION = 3;
12
14
  // A field may name several headers; the first one present in the file is used.
13
15
  export const FLOW = {
14
16
  invoice: { date: '业务日期', org: ['销售大区', '办事处'], amount: '发票金额', quantity: '计价数量', key: ['单据类型', '单据编码', '单据行号'], overlapAllowed: true },
15
- movement: { date: '扫码日期', org: ['大区名称', '办事处名称'], amount: '扫码金额', quantity: '扫码件数', bottles: '扫码数量(瓶)' },
17
+ movement: { date: '数据日期', org: ['大区', '办事处'], amount: '总动销金额', quantity: '总动销数量', documentFilter: isDealerMovement },
18
+ scan: { date: '扫码日期', org: ['大区名称', '办事处名称'], amount: '扫码金额', quantity: '扫码件数', bottles: '扫码数量(瓶)' },
16
19
  opening: { date: '抽奖日期', org: ['产品所属-大区', '产品所属-办事处'], city: '开瓶城市', amount: '开瓶金额', bottles: '开瓶瓶数' },
17
20
  // Inventory: compared and replaced by the day of 提交时间, which itself keeps its seconds.
18
- // 2026-11-27:藏10、吞之乎平台计入发票,分销商动销作参考;宴席改为按执行月份累加。
19
21
  // month: 日期列只到月份,按该月 1 日参与比较与替换(同月重复上传即按月整段替换)。
20
22
  zang10: { date: '订单归属年月', month: true, org: ['大区', '办事处'], amount: '订单金额(元)', quantity: '购货数量\n(件)' },
21
23
  tunzhihu: { date: '业务日期', org: ['大区', '办事处'], amount: '发票金额', quantity: '数量(件)' },
@@ -31,14 +33,15 @@ export const WHOLE = {
31
33
  // Export scope check (contract §11.4). Empty list: the board has no such field.
32
34
  export const SCOPE = {
33
35
  invoice: { zone: ['战区名称'], region: ['销售大区'], product: ['品种'], productLabel: '品种' },
34
- movement: { zone: ['战区名称'], region: ['大区名称'], product: ['品种名称'], productLabel: '品种' },
36
+ movement: { zone: ['战区'], region: ['大区'], product: ['品种'], productLabel: '品种' },
37
+ scan: { zone: ['战区名称'], region: ['大区名称'], product: ['品种名称'], productLabel: '品种' },
35
38
  opening: { zone: ['产品所属-战区'], region: ['产品所属-大区'], product: ['品种'], productLabel: '品种' },
36
39
  inventory: { zone: ['战区名称'], region: ['大区', '大区名称'], product: ['产品名称', '产品编码'], productLabel: '产品' },
37
40
  terminal: { zone: ['战区名称'], region: ['大区'], product: ['签约品种'], productLabel: '签约品种' },
38
41
  banquet: { zone: [], region: ['大区'], product: [], productLabel: '产品' },
39
42
  zang10: { zone: ['战区'], region: ['大区'], product: [], productLabel: '产品' },
40
43
  tunzhihu: { zone: ['战区'], region: ['大区'], product: [], productLabel: '产品' },
41
- distributor: { zone: ['战区'], region: ['大区'], product: [], productLabel: '产品' },
44
+ distributor: { zone: ['战区'], region: ['大区'], product: ['品种', '产品名称'], productLabel: '产品' },
42
45
  };
43
46
  export const PRODUCT_RULE = { windowMin: 3, fileMax: 1, minRows: 20, fallbackDays: 30 };
44
47
  export const MODES = ['incremental', 'range', 'full'];
@@ -55,11 +58,16 @@ export class TemplateMismatchError extends Error {
55
58
  }
56
59
  /** Stand-in for a current source saved under an older template: it can only be replaced as a whole. */
57
60
  export function outdatedBase(moduleId, reason) {
58
- return { version: AGGREGATE_VERSION, moduleId, outdated: true, reason: reason || `当前有效版本缺少${FLOW[moduleId]?.date ?? '必需'}列,是旧模板文件。` };
61
+ return { version: AGGREGATE_VERSION, moduleId, outdated: true, reason: reason || '当前有效版本缺少现行模板必需字段,是旧模板文件。' };
59
62
  }
60
- /** A cached aggregate built from a file without the current date column is stale as well. */
63
+ function missingTemplateHeaders(moduleId, headers) {
64
+ const required = moduleId === 'distributor' ? moduleById.get(moduleId).requiredHeaders : [FLOW[moduleId].date];
65
+ const actual = new Set(headers.map(normalizeHeader));
66
+ return required.filter(header => !actual.has(normalizeHeader(header)));
67
+ }
68
+ /** A cached aggregate built from a file without the current required fields is stale as well. */
61
69
  export const aggregateMatchesTemplate = (moduleId, aggregate) => !FLOW[moduleId] || !aggregate?.headers
62
- || aggregate.headers.some(header => normalizeHeader(header) === normalizeHeader(FLOW[moduleId].date));
70
+ || !missingTemplateHeaders(moduleId, aggregate.headers).length;
63
71
  const DAY = /^\d{4}-\d{2}-\d{2}$/;
64
72
  export const validDay = value => typeof value === 'string' && DAY.test(value) && sourceDate(value) === value;
65
73
  const shiftDay = (day, offset) => { const d = new Date(`${day}T00:00:00Z`); d.setUTCDate(d.getUTCDate() + offset); return d.toISOString().slice(0, 10); };
@@ -127,6 +135,8 @@ export async function streamSource(file, validation, moduleId, onHeader, onRow)
127
135
  dateColumn = headers.findIndex(header => normalizeHeader(header) === normalizeHeader(spec.date));
128
136
  get = accessor(headers);
129
137
  if (dateColumn < 0) throw new TemplateMismatchError(`缺少日期字段:${spec.date}。`);
138
+ const missing = missingTemplateHeaders(moduleId, headers);
139
+ if (missing.length) throw new TemplateMismatchError(`当前有效版本缺少字段:${missing.join('、')}。`);
130
140
  await onHeader({ sheetName: validation.sheet, headers, dateColumn, format: validation.sourceFormat ?? null });
131
141
  return;
132
142
  }
@@ -140,7 +150,7 @@ export async function streamSource(file, validation, moduleId, onHeader, onRow)
140
150
  // composed workbook cannot shift them. Inventory keeps the time of day.
141
151
  if (day && typeof raw === 'number' && !spec.month) values[dateColumn] = spec.time ? serialDateTime(raw, date1904Ref.value) : new Date(`${day}T00:00:00Z`);
142
152
  await onRow({ row: rowNumber, values, date: day });
143
- }, date1904Ref);
153
+ }, date1904Ref, { preserveMerges: moduleId === 'scan' });
144
154
  if (!headers) throw new Error('已验证的工作表无法读取。');
145
155
  return result;
146
156
  }
@@ -160,24 +170,43 @@ function scopeHas(get, moduleId) {
160
170
  return { zone: get.has(spec.zone), region: get.has(spec.region), product: get.has(spec.product) };
161
171
  }
162
172
 
173
+ const exactMovement = id => id === 'movement' || id === 'distributor';
174
+ const movementMeasures = ['amount', 'quantity'];
175
+
163
176
  /** Per-day totals, organizations and scope values, small enough to keep beside a source. */
164
177
  export function aggregator(moduleId) {
165
178
  const spec = FLOW[moduleId], scope = SCOPE[moduleId], byDate = {}, invalidRows = [], zones = new Set(), days = new Map(), skipped = { rows: 0, valued: [], bottles: 0 };
179
+ const exact = exactMovement(moduleId), regionZones = new Map();
166
180
  let get = null, headers = [], rows = 0, format = null;
167
181
  return {
168
182
  header(info) { headers = info.headers; format = info.format ?? null; get = accessor(info.headers); },
169
183
  row({ row, values, date, skipped: skip, valued }) {
170
184
  if (skip) { skipped.rows++; if (valued) { skipped.valued.push(row); skipped.bottles += spec.bottles ? number(get(values, spec.bottles)) ?? 0 : 0; } return; }
171
185
  rows++;
172
- addTo(zones, get(values, scope.zone));
186
+ const region = text(get(values, spec.org[0])), zone = text(get(values, scope.zone));
187
+ addTo(zones, zone);
188
+ if (region) {
189
+ const known = regionZones.get(region) ?? new Set();
190
+ known.add(zone);
191
+ regionZones.set(region, known);
192
+ }
173
193
  if (!date) { invalidRows.push(row); return; }
174
194
  let day = days.get(date);
175
- if (!day) { day = { rows: 0, amount: 0, quantity: 0, bottles: 0, regions: new Set(), offices: new Set(), cities: new Set(), dealers: new Set(), products: new Set() }; days.set(date, day); }
195
+ if (!day) {
196
+ day = { rows: 0, amount: 0, quantity: 0, bottles: 0, regions: new Set(), offices: new Set(), cities: new Set(), dealers: new Set(), products: new Set() };
197
+ if (exact) day.decimal = { amount: createDecimalSum(), quantity: createDecimalSum() };
198
+ days.set(date, day);
199
+ }
176
200
  day.rows++;
177
- if (spec.amount) day.amount += number(get(values, spec.amount)) ?? 0;
178
- if (spec.quantity) day.quantity += number(get(values, spec.quantity)) ?? 0;
201
+ if (!spec.documentFilter || spec.documentFilter(text(get(values, '单据类型')))) {
202
+ for (const field of movementMeasures) if (spec[field]) {
203
+ const value = number(get(values, spec[field]));
204
+ if (!exact) day[field] += value ?? 0;
205
+ else if (value === null) day.decimal[field] = null;
206
+ else day.decimal[field]?.add(value);
207
+ }
208
+ }
179
209
  if (spec.bottles) day.bottles += number(get(values, spec.bottles)) ?? 0;
180
- const region = text(get(values, spec.org[0]));
181
210
  addTo(day.regions, region);
182
211
  addTo(day.offices, [region, text(get(values, spec.org[1]))].filter(Boolean).join(' / '));
183
212
  if (spec.city) addTo(day.cities, get(values, spec.city));
@@ -190,13 +219,16 @@ export function aggregator(moduleId) {
190
219
  for (const value of day.regions) regions.add(value);
191
220
  for (const value of day.products) products.add(value);
192
221
  byDate[date] = { rows: day.rows, amount: round(day.amount), quantity: round(day.quantity), bottles: round(day.bottles),
222
+ ...(exact ? { amount: day.decimal.amount?.value() ?? null, quantity: day.decimal.quantity?.value() ?? null,
223
+ decimal: { amount: day.decimal.amount?.exact() ?? null, quantity: day.decimal.quantity?.exact() ?? null } } : {}),
193
224
  regions: sorted(day.regions), offices: sorted(day.offices), cities: sorted(day.cities), dealers: sorted(day.dealers), products: sorted(day.products) };
194
225
  }
195
226
  const dates = Object.keys(byDate).sort();
196
227
  return { version: AGGREGATE_VERSION, moduleId, format, rows, start: dates[0] ?? null, end: dates.at(-1) ?? null,
197
228
  invalidDateRows: invalidRows.length, invalidDateSample: invalidRows.slice(0, 20), byDate, headers,
198
229
  skippedRows: skipped.rows, skippedValuedRows: skipped.valued.length, skippedValuedSample: skipped.valued.slice(0, 20), skippedBottles: round(skipped.bottles),
199
- has: get ? scopeHas(get, moduleId) : { zone: false, region: false, product: false }, zones: sorted(zones), regions: sorted(regions), products: sorted(products) };
230
+ has: get ? scopeHas(get, moduleId) : { zone: false, region: false, product: false }, zones: sorted(zones), regions: sorted(regions), products: sorted(products),
231
+ regionZones: Object.fromEntries([...regionZones].map(([region, values]) => [region, sorted(values)])) };
200
232
  },
201
233
  };
202
234
  }
@@ -241,6 +273,8 @@ export async function summarizeFile(file, validation, moduleId) {
241
273
  }
242
274
 
243
275
  /** Rows of the new file whose identity key already exists on the same day in the current source (classification only). */
276
+ export const hasKeyMatcher = moduleId => Boolean(FLOW[moduleId]?.key);
277
+
244
278
  export function keyMatcher(moduleId, part) {
245
279
  const spec = FLOW[moduleId];
246
280
  if (!spec?.key) return null;
@@ -283,16 +317,23 @@ export function suggestMode(base, part) {
283
317
  }
284
318
 
285
319
  /** Totals over several (byDate, days) parts; dealers are counted once across parts. */
286
- function totals(parts) {
320
+ function totals(parts, moduleId) {
287
321
  const result = { rows: 0, amount: 0, quantity: 0, bottles: 0, days: 0, dealers: 0 };
288
322
  const dealers = new Set(), seenDays = new Set();
323
+ const decimal = exactMovement(moduleId) ? { amount: createDecimalSum(), quantity: createDecimalSum() } : null;
289
324
  for (const [byDate, days] of parts) for (const day of days) {
290
325
  const value = byDate[day]; if (!value) continue;
291
- result.rows += value.rows; result.amount += value.amount; result.quantity += value.quantity; result.bottles += value.bottles;
326
+ result.rows += value.rows; result.bottles += value.bottles;
327
+ for (const field of movementMeasures) {
328
+ if (!decimal) result[field] += value[field];
329
+ else if (value[field] === null) decimal[field] = null;
330
+ else decimal[field]?.add(value.decimal?.[field] ?? value[field]);
331
+ }
292
332
  seenDays.add(day);
293
333
  for (const dealer of value.dealers ?? []) dealers.add(dealer);
294
334
  }
295
- for (const key of ['amount', 'quantity', 'bottles']) result[key] = round(result[key]);
335
+ for (const field of movementMeasures) result[field] = decimal ? decimal[field]?.value() ?? null : round(result[field]);
336
+ result.bottles = round(result.bottles);
296
337
  result.days = seenDays.size; result.dealers = dealers.size;
297
338
  return result;
298
339
  }
@@ -302,14 +343,15 @@ const months = days => [...new Set(days.map(day => day.slice(0, 7)))].sort();
302
343
 
303
344
  const FIGURES = {
304
345
  invoice: [['行数', 'rows', 'count'], ['发票净额(万元)', 'amount', 'wan']],
305
- movement: [['行数', 'rows', 'count'], ['扫码金额(万元)', 'amount', 'wan'], ['扫码件数', 'quantity', 'count'], ['扫码瓶数', 'bottles', 'count']],
346
+ movement: [['行数', 'rows', 'count'], ['动销净额(万元)', 'amount', 'wan'], ['动销件数', 'quantity', 'count']],
347
+ scan: [['行数', 'rows', 'count'], ['扫码金额(万元)', 'amount', 'wan'], ['扫码件数', 'quantity', 'count'], ['扫码瓶数', 'bottles', 'count']],
306
348
  opening: [['行数', 'rows', 'count'], ['开瓶瓶数', 'bottles', 'count'], ['开瓶金额(万元)', 'amount', 'wan']],
307
349
  inventory: [['盘点记录', 'rows', 'count'], ['经销商', 'dealers', 'count']],
308
350
  terminal: [['协议数', 'agreements', 'count'], ['签约终端', 'outlets', 'count']],
309
351
  banquet: [['执行场次', 'quantity', 'count'], ['开瓶瓶数', 'bottles', 'count']],
310
352
  zang10: [['行数', 'rows', 'count'], ['订单金额(万元)', 'amount', 'wan']],
311
353
  tunzhihu: [['行数', 'rows', 'count'], ['发票金额(万元)', 'amount', 'wan']],
312
- distributor: [['行数', 'rows', 'count'], ['动销金额(万元)', 'amount', 'wan']],
354
+ distributor: [['行数', 'rows', 'count'], ['动销净额(万元)', 'amount', 'wan'], ['动销件数', 'quantity', 'count']],
313
355
  };
314
356
  const figures = (moduleId, before, after) => FIGURES[moduleId].map(([label, key, unit]) => ({ label, key, unit, before: before ? before[key] ?? null : null, after: after ? after[key] ?? null : null }));
315
357
  const listText = (values, limit = 3) => `${values.slice(0, limit).join('、')}${values.length > limit ? ` 等 ${values.length} 个` : ''}`;
@@ -335,7 +377,15 @@ export function scopeCheck(moduleId, base, part) {
335
377
  if (!part.has?.[dim] || !base.has?.[dim] || !base[list]?.length) { unchecked.push(`${label}(${!part.has?.[dim] ? '新文件' : '当前数据'}没有该字段)`); continue; }
336
378
  result.checked[dim] = true;
337
379
  const known = new Set(base[list]), extra = (part[list] ?? []).filter(value => !known.has(value));
338
- if (extra.length) result.blocked.push(`文件包含当前数据没有的${label}:${listText(extra)}`);
380
+ // 只有同一战区内新增的大区允许整份替换时确认放行;出现其他战区仍视为导错范围。
381
+ if (extra.length) {
382
+ const message = `文件包含当前数据没有的${label}:${listText(extra)}`;
383
+ result.blocked.push(message);
384
+ if (dim === 'region' && result.checked.zone && extra.every(region => {
385
+ const zones = part.regionZones?.[region];
386
+ return zones?.length && zones.every(zone => zone && base.zones.includes(zone));
387
+ })) (result.newOrganizations ||= []).push(message);
388
+ }
339
389
  }
340
390
  const productLabel = spec.productLabel;
341
391
  if (!spec.product.length) unchecked.push(`${productLabel}(表中没有该字段)`);
@@ -351,12 +401,22 @@ export function scopeCheck(moduleId, base, part) {
351
401
  if (result.blocked.length) {
352
402
  const zones = base.zones ?? [];
353
403
  const scopeName = zones.length && zones.length <= 3 ? zones.join('、') : '当前组织范围';
354
- result.advice = `请在系统里按「${scopeName}${spec.product.length ? '、全部产品' : ''}」重新导出${base.byDate ? '最近 7 天' : ''},再拖进来。`;
404
+ result.advice = `请在系统里按「${scopeName}${spec.product.length ? '、全部产品' : ''}」重新导出${!base.byDate ? '' : FLOW[moduleId]?.month ? '对应月份' : '最近 7 天'},再拖进来。`;
355
405
  result.ok = false;
356
406
  }
357
407
  return result;
358
408
  }
359
409
 
410
+ /**
411
+ * 整份替换时,新文件出现同一战区内当前数据没有的大区可能是正常扩充(例如换成覆盖更广的新模板),
412
+ * 不再直接拦下,改为提醒并勾选确认后提交;产品数量异常等疑似导漏的检查仍然拦下。
413
+ */
414
+ function relaxForFull(scope) {
415
+ if (!scope.newOrganizations?.length) return { scope, newOrganizations: [] };
416
+ const blocked = scope.blocked.filter(message => !scope.newOrganizations.includes(message));
417
+ return { scope: { ...scope, blocked, ok: blocked.length === 0, advice: blocked.length ? scope.advice : '' }, newOrganizations: scope.newOrganizations };
418
+ }
419
+
360
420
  /** What an update will change. Used for the check card and enforced again on apply. */
361
421
  export function receipt({ moduleId, base, part, mode, start, end, existingByDate = {} }) {
362
422
  if (isWholeModule(moduleId)) return wholeReceipt({ moduleId, base, part, mode });
@@ -374,6 +434,7 @@ export function receipt({ moduleId, base, part, mode, start, end, existingByDate
374
434
  if (part.skippedValuedRows) warnings.push(`${part.skippedValuedRows} 行没有${spec.date}却有数值(开瓶 ${part.skippedBottles} 瓶;Excel 行号:${part.skippedValuedSample.join('、')}${part.skippedValuedRows > part.skippedValuedSample.length ? '等' : ''}),不归入任何月份、不计入。`);
375
435
  if (part.invalidDateRows) blocked.push(`${part.invalidDateRows} 行${spec.date}无效(Excel 行号:${part.invalidDateSample.join('、')}${part.invalidDateRows > part.invalidDateSample.length ? '等' : ''}),请修正后重新导出。`);
376
436
  if (mode !== 'full' && base && (base.format ?? null) !== (part.format ?? null)) blocked.push('文件格式与当前数据不同,只能整份替换。');
437
+ const total = parts => totals(parts, moduleId);
377
438
  let window, after, before, disappearing = [], missing = { regions: [], offices: [], cities: [] };
378
439
  if (mode === 'range') {
379
440
  if (!validDay(start) || !validDay(end) || start > end) { blocked.push('请填写有效的起止日期(开始不晚于结束)。'); start = part.start; end = part.end; }
@@ -381,7 +442,7 @@ export function receipt({ moduleId, base, part, mode, start, end, existingByDate
381
442
  if (outside.length) blocked.push(`文件有 ${outside.reduce((n, day) => n + partBy[day].rows, 0)} 行日期不在替换区间内(${outside[0]}${outside.length > 1 ? ` 等 ${outside.length} 天` : ''}),请调整区间或重新导出。`);
382
443
  window = day => day >= start && day <= end;
383
444
  const baseDays = listDays(baseBy, window);
384
- before = totals([[baseBy, baseDays]]); after = totals([[partBy, partDays.filter(window)]]);
445
+ before = total([[baseBy, baseDays]]); after = total([[partBy, partDays.filter(window)]]);
385
446
  disappearing = baseDays.filter(day => !partBy[day]);
386
447
  } else if (mode === 'incremental') {
387
448
  const overlap = partDays.filter(day => baseBy[day]);
@@ -390,11 +451,11 @@ export function receipt({ moduleId, base, part, mode, start, end, existingByDate
390
451
  if (moduleId === 'invoice' && existing) warnings.push(`有 ${existing} 行的单据类型、编码和行号在同一天已经存在,追加后会进入重复候选检查;建议改用范围更新。`);
391
452
  if (moduleId === 'inventory' && existing) warnings.push(`有 ${existing} 行的经销商编码、产品和提交时间与现有记录相同,追加后作为并列记录保留(不自动去重);建议改用范围更新。`);
392
453
  // Incremental compares the whole current source with the source after appending.
393
- before = totals([[baseBy, baseAll]]); after = totals([[baseBy, baseAll], [partBy, partDays]]);
454
+ before = total([[baseBy, baseAll]]); after = total([[baseBy, baseAll], [partBy, partDays]]);
394
455
  window = day => partBy[day];
395
456
  } else {
396
457
  window = () => true;
397
- before = totals([[baseBy, baseAll]]); after = totals([[partBy, partDays]]);
458
+ before = total([[baseBy, baseAll]]); after = total([[partBy, partDays]]);
398
459
  if (base?.start && part.start && part.start > base.start) warnings.push(`历史起点从 ${base.start} 变为 ${part.start},之前的数据会被移除。`);
399
460
  if (base?.end && part.end && part.end < base.end) warnings.push(`最新日期从 ${base.end} 倒退到 ${part.end}。`);
400
461
  const lost = months(baseAll).filter(month => !partDays.some(day => day.startsWith(month)));
@@ -408,15 +469,16 @@ export function receipt({ moduleId, base, part, mode, start, end, existingByDate
408
469
  }
409
470
  if (moduleId !== 'opening') missing.cities = [];
410
471
  }
411
- const scope = scopeCheck(moduleId, base, part);
472
+ const checked = scopeCheck(moduleId, base, part);
473
+ const { scope, newOrganizations } = mode === 'full' ? relaxForFull(checked) : { scope: checked, newOrganizations: [] };
412
474
  blocked.push(...scope.blocked);
413
- const requiresConfirmation = missing.regions.length + missing.offices.length + missing.cities.length > 0;
475
+ const requiresConfirmation = missing.regions.length + missing.offices.length + missing.cities.length + newOrganizations.length > 0;
414
476
  const parts = [];
415
477
  if (missing.regions.length) parts.push(`大区:${missing.regions.join('、')}`);
416
478
  if (missing.offices.length) parts.push(`办事处:${listText(missing.offices, 6)}`);
417
479
  if (missing.cities.length) parts.push(`城市:${listText(missing.cities, 6)}`);
418
480
  const existingRows = Object.entries(existingByDate).filter(([day]) => window(day)).reduce((n, [, value]) => n + value, 0);
419
- const identity = spec.key ? { existing: existingRows, added: Math.max(0, totals([[partBy, partDays.filter(window)]]).rows - existingRows),
481
+ const identity = spec.key ? { existing: existingRows, added: Math.max(0, total([[partBy, partDays.filter(window)]]).rows - existingRows),
420
482
  label: moduleId === 'invoice' ? '单据类型+编码+行号' : '经销商编码+产品+提交时间' } : null;
421
483
  const outStart = mode === 'range' ? start : part.start, outEnd = mode === 'range' ? end : part.end;
422
484
  return {
@@ -424,7 +486,8 @@ export function receipt({ moduleId, base, part, mode, start, end, existingByDate
424
486
  windowLabel: mode === 'range' ? `替换 ${outStart} ~ ${outEnd}` : mode === 'incremental' ? `追加 ${part.start} ~ ${part.end}` : '整份替换',
425
487
  file: { rows: part.rows, start: part.start, end: part.end }, before, after, figures: figures(moduleId, before, after),
426
488
  disappearingDates: disappearing, missingOrganizations: missing, requiresConfirmation,
427
- confirmation: requiresConfirmation ? { message: `组织缺失提醒:区间内的旧数据有、新文件里没有的 ${parts.join(';')}。可能导出时只选了部分组织。`, label: '我已核对,这些组织在区间内确实没有数据' } : null,
489
+ confirmation: requiresConfirmation ? { message: [parts.length ? `组织缺失提醒:区间内的旧数据有、新文件里没有的 ${parts.join(';')}。可能导出时只选了部分组织。` : '', newOrganizations.length ? `组织新增提醒:${newOrganizations.join(';')}。整份替换后看板会包含这些组织;如果不是有意扩大范围,请重新导出。` : ''].filter(Boolean).join(' '),
490
+ label: parts.length ? '我已核对,这些组织变化属实' : '我已核对,新增的组织属实' } : null,
428
491
  identity, invoiceIdentity: moduleId === 'invoice' ? { existing: identity.existing, added: identity.added } : null,
429
492
  scope, blocked, warnings,
430
493
  };
@@ -447,8 +510,13 @@ export function wholeReceipt({ moduleId, base, part, mode = 'full' }) {
447
510
  if (base.end && part.end && part.end < base.end) warnings.push(`签约日期最新只到 ${part.end},早于当前数据的 ${base.end}。`);
448
511
  }
449
512
  }
450
- const scope = scopeCheck(moduleId, base, part);
513
+ const { scope, newOrganizations } = relaxForFull(scopeCheck(moduleId, base, part));
451
514
  blocked.push(...scope.blocked);
515
+ if (newOrganizations.length) {
516
+ const extra = `组织新增提醒:${newOrganizations.join(';')}。整份替换后看板会包含这些组织;如果不是有意扩大范围,请重新导出。`;
517
+ confirmation = confirmation ? { ...confirmation, message: `${confirmation.message} ${extra}` } : { message: extra, label: '我已核对,新增的组织属实' };
518
+ requiresConfirmation = true;
519
+ }
452
520
  return {
453
521
  moduleId, mode: 'full', modeLabel: MODE_LABELS.full, start: part.start, end: part.end, windowLabel: '整份替换',
454
522
  file: { rows: part.rows, start: part.start, end: part.end }, before: base ?? null, after: part, figures: figures(moduleId, base, part),
@@ -502,16 +570,19 @@ export async function writeSource(file, { sheetName, headers, rows, dateColumn,
502
570
  }
503
571
 
504
572
  /** Streaming composition: the current source is read once and never held in memory. */
505
- export async function composeFile({ baseFile, baseValidation, part, mode, start, end, outFile, moduleId }) {
573
+ export async function composeFile({ baseFile, baseValidation, part, partFile, partValidation, mode, start, end, outFile, moduleId }) {
506
574
  const keep = keeper(mode, start, end);
507
575
  let plan = null, out = null, kept = 0;
508
576
  await streamSource(baseFile, baseValidation, moduleId, info => {
509
577
  plan = layout(info.headers, part.headers);
510
578
  out = writer(outFile, info.sheetName, plan.headers, info.dateColumn, !!FLOW[moduleId].time);
511
579
  }, row => { if (keep(row)) { out.add(plan.widen(row.values)); kept++; } });
512
- for (const row of part.rows) out.add(plan.project(row.values));
580
+ let appended = 0;
581
+ const append = row => { out.add(plan.project(row.values)); appended++; };
582
+ if (Array.isArray(part.rows)) for (const row of part.rows) append(row);
583
+ else await streamSource(partFile, partValidation, moduleId, () => {}, append);
513
584
  await out.close();
514
- return { warnings: plan.warnings, kept, appended: part.rows.length, rows: kept + part.rows.length };
585
+ return { warnings: plan.warnings, kept, appended, rows: kept + appended };
515
586
  }
516
587
 
517
588
  /** Earlier source fingerprints this upload was composed from (newest first). */
@@ -1,9 +1,9 @@
1
- import { readSource, aggregate, aggregator, aggregateFile, keyMatcher, receipt, streamSource, composeFile, summarizeFile, isWholeModule, outdatedBase, aggregateMatchesTemplate } from './flow.mjs';
1
+ import { hasKeyMatcher, readSource, aggregate, aggregator, aggregateFile, keyMatcher, receipt, streamSource, composeFile, summarizeFile, isWholeModule, outdatedBase, aggregateMatchesTemplate } from './flow.mjs';
2
2
  import { streamSheetRows } from './xlsx-rows.mjs';
3
3
  import { sourceDate } from '../review-engine.mjs';
4
4
  import { normalizeHeader } from '../modules.mjs';
5
5
 
6
- const COVERAGE_DATE = { invoice: '业务日期', movement: '扫码日期', opening: '抽奖日期', terminal: '签约日期', inventory: '提交时间' };
6
+ const COVERAGE_DATE = { invoice: '业务日期', movement: '数据日期', scan: '扫码日期', opening: '抽奖日期', terminal: '签约日期', inventory: '提交时间' };
7
7
 
8
8
  /** Earliest and latest date of a source, for uploads saved before coverage was recorded. */
9
9
  async function coverageOf(file, validation, moduleId) {
@@ -16,7 +16,7 @@ async function coverageOf(file, validation, moduleId) {
16
16
  if (column < 0) return;
17
17
  const day = sourceDate(cells[column], ref.value);
18
18
  if (day) { if (!start || day < start) start = day; if (!end || day > end) end = day; }
19
- }, ref);
19
+ }, ref, { preserveMerges: moduleId === 'scan' });
20
20
  return { start, end };
21
21
  }
22
22
 
@@ -30,11 +30,11 @@ export async function runFlowJob(job) {
30
30
  return { part, base, existingByDate: {} };
31
31
  }
32
32
  if (job.kind === 'analyze') {
33
- const part = await readSource(job.partFile, job.partValidation, job.moduleId);
34
- const partAggregate = aggregate(part, job.moduleId);
33
+ const part = hasKeyMatcher(job.moduleId) ? await readSource(job.partFile, job.partValidation, job.moduleId) : null;
34
+ const partAggregate = part ? aggregate(part, job.moduleId) : await aggregateFile(job.partFile, job.partValidation, job.moduleId);
35
35
  if (!job.baseFile) return { part: partAggregate, base: null, existingByDate: {} };
36
36
  if (job.baseAggregate && !aggregateMatchesTemplate(job.moduleId, job.baseAggregate)) return { part: partAggregate, base: outdatedBase(job.moduleId), existingByDate: {} };
37
- const needAggregate = !job.baseAggregate, matcher = keyMatcher(job.moduleId, part);
37
+ const needAggregate = !job.baseAggregate, matcher = part ? keyMatcher(job.moduleId, part) : null;
38
38
  if (needAggregate || matcher) {
39
39
  const acc = needAggregate ? aggregator(job.moduleId) : null;
40
40
  try {
@@ -42,7 +42,7 @@ export async function runFlowJob(job) {
42
42
  info => { acc?.header(info); matcher?.header(info); }, row => { acc?.row(row); matcher?.row(row); });
43
43
  } catch (error) {
44
44
  // 模板已更新:旧文件缺少当前日期列,不能比对,只能整份替换。
45
- if (error?.code === 'TEMPLATE_MISMATCH') return { part: partAggregate, base: outdatedBase(job.moduleId), existingByDate: {} };
45
+ if (error?.code === 'TEMPLATE_MISMATCH') return { part: partAggregate, base: outdatedBase(job.moduleId, `当前有效版本是旧模板文件。${error.message}`), existingByDate: {} };
46
46
  throw error;
47
47
  }
48
48
  return { part: partAggregate, base: acc ? acc.result() : job.baseAggregate, existingByDate: matcher ? matcher.result() : {} };
@@ -50,15 +50,15 @@ export async function runFlowJob(job) {
50
50
  return { part: partAggregate, base: job.baseAggregate, existingByDate: {} };
51
51
  }
52
52
  if (job.kind === 'compose') {
53
- const part = await readSource(job.partFile, job.partValidation, job.moduleId);
54
- const partAggregate = aggregate(part, job.moduleId);
53
+ const part = hasKeyMatcher(job.moduleId) ? await readSource(job.partFile, job.partValidation, job.moduleId) : null;
54
+ const partAggregate = part ? aggregate(part, job.moduleId) : await aggregateFile(job.partFile, job.partValidation, job.moduleId);
55
55
  // Recheck against the files themselves rather than the earlier preview.
56
- const acc = aggregator(job.moduleId), matcher = keyMatcher(job.moduleId, part);
56
+ const acc = aggregator(job.moduleId), matcher = part ? keyMatcher(job.moduleId, part) : null;
57
57
  await streamSource(job.baseFile, job.baseValidation, job.moduleId, info => { acc.header(info); matcher?.header(info); }, row => { acc.row(row); matcher?.row(row); });
58
58
  const checked = receipt({ moduleId: job.moduleId, base: acc.result(), part: partAggregate, mode: job.mode, start: job.start, end: job.end, existingByDate: matcher ? matcher.result() : {} });
59
59
  if (checked.blocked.length) throw new Error(checked.blocked.join(' '));
60
60
  if (checked.requiresConfirmation && !job.confirmMissing) throw new Error('有组织在新文件里缺失,请先核对并确认后再提交。');
61
- const composed = await composeFile({ baseFile: job.baseFile, baseValidation: job.baseValidation, part, mode: job.mode, start: job.start, end: job.end, outFile: job.outFile, moduleId: job.moduleId });
61
+ const composed = await composeFile({ baseFile: job.baseFile, baseValidation: job.baseValidation, part: part ?? partAggregate, partFile: job.partFile, partValidation: job.partValidation, mode: job.mode, start: job.start, end: job.end, outFile: job.outFile, moduleId: job.moduleId });
62
62
  return { receipt: checked, warnings: [...checked.warnings, ...composed.warnings], kept: composed.kept, appended: composed.appended, rows: composed.rows };
63
63
  }
64
64
  throw new Error('Unknown flow operation');
@@ -1,12 +1,15 @@
1
1
  // Minimal streaming reader for one worksheet, built on the same yauzl + saxes
2
2
  // stack as the upload validator (exceljs' streaming reader rejects some real
3
3
  // exports). Values: string, number, boolean, Date (date-formatted cells) or null.
4
+ import { createHash } from 'node:crypto';
5
+ import { createReadStream } from 'node:fs';
4
6
  import yauzl from 'yauzl';
5
7
  import { SaxesParser } from 'saxes';
6
8
  import { posix } from 'node:path';
7
9
 
8
10
  const BUILTIN_DATE_FORMATS = new Set([14, 15, 16, 17, 18, 19, 20, 21, 22, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 45, 46, 47, 50, 51, 52, 53, 54, 55, 56, 57, 58]);
9
11
  const localName = node => node.name.split(':').at(-1);
12
+ const columnNumber = letters => [...letters].reduce((n, c) => n * 26 + c.charCodeAt(0) - 64, 0);
10
13
 
11
14
  export function isDateFormat(code) {
12
15
  if (!code) return false;
@@ -52,7 +55,7 @@ async function parseXml(archive, path, handlers, required = true) {
52
55
  * Stream the rows of the named sheet. onRow(rowNumber, values) may be async.
53
56
  * Returns { date1904 }.
54
57
  */
55
- export async function streamSheetRows(file, sheetName, onRow, ref = {}) {
58
+ export async function streamSheetRows(file, sheetName, onRow, ref = {}, { preserveMerges = false } = {}) {
56
59
  const archive = await openArchive(file);
57
60
  try {
58
61
  let date1904 = false;
@@ -73,6 +76,38 @@ export async function streamSheetRows(file, sheetName, onRow, ref = {}) {
73
76
  const path = sheet && relationships.get(sheet.relId);
74
77
  if (!path) throw new Error('已验证的工作表无法读取。');
75
78
 
79
+ // Excel stores merges after sheetData. Read their bounds first for scan
80
+ // uploads, then retain only the values of active merge masters.
81
+ const merges = [];
82
+ if (preserveMerges) await parseXml(archive, path, { opentag(node) {
83
+ if (localName(node) !== 'mergeCell') return;
84
+ const range = /^([A-Z]+)(\d+):([A-Z]+)(\d+)$/.exec(node.attributes.ref);
85
+ if (!range) return;
86
+ const [, first, top, last, bottom] = range;
87
+ const left = columnNumber(first), right = columnNumber(last);
88
+ if (left > right || right > 512 || Number(top) < 1 || Number(top) > Number(bottom) || Number(bottom) > 1_000_001) throw new Error('合并单元格超出工作表行列限制。');
89
+ merges.push({ top: Number(top), left, bottom: Number(bottom), right, value: null });
90
+ } });
91
+ merges.sort((a, b) => a.top - b.top || a.left - b.left);
92
+ let nextMerge = 0, lastRow = 0, activeMerges = [];
93
+ const emit = async (row, cells) => {
94
+ while (nextMerge < merges.length && merges[nextMerge].top <= row) activeMerges.push(merges[nextMerge++]);
95
+ activeMerges = activeMerges.filter(item => item.bottom >= row);
96
+ for (const item of activeMerges) {
97
+ if (item.top === row) item.value = cells[item.left - 1] ?? null;
98
+ for (let col = item.left; col <= item.right; col++) cells[col - 1] = item.value;
99
+ }
100
+ await onRow(row, cells);
101
+ };
102
+ const flushGaps = async row => {
103
+ while (lastRow + 1 < row) {
104
+ const nextTop = merges[nextMerge]?.top ?? row;
105
+ const next = activeMerges.some(item => item.bottom > lastRow && item.value != null) ? lastRow + 1 : nextTop;
106
+ if (next >= row) break;
107
+ await emit(next, []);
108
+ lastRow = next;
109
+ }
110
+ };
76
111
  const sharedStrings = [];
77
112
  {
78
113
  let value = '', inText = false, inString = false, phonetic = 0;
@@ -110,7 +145,7 @@ export async function streamSheetRows(file, sheetName, onRow, ref = {}) {
110
145
  previousRow = rowNumber; previousCol = 0; values = [];
111
146
  } else if (name === 'c') {
112
147
  const letters = node.attributes.r?.match(/^([A-Z]+)\d+$/)?.[1];
113
- const column = letters ? [...letters].reduce((n, c) => n * 26 + c.charCodeAt(0) - 64, 0) : previousCol + 1;
148
+ const column = letters ? columnNumber(letters) : previousCol + 1;
114
149
  previousCol = column;
115
150
  cell = { column, type: node.attributes.t ?? 'n', style: Number(node.attributes.s ?? 0), raw: '', inline: '' };
116
151
  } else if ((name === 'v' || name === 't') && cell) capture = name;
@@ -138,8 +173,44 @@ export async function streamSheetRows(file, sheetName, onRow, ref = {}) {
138
173
  values = null;
139
174
  }
140
175
  },
141
- async flush() { while (queue.length) { const [row, cells] = queue.shift(); await onRow(row, cells); } },
176
+ async flush() {
177
+ for (const [row, cells] of queue) {
178
+ if (merges.length) { await flushGaps(row); await emit(row, cells); lastRow = row; }
179
+ else await onRow(row, cells);
180
+ }
181
+ queue.length = 0;
182
+ },
142
183
  });
184
+ if (merges.length) await flushGaps(1_000_002);
143
185
  return { date1904 };
144
186
  } finally { archive.zip.close(); }
145
187
  }
188
+
189
+ /** Read the validated header and stream scalar business rows for generation and review. */
190
+ export async function streamValidatedRows(file, validation, limit, onHeader, onRow, options) {
191
+ const headerRow = validation.headerRow ?? 1;
192
+ const ref = { value: false };
193
+ let headers;
194
+ const result = await streamSheetRows(file, validation.sheet, (row, cells) => {
195
+ if (row === headerRow) {
196
+ const count = Math.min(Math.max(validation.columnCount ?? 0, cells.length), limit ?? Infinity);
197
+ headers = Array.from({ length: count }, (_, index) => String(cells[index] ?? '').trim());
198
+ return onHeader(headers, ref.value);
199
+ }
200
+ if (row < headerRow) return;
201
+ if (!headers) throw new Error('已验证的工作表无法读取。');
202
+ const values = headers.map((_, index) => {
203
+ const value = cells[index] ?? null;
204
+ return value instanceof Date ? value.toISOString() : value;
205
+ });
206
+ if (values.some(value => String(value ?? '').trim() !== '')) return onRow({ row, sheet: validation.sheet, values });
207
+ }, ref, options);
208
+ if (!headers) throw new Error('已验证的工作表无法读取。');
209
+ return result;
210
+ }
211
+
212
+ export async function hashWorkbook(file) {
213
+ const digest = createHash('sha256');
214
+ for await (const chunk of createReadStream(file)) digest.update(chunk);
215
+ return digest.digest('hex');
216
+ }
@@ -1,22 +1,25 @@
1
1
  import { defineModule } from '../../recognition/module-definition.mjs';
2
2
 
3
- // 分销商动销(高端产品)。只作动销详情里的参考展示,不并入动销合计:
4
- // 2026-11-27 核对发现它与终端扫码多为同一批交易,且两表没有共同单号,无法逐笔去重。
5
3
  export default defineModule({
6
4
  "id": "distributor",
7
- "title": "分销商动销",
8
- "description": "高端产品分销商出库,动销参考",
5
+ "title": "分销商动销明细",
6
+ "description": "分销商动销金额和件数",
9
7
  "sheetNames": [
10
8
  "分销商动销明细"
11
9
  ],
12
10
  "notes": [
13
- "只在终端动销详情中单独展示,不计入动销合计、动销达成或跨表比例(用户 2026-11-27 选择方案 A)。",
14
- "按“动销日期 (日)”归属日期;“总动销金额”单位元,退货与补录扣减按原负值计入。"
11
+ "全部行并入动销金额、件数及相关指标。",
12
+ "按“动销日期 (日)”归属日期;“总动销金额”单位元,各类单据按原值计入。"
15
13
  ],
16
14
  "fields": [
17
15
  { "key": "date", "header": "动销日期 (日)" },
18
16
  { "key": "distributorName", "header": "分销商名称" },
19
17
  { "key": "distributorCode", "header": "分销商编码" },
18
+ { "key": "marketingCompany", "header": "营销公司名称" },
19
+ { "key": "businessUnit", "header": "事业部" },
20
+ { "key": "theater", "header": "战区" },
21
+ { "key": "brand", "header": "品牌" },
22
+ { "key": "category", "header": "品类" },
20
23
  { "key": "region", "header": "大区" },
21
24
  { "key": "office", "header": "办事处" },
22
25
  { "key": "directorUnit", "header": "客户主任单元" },