dsh-data-dashboard 0.0.0-stage → 0.1.4

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 (70) 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 +192 -0
  17. package/backend/public/admin.js +713 -0
  18. package/backend/public/board.css +43 -0
  19. package/backend/public/board.html +47 -0
  20. package/backend/public/board.js +96 -0
  21. package/backend/public/index.html +110 -0
  22. package/backend/public/review.css +5 -0
  23. package/backend/public/review.js +452 -0
  24. package/backend/real-data/generate-dashboard.mjs +135 -0
  25. package/backend/real-data/inventory-history.mjs +316 -0
  26. package/backend/real-data/organization-mapping.mjs +102 -0
  27. package/backend/real-data/source-payload.mjs +459 -0
  28. package/backend/real-data/terminal-components.mjs +280 -0
  29. package/backend/real-data/terminal-structure.css +105 -0
  30. package/backend/real-data/terminal-structure.mjs +276 -0
  31. package/backend/real-data/v10-components.mjs +112 -0
  32. package/backend/real-data/v10-details.css +18 -0
  33. package/backend/real-data/v10-details.mjs +251 -0
  34. package/backend/real-data/v10-layout.css +27 -0
  35. package/backend/real-data/v10-model.mjs +521 -0
  36. package/backend/real-data/v10-overview-data.mjs +248 -0
  37. package/backend/real-data/v10-overview.css +264 -0
  38. package/backend/real-data/v10-overview.mjs +263 -0
  39. package/backend/real-data/v10-presentation.mjs +342 -0
  40. package/backend/real-data/v10-shell.html +1097 -0
  41. package/backend/real-data/v10-template.mjs +351 -0
  42. package/backend/recognition/fingerprint.mjs +32 -0
  43. package/backend/recognition/headers.mjs +2 -0
  44. package/backend/recognition/module-definition.mjs +4 -0
  45. package/backend/recognition/result.mjs +29 -0
  46. package/backend/recognition/upload-limits.mjs +14 -0
  47. package/backend/review-engine.mjs +364 -0
  48. package/backend/review-service.mjs +182 -0
  49. package/backend/server.mjs +545 -0
  50. package/backend/store.mjs +68 -0
  51. package/backend/target-template.mjs +47 -0
  52. package/backend/validate-workbook.mjs +251 -0
  53. package/backend/web-sync/README.md +37 -0
  54. package/backend/web-sync/client.mjs +63 -0
  55. package/backend/web-sync/exporter.mjs +260 -0
  56. package/backend/web-sync/local.html +34 -0
  57. package/backend/web-sync/server.mjs +147 -0
  58. package/build-manifest.json +79 -0
  59. package/client.js +24 -0
  60. package/cordis.patch.yml +3 -0
  61. package/index.js +117 -0
  62. package/lib/dist-manifest.mjs +19 -0
  63. package/lib/market-index.mjs +56 -0
  64. package/lib/package-audit.mjs +34 -0
  65. package/lib/settings.mjs +71 -0
  66. package/lib/tool-definitions.mjs +56 -0
  67. package/lib/tools.mjs +255 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +71 -4
package/README.md CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ # 战区看板 · DSH Data Dashboard(dsh-data-dashboard)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DeepSeek Harness 插件:在左侧栏加入「战区看板」,打开本机战区经营看板合并页(看板 / 更新数据 / 历史版本),并提供三个只读看板查询工具(资料状态;发票、动销、开瓶汇总及目标达成;组织名称)。
4
+
5
+ - 后台只监听 127.0.0.1,默认端口 4181。
6
+ - 数据放在用户数据目录,不在插件安装目录内:macOS `~/Library/Application Support/TheaterCommandBoard-DSH/data`,Windows `%APPDATA%\TheaterCommandBoard-DSH\data`。卸载或更新插件不会删除这些数据。
7
+ - 业务数据只在本机处理;插件包内不含任何业务数据。
8
+
9
+ ## 安装
10
+
11
+ 需要 DeepSeek Harness 0.2.2-rc.5 以上(0.3 以下)。
12
+
13
+ 1. 在 DSH 打开「插件」→「添加插件」。
14
+ 2. 包名填 `dsh-data-dashboard`。
15
+ 3. 「安装源」选「中国大陆镜像源」(新版本发布后,镜像同步可能延迟约 10 分钟;装不到最新版时稍后再试,或改选 npm 官方源)。
16
+ 4. 安装完成后点「立即启用」,左侧栏出现「战区看板」。
17
+
18
+ 命令行安装:`dsh plugin --profile web add dsh-data-dashboard`;卸载:`dsh plugin --profile web remove dsh-data-dashboard`。
19
+
20
+ ## 更新
21
+
22
+ DSH 会检查 npm 上的新版本,插件卡片出现“有新版本”时按提示更新;也可以卸载后重新安装同一个包名。数据目录保持不变。
23
+
24
+ ## 配置(可选)
25
+
26
+ 在 profile 的 `cordis.patch.yml` 中覆盖:
27
+
28
+ ```yaml
29
+ - id: theater-board
30
+ name: dsh-data-dashboard
31
+ config:
32
+ port: 4181 # 不能用 4180
33
+ dataDir: '' # 留空用默认目录;可填绝对路径沿用已有数据(同一目录同时只能有一个后台在用)
34
+ ```
35
+
36
+ 查询工具只读:不上传、不修改数据、不生成看板;回答依据最近一次生成的看板。
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#aa343e"/><g fill="none" stroke="#fff" stroke-width="4" stroke-linejoin="round"><rect x="12" y="12" width="17" height="22" rx="3"/><rect x="35" y="12" width="17" height="12" rx="3"/><rect x="35" y="30" width="17" height="22" rx="3"/><rect x="12" y="40" width="17" height="12" rx="3"/></g></svg>
@@ -0,0 +1,492 @@
1
+ // Incremental, range and full updates. Invoice, movement, opening and
2
+ // inventory are dated sources (three modes); terminal and banquet are only
3
+ // replaced as a whole but go through the same check card. The composed
4
+ // workbook is written as an ordinary source so validation, inspection,
5
+ // review decisions and generation keep their existing contracts.
6
+ import ExcelJS from 'exceljs';
7
+ import { normalizeHeader } from '../modules.mjs';
8
+ import { sourceDate } from '../review-engine.mjs';
9
+ import { streamSheetRows } from './xlsx-rows.mjs';
10
+
11
+ export const AGGREGATE_VERSION = 2;
12
+ // A field may name several headers; the first one present in the file is used.
13
+ export const FLOW = {
14
+ invoice: { date: '业务日期', org: ['销售大区', '办事处'], amount: '发票金额', quantity: '计价数量', key: ['单据类型', '单据编码', '单据行号'], overlapAllowed: true },
15
+ movement: { date: '扫码日期', org: ['大区名称', '办事处名称'], amount: '扫码金额', quantity: '扫码件数', bottles: '扫码数量(瓶)' },
16
+ opening: { date: '抽奖日期', org: ['产品所属-大区', '产品所属-办事处'], city: '开瓶城市', amount: '开瓶金额', bottles: '开瓶瓶数' },
17
+ // Inventory: compared and replaced by the day of 提交时间, which itself keeps its seconds.
18
+ inventory: { date: '提交时间', time: true, org: [['大区', '大区名称'], ['办事处', '办事处名称']], dealer: '经销商编码', key: ['经销商编码', ['产品名称', '产品编码'], '提交时间'], overlapAllowed: true },
19
+ };
20
+ export const WHOLE = {
21
+ terminal: { date: '签约日期', agreement: '协议编号', outlet: '网点编号' },
22
+ banquet: { events: '执行场次', bottles: '开瓶数量' },
23
+ };
24
+ // Export scope check (contract §11.4). Empty list: the board has no such field.
25
+ export const SCOPE = {
26
+ invoice: { zone: ['战区名称'], region: ['销售大区'], product: ['品种'], productLabel: '品种' },
27
+ movement: { zone: ['战区名称'], region: ['大区名称'], product: ['品种名称'], productLabel: '品种' },
28
+ opening: { zone: ['产品所属-战区'], region: ['产品所属-大区'], product: ['品种'], productLabel: '品种' },
29
+ inventory: { zone: ['战区名称'], region: ['大区', '大区名称'], product: ['产品名称', '产品编码'], productLabel: '产品' },
30
+ terminal: { zone: ['战区名称'], region: ['大区'], product: ['签约品种'], productLabel: '签约品种' },
31
+ banquet: { zone: [], region: ['大区'], product: [], productLabel: '产品' },
32
+ };
33
+ export const PRODUCT_RULE = { windowMin: 3, fileMax: 1, minRows: 20, fallbackDays: 30 };
34
+ export const MODES = ['incremental', 'range', 'full'];
35
+ export const MODE_LABELS = { incremental: '增量', range: '范围更新', full: '整份替换' };
36
+ export const isFlowModule = id => Object.hasOwn(FLOW, id);
37
+ export const isWholeModule = id => Object.hasOwn(WHOLE, id);
38
+ export const isUpdatable = id => isFlowModule(id) || isWholeModule(id);
39
+ export const modesFor = id => isFlowModule(id) ? MODES : isWholeModule(id) ? ['full'] : [];
40
+
41
+ const text = value => value === null || value === undefined ? '' : String(value).trim();
42
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
43
+ export const validDay = value => typeof value === 'string' && DAY.test(value) && sourceDate(value) === value;
44
+ const shiftDay = (day, offset) => { const d = new Date(`${day}T00:00:00Z`); d.setUTCDate(d.getUTCDate() + offset); return d.toISOString().slice(0, 10); };
45
+
46
+ function plain(value) {
47
+ if (value === null || value === undefined) return null;
48
+ if (value instanceof Date || typeof value !== 'object') return value;
49
+ if ('formula' in value || 'sharedFormula' in value) return plain(value.result ?? null);
50
+ if (value.richText) return value.richText.map(part => part.text).join('');
51
+ if ('text' in value) return plain(value.text);
52
+ return null;
53
+ }
54
+
55
+ function number(value) {
56
+ if (value === null || value === undefined || typeof value === 'boolean') return null;
57
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
58
+ const raw = text(value);
59
+ if (!raw || (raw.includes(',') && !/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/.test(raw))) return null;
60
+ const parsed = Number(raw.replaceAll(',', ''));
61
+ return Number.isFinite(parsed) ? parsed : null;
62
+ }
63
+
64
+ // Excel serial → Date keeping the wall-clock time to the second (same rule as the inventory reader).
65
+ function serialDateTime(value, date1904) {
66
+ const epoch = Date.UTC(date1904 ? 1904 : 1899, date1904 ? 0 : 11, date1904 ? 1 : 30);
67
+ const correction = !date1904 && value < 60 ? 86400000 : 0;
68
+ return new Date(epoch + correction + Math.round(value * 86400) * 1000);
69
+ }
70
+
71
+ /** Header lookup; a field may list several header names. */
72
+ function accessor(headers) {
73
+ const positions = new Map();
74
+ headers.forEach((header, index) => { const key = normalizeHeader(header); if (key && !positions.has(key)) positions.set(key, index); });
75
+ const cache = new Map();
76
+ const index = names => {
77
+ if (names === undefined || names === null) return -1;
78
+ const id = Array.isArray(names) ? names.join('\u0000') : names;
79
+ if (cache.has(id)) return cache.get(id);
80
+ let found = -1;
81
+ for (const name of [].concat(names)) { const at = positions.get(normalizeHeader(name)); if (at !== undefined) { found = at; break; } }
82
+ cache.set(id, found);
83
+ return found;
84
+ };
85
+ const get = (values, names) => { const at = index(names); return at < 0 ? null : values[at]; };
86
+ get.has = names => [].concat(names ?? []).length > 0 && index(names) >= 0;
87
+ return get;
88
+ }
89
+ const keyText = value => value instanceof Date ? value.toISOString() : text(value);
90
+
91
+ /**
92
+ * Stream the validated main sheet row by row with plain values and the flow date.
93
+ * Streaming keeps a year of daily data within the worker's memory limit.
94
+ */
95
+ export async function streamSource(file, validation, moduleId, onHeader, onRow) {
96
+ const spec = FLOW[moduleId];
97
+ const headerRow = validation.headerRow ?? 1;
98
+ let headers = null, dateColumn = -1;
99
+ // date1904 is filled in once workbook.xml has been read, before any row.
100
+ const date1904Ref = { value: false };
101
+ const result = await streamSheetRows(file, validation.sheet, async (rowNumber, cells) => {
102
+ if (rowNumber < headerRow) return;
103
+ if (rowNumber === headerRow) {
104
+ headers = cells.map(value => text(plain(value)));
105
+ while (headers.length && !headers.at(-1)) headers.pop();
106
+ dateColumn = headers.findIndex(header => normalizeHeader(header) === normalizeHeader(spec.date));
107
+ if (dateColumn < 0) throw new Error(`缺少日期字段:${spec.date}。`);
108
+ await onHeader({ sheetName: validation.sheet, headers, dateColumn, format: validation.sourceFormat ?? null });
109
+ return;
110
+ }
111
+ if (!headers) throw new Error('未找到表头行。');
112
+ const values = headers.map((_, index) => plain(cells[index] ?? null));
113
+ if (!values.some(value => text(value) !== '')) return;
114
+ const raw = values[dateColumn];
115
+ const day = sourceDate(raw, date1904Ref.value);
116
+ // Numeric serial dates are rewritten as dates so the 1900/1904 base of the
117
+ // composed workbook cannot shift them. Inventory keeps the time of day.
118
+ if (day && typeof raw === 'number') values[dateColumn] = spec.time ? serialDateTime(raw, date1904Ref.value) : new Date(`${day}T00:00:00Z`);
119
+ await onRow({ row: rowNumber, values, date: day });
120
+ }, date1904Ref);
121
+ if (!headers) throw new Error('已验证的工作表无法读取。');
122
+ return result;
123
+ }
124
+
125
+ /** Read a (small) source fully into memory. */
126
+ export async function readSource(file, validation, moduleId) {
127
+ const source = { rows: [] };
128
+ await streamSource(file, validation, moduleId, header => Object.assign(source, header), row => { source.rows.push(row); });
129
+ return source;
130
+ }
131
+
132
+ const round = value => Math.round(value * 100) / 100;
133
+ const addTo = (set, value) => { const name = text(value); if (name) set.add(name); };
134
+ const sorted = set => [...set].sort();
135
+ function scopeHas(get, moduleId) {
136
+ const spec = SCOPE[moduleId];
137
+ return { zone: get.has(spec.zone), region: get.has(spec.region), product: get.has(spec.product) };
138
+ }
139
+
140
+ /** Per-day totals, organizations and scope values, small enough to keep beside a source. */
141
+ export function aggregator(moduleId) {
142
+ const spec = FLOW[moduleId], scope = SCOPE[moduleId], byDate = {}, invalidRows = [], zones = new Set(), days = new Map();
143
+ let get = null, headers = [], rows = 0, format = null;
144
+ return {
145
+ header(info) { headers = info.headers; format = info.format ?? null; get = accessor(info.headers); },
146
+ row({ row, values, date }) {
147
+ rows++;
148
+ addTo(zones, get(values, scope.zone));
149
+ if (!date) { invalidRows.push(row); return; }
150
+ let day = days.get(date);
151
+ 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); }
152
+ day.rows++;
153
+ if (spec.amount) day.amount += number(get(values, spec.amount)) ?? 0;
154
+ if (spec.quantity) day.quantity += number(get(values, spec.quantity)) ?? 0;
155
+ if (spec.bottles) day.bottles += number(get(values, spec.bottles)) ?? 0;
156
+ const region = text(get(values, spec.org[0]));
157
+ addTo(day.regions, region);
158
+ addTo(day.offices, [region, text(get(values, spec.org[1]))].filter(Boolean).join(' / '));
159
+ if (spec.city) addTo(day.cities, get(values, spec.city));
160
+ if (spec.dealer) addTo(day.dealers, get(values, spec.dealer));
161
+ addTo(day.products, get(values, scope.product));
162
+ },
163
+ result() {
164
+ const regions = new Set(), products = new Set();
165
+ for (const [date, day] of days) {
166
+ for (const value of day.regions) regions.add(value);
167
+ for (const value of day.products) products.add(value);
168
+ byDate[date] = { rows: day.rows, amount: round(day.amount), quantity: round(day.quantity), bottles: round(day.bottles),
169
+ regions: sorted(day.regions), offices: sorted(day.offices), cities: sorted(day.cities), dealers: sorted(day.dealers), products: sorted(day.products) };
170
+ }
171
+ const dates = Object.keys(byDate).sort();
172
+ return { version: AGGREGATE_VERSION, moduleId, format, rows, start: dates[0] ?? null, end: dates.at(-1) ?? null,
173
+ invalidDateRows: invalidRows.length, invalidDateSample: invalidRows.slice(0, 20), byDate, headers,
174
+ has: get ? scopeHas(get, moduleId) : { zone: false, region: false, product: false }, zones: sorted(zones), regions: sorted(regions), products: sorted(products) };
175
+ },
176
+ };
177
+ }
178
+ export function aggregate(source, moduleId) {
179
+ const acc = aggregator(moduleId);
180
+ acc.header(source); for (const row of source.rows) acc.row(row);
181
+ return acc.result();
182
+ }
183
+ export async function aggregateFile(file, validation, moduleId) {
184
+ const acc = aggregator(moduleId);
185
+ await streamSource(file, validation, moduleId, info => acc.header(info), row => acc.row(row));
186
+ return acc.result();
187
+ }
188
+
189
+ /** Summary of a board that is only replaced as a whole (terminal, banquet). */
190
+ export async function summarizeFile(file, validation, moduleId) {
191
+ const spec = WHOLE[moduleId], scope = SCOPE[moduleId], headerRow = validation.headerRow ?? 1;
192
+ const zones = new Set(), regions = new Set(), products = new Set(), agreements = new Set(), outlets = new Set();
193
+ const date1904Ref = { value: false };
194
+ let get = null, headers = [], rows = 0, events = 0, bottles = 0, start = null, end = null;
195
+ await streamSheetRows(file, validation.sheet, (rowNumber, cells) => {
196
+ if (rowNumber < headerRow) return;
197
+ if (rowNumber === headerRow) { headers = cells.map(value => text(plain(value))); while (headers.length && !headers.at(-1)) headers.pop(); get = accessor(headers); return; }
198
+ if (!get) throw new Error('未找到表头行。');
199
+ const values = headers.map((_, index) => plain(cells[index] ?? null));
200
+ if (!values.some(value => text(value) !== '')) return;
201
+ rows++;
202
+ addTo(zones, get(values, scope.zone)); addTo(regions, get(values, scope.region)); addTo(products, get(values, scope.product));
203
+ if (spec.agreement) addTo(agreements, get(values, spec.agreement));
204
+ if (spec.outlet) addTo(outlets, get(values, spec.outlet));
205
+ if (spec.events) events += number(get(values, spec.events)) ?? 0;
206
+ if (spec.bottles) bottles += number(get(values, spec.bottles)) ?? 0;
207
+ if (spec.date) {
208
+ const day = sourceDate(get(values, spec.date), date1904Ref.value);
209
+ if (day) { if (!start || day < start) start = day; if (!end || day > end) end = day; }
210
+ }
211
+ }, date1904Ref);
212
+ if (!get) throw new Error('已验证的工作表无法读取。');
213
+ return { version: AGGREGATE_VERSION, moduleId, whole: true, format: validation.sourceFormat ?? null, rows, start, end, headers,
214
+ agreements: agreements.size, outlets: outlets.size, agreementIds: spec.agreement ? sorted(agreements) : [], events: round(events), bottles: round(bottles),
215
+ has: scopeHas(get, moduleId), zones: sorted(zones), regions: sorted(regions), products: sorted(products) };
216
+ }
217
+
218
+ /** Rows of the new file whose identity key already exists on the same day in the current source (classification only). */
219
+ export function keyMatcher(moduleId, part) {
220
+ const spec = FLOW[moduleId];
221
+ if (!spec?.key) return null;
222
+ const partGet = accessor(part.headers);
223
+ const keyOf = (get, values) => JSON.stringify(spec.key.map(name => keyText(get(values, name))));
224
+ const wanted = new Map();
225
+ for (const row of part.rows) if (row.date) { const set = wanted.get(row.date) ?? new Set(); set.add(keyOf(partGet, row.values)); wanted.set(row.date, set); }
226
+ const found = new Map();
227
+ let baseGet = null;
228
+ return {
229
+ header(info) { baseGet = accessor(info.headers); },
230
+ row(row) { if (row.date && wanted.has(row.date)) { const key = keyOf(baseGet, row.values); if (wanted.get(row.date).has(key)) { const set = found.get(row.date) ?? new Set(); set.add(key); found.set(row.date, set); } } },
231
+ result() {
232
+ const result = {};
233
+ for (const row of part.rows) if (row.date && found.get(row.date)?.has(keyOf(partGet, row.values))) result[row.date] = (result[row.date] ?? 0) + 1;
234
+ return result;
235
+ },
236
+ };
237
+ }
238
+ export const invoiceMatcher = part => keyMatcher('invoice', part);
239
+ export function existingRows(moduleId, base, part) {
240
+ const matcher = keyMatcher(moduleId, part);
241
+ if (!matcher) return {};
242
+ matcher.header(base); for (const row of base.rows) matcher.row(row);
243
+ return matcher.result();
244
+ }
245
+ export const existingInvoiceRows = (base, part) => existingRows('invoice', base, part);
246
+
247
+ export function suggestMode(base, part) {
248
+ if (part?.whole) return { mode: 'full', start: part.start, end: part.end, reason: '这个板块只支持整份替换。' };
249
+ if (!base || !base.start) return { mode: 'full', start: part.start, end: part.end, reason: '当前没有有效数据,用这份文件建立基线。' };
250
+ if ((base.format ?? null) !== (part.format ?? null)) return { mode: 'full', start: part.start, end: part.end, reason: '文件格式与当前数据不同,只能整份替换。' };
251
+ const overlap = Object.keys(part.byDate).filter(day => base.byDate[day]);
252
+ if (!overlap.length) return { mode: 'incremental', start: part.start, end: part.end, reason: '文件里全部是新日期,直接追加。' };
253
+ if (part.start <= base.start && part.end >= base.end) return { mode: 'full', start: part.start, end: part.end, reason: '文件覆盖了当前全部日期,整份替换。' };
254
+ return { mode: 'range', start: part.start, end: part.end, reason: `与现有数据有 ${overlap.length} 天重叠,按文件日期范围整段替换。` };
255
+ }
256
+
257
+ /** Totals over several (byDate, days) parts; dealers are counted once across parts. */
258
+ function totals(parts) {
259
+ const result = { rows: 0, amount: 0, quantity: 0, bottles: 0, days: 0, dealers: 0 };
260
+ const dealers = new Set(), seenDays = new Set();
261
+ for (const [byDate, days] of parts) for (const day of days) {
262
+ const value = byDate[day]; if (!value) continue;
263
+ result.rows += value.rows; result.amount += value.amount; result.quantity += value.quantity; result.bottles += value.bottles;
264
+ seenDays.add(day);
265
+ for (const dealer of value.dealers ?? []) dealers.add(dealer);
266
+ }
267
+ for (const key of ['amount', 'quantity', 'bottles']) result[key] = round(result[key]);
268
+ result.days = seenDays.size; result.dealers = dealers.size;
269
+ return result;
270
+ }
271
+ function union(byDate, days, field) { const set = new Set(); for (const day of days) for (const value of byDate[day]?.[field] ?? []) set.add(value); return set; }
272
+ const listDays = (byDate, inRange) => Object.keys(byDate).filter(inRange).sort();
273
+ const months = days => [...new Set(days.map(day => day.slice(0, 7)))].sort();
274
+
275
+ const FIGURES = {
276
+ invoice: [['行数', 'rows', 'count'], ['发票净额(万元)', 'amount', 'wan']],
277
+ movement: [['行数', 'rows', 'count'], ['扫码金额(万元)', 'amount', 'wan'], ['扫码件数', 'quantity', 'count'], ['扫码瓶数', 'bottles', 'count']],
278
+ opening: [['行数', 'rows', 'count'], ['开瓶瓶数', 'bottles', 'count'], ['红包金额(万元)', 'amount', 'wan']],
279
+ inventory: [['盘点记录', 'rows', 'count'], ['经销商', 'dealers', 'count']],
280
+ terminal: [['协议数', 'agreements', 'count'], ['签约终端', 'outlets', 'count']],
281
+ banquet: [['执行场次', 'events', 'count'], ['开瓶瓶数', 'bottles', 'count']],
282
+ };
283
+ 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 }));
284
+ const listText = (values, limit = 3) => `${values.slice(0, limit).join('、')}${values.length > limit ? ` 等 ${values.length} 个` : ''}`;
285
+ const DIMENSIONS = [['zone', 'zones', '战区'], ['region', 'regions', '大区']];
286
+
287
+ /** Products of the current source over the comparison window (§11.4). */
288
+ function productWindow(base, part) {
289
+ if (!base.byDate) return base.products ?? [];
290
+ let days = Object.keys(part.byDate ?? {}).filter(day => base.byDate[day]);
291
+ if (!days.length && base.end) { const from = shiftDay(base.end, 1 - PRODUCT_RULE.fallbackDays); days = Object.keys(base.byDate).filter(day => day >= from && day <= base.end); }
292
+ return [...union(base.byDate, days, 'products')].sort();
293
+ }
294
+
295
+ /** Export scope check: blocks a file whose organizations or products do not match the current source. */
296
+ export function scopeCheck(moduleId, base, part) {
297
+ const spec = SCOPE[moduleId];
298
+ const result = { ok: true, checked: { zone: false, region: false, product: false }, blocked: [], notes: [], advice: '', productLabel: spec.productLabel,
299
+ counts: { zones: part.zones?.length ?? 0, regions: part.regions?.length ?? 0, products: part.products?.length ?? 0 } };
300
+ if (!base) { result.notes.push('当前没有有效数据,本次不检查导出范围。'); return result; }
301
+ const unchecked = [];
302
+ for (const [dim, list, label] of DIMENSIONS) {
303
+ if (!spec[dim].length) { unchecked.push(`${label}(表中没有该字段)`); continue; }
304
+ if (!part.has?.[dim] || !base.has?.[dim] || !base[list]?.length) { unchecked.push(`${label}(${!part.has?.[dim] ? '新文件' : '当前数据'}没有该字段)`); continue; }
305
+ result.checked[dim] = true;
306
+ const known = new Set(base[list]), extra = (part[list] ?? []).filter(value => !known.has(value));
307
+ if (extra.length) result.blocked.push(`文件包含当前数据没有的${label}:${listText(extra)}`);
308
+ }
309
+ const productLabel = spec.productLabel;
310
+ if (!spec.product.length) unchecked.push(`${productLabel}(表中没有该字段)`);
311
+ else if (!part.has?.product || !base.has?.product) unchecked.push(`${productLabel}(${!part.has?.product ? '新文件' : '当前数据'}没有该字段)`);
312
+ else {
313
+ result.checked.product = true;
314
+ const window = productWindow(base, part), mine = part.products ?? [];
315
+ result.counts.windowProducts = window.length;
316
+ if (window.length >= PRODUCT_RULE.windowMin && mine.length <= PRODUCT_RULE.fileMax && part.rows >= PRODUCT_RULE.minRows)
317
+ result.blocked.push(`${productLabel}只有「${mine[0] ?? '—'}」${mine.length} 个,当前数据同期有 ${window.length} 个${productLabel},可能只导出了部分产品`);
318
+ }
319
+ if (unchecked.length) result.notes.push(`未检查:${unchecked.join('、')}。`);
320
+ if (result.blocked.length) {
321
+ const zones = base.zones ?? [];
322
+ const scopeName = zones.length && zones.length <= 3 ? zones.join('、') : '当前组织范围';
323
+ result.advice = `请在系统里按「${scopeName}${spec.product.length ? '、全部产品' : ''}」重新导出${base.byDate ? '最近 7 天' : ''},再拖进来。`;
324
+ result.ok = false;
325
+ }
326
+ return result;
327
+ }
328
+
329
+ /** What an update will change. Used for the check card and enforced again on apply. */
330
+ export function receipt({ moduleId, base, part, mode, start, end, existingByDate = {} }) {
331
+ if (isWholeModule(moduleId)) return wholeReceipt({ moduleId, base, part, mode });
332
+ if (!MODES.includes(mode)) throw new Error('更新方式无效。');
333
+ const spec = FLOW[moduleId], blocked = [], warnings = [];
334
+ const baseBy = base?.byDate ?? {}, partBy = part.byDate;
335
+ const partDays = Object.keys(partBy).sort(), baseAll = Object.keys(baseBy);
336
+ if (!part.rows) blocked.push('文件没有数据行。');
337
+ if (part.invalidDateRows) blocked.push(`${part.invalidDateRows} 行${spec.date}无效(Excel 行号:${part.invalidDateSample.join('、')}${part.invalidDateRows > part.invalidDateSample.length ? '等' : ''}),请修正后重新导出。`);
338
+ if (mode !== 'full' && base && (base.format ?? null) !== (part.format ?? null)) blocked.push('文件格式与当前数据不同,只能整份替换。');
339
+ let window, after, before, disappearing = [], missing = { regions: [], offices: [], cities: [] };
340
+ if (mode === 'range') {
341
+ if (!validDay(start) || !validDay(end) || start > end) { blocked.push('请填写有效的起止日期(开始不晚于结束)。'); start = part.start; end = part.end; }
342
+ const outside = partDays.filter(day => day < start || day > end);
343
+ if (outside.length) blocked.push(`文件有 ${outside.reduce((n, day) => n + partBy[day].rows, 0)} 行日期不在替换区间内(${outside[0]}${outside.length > 1 ? ` 等 ${outside.length} 天` : ''}),请调整区间或重新导出。`);
344
+ window = day => day >= start && day <= end;
345
+ const baseDays = listDays(baseBy, window);
346
+ before = totals([[baseBy, baseDays]]); after = totals([[partBy, partDays.filter(window)]]);
347
+ disappearing = baseDays.filter(day => !partBy[day]);
348
+ } else if (mode === 'incremental') {
349
+ const overlap = partDays.filter(day => baseBy[day]);
350
+ if (overlap.length && !spec.overlapAllowed) blocked.push(`文件包含已有记录的日期(${overlap.slice(0, 5).join('、')}${overlap.length > 5 ? ` 等 ${overlap.length} 天` : ''}),增量只能追加新日期,请改用范围更新。`);
351
+ const existing = Object.values(existingByDate).reduce((n, value) => n + value, 0);
352
+ if (moduleId === 'invoice' && existing) warnings.push(`有 ${existing} 行的单据类型、编码和行号在同一天已经存在,追加后会进入重复候选检查;建议改用范围更新。`);
353
+ if (moduleId === 'inventory' && existing) warnings.push(`有 ${existing} 行的经销商编码、产品和提交时间与现有记录相同,追加后作为并列记录保留(不自动去重);建议改用范围更新。`);
354
+ // Incremental compares the whole current source with the source after appending.
355
+ before = totals([[baseBy, baseAll]]); after = totals([[baseBy, baseAll], [partBy, partDays]]);
356
+ window = day => partBy[day];
357
+ } else {
358
+ window = () => true;
359
+ before = totals([[baseBy, baseAll]]); after = totals([[partBy, partDays]]);
360
+ if (base?.start && part.start && part.start > base.start) warnings.push(`历史起点从 ${base.start} 变为 ${part.start},之前的数据会被移除。`);
361
+ if (base?.end && part.end && part.end < base.end) warnings.push(`最新日期从 ${base.end} 倒退到 ${part.end}。`);
362
+ const lost = months(baseAll).filter(month => !partDays.some(day => day.startsWith(month)));
363
+ if (lost.length) warnings.push(`${lost.slice(0, 6).join('、')}${lost.length > 6 ? ` 等 ${lost.length} 个月` : ''}在新文件里整月没有数据。`);
364
+ }
365
+ if (mode !== 'incremental' && base) {
366
+ const baseDays = listDays(baseBy, window), newDays = partDays.filter(window);
367
+ for (const field of ['regions', 'offices', 'cities']) {
368
+ const now = union(partBy, newDays, field);
369
+ missing[field] = [...union(baseBy, baseDays, field)].filter(value => !now.has(value)).sort();
370
+ }
371
+ if (moduleId !== 'opening') missing.cities = [];
372
+ }
373
+ const scope = scopeCheck(moduleId, base, part);
374
+ blocked.push(...scope.blocked);
375
+ const requiresConfirmation = missing.regions.length + missing.offices.length + missing.cities.length > 0;
376
+ const parts = [];
377
+ if (missing.regions.length) parts.push(`大区:${missing.regions.join('、')}`);
378
+ if (missing.offices.length) parts.push(`办事处:${listText(missing.offices, 6)}`);
379
+ if (missing.cities.length) parts.push(`城市:${listText(missing.cities, 6)}`);
380
+ const existingRows = Object.entries(existingByDate).filter(([day]) => window(day)).reduce((n, [, value]) => n + value, 0);
381
+ const identity = spec.key ? { existing: existingRows, added: Math.max(0, totals([[partBy, partDays.filter(window)]]).rows - existingRows),
382
+ label: moduleId === 'invoice' ? '单据类型+编码+行号' : '经销商编码+产品+提交时间' } : null;
383
+ const outStart = mode === 'range' ? start : part.start, outEnd = mode === 'range' ? end : part.end;
384
+ return {
385
+ moduleId, mode, modeLabel: MODE_LABELS[mode], start: outStart, end: outEnd,
386
+ windowLabel: mode === 'range' ? `替换 ${outStart} ~ ${outEnd}` : mode === 'incremental' ? `追加 ${part.start} ~ ${part.end}` : '整份替换',
387
+ file: { rows: part.rows, start: part.start, end: part.end }, before, after, figures: figures(moduleId, before, after),
388
+ disappearingDates: disappearing, missingOrganizations: missing, requiresConfirmation,
389
+ confirmation: requiresConfirmation ? { message: `组织缺失提醒:区间内的旧数据有、新文件里没有的 ${parts.join(';')}。可能导出时只选了部分组织。`, label: '我已核对,这些组织在区间内确实没有数据' } : null,
390
+ identity, invoiceIdentity: moduleId === 'invoice' ? { existing: identity.existing, added: identity.added } : null,
391
+ scope, blocked, warnings,
392
+ };
393
+ }
394
+
395
+ /** Check card for terminal and banquet: whole replacement only. */
396
+ export function wholeReceipt({ moduleId, base, part, mode = 'full' }) {
397
+ const blocked = [], warnings = [], notes = [];
398
+ if (mode !== 'full') blocked.push('这个板块只支持整份替换。');
399
+ if (!part.rows) blocked.push('文件没有数据行。');
400
+ let requiresConfirmation = false, confirmation = null, disappearingAgreements = [];
401
+ if (moduleId === 'terminal') {
402
+ if (base) {
403
+ const now = new Set(part.agreementIds ?? []);
404
+ disappearingAgreements = (base.agreementIds ?? []).filter(id => !now.has(id));
405
+ if (disappearingAgreements.length) {
406
+ requiresConfirmation = true;
407
+ confirmation = { message: `当前 ${disappearingAgreements.length} 份协议在新文件里找不到(可能被关闭或删除):${listText(disappearingAgreements, 5)}。`, label: '我已核对,确认替换' };
408
+ }
409
+ if (base.end && part.end && part.end < base.end) warnings.push(`签约日期最新只到 ${part.end},早于当前数据的 ${base.end}。`);
410
+ }
411
+ }
412
+ if (moduleId === 'banquet') notes.push('宴席表没有日期列;新文件的统计期间需要在导入检查中重新确认。');
413
+ const scope = scopeCheck(moduleId, base, part);
414
+ blocked.push(...scope.blocked);
415
+ return {
416
+ moduleId, mode: 'full', modeLabel: MODE_LABELS.full, start: part.start, end: part.end, windowLabel: '整份替换',
417
+ file: { rows: part.rows, start: part.start, end: part.end }, before: base ?? null, after: part, figures: figures(moduleId, base, part),
418
+ disappearingDates: [], missingOrganizations: { regions: [], offices: [], cities: [] }, disappearingAgreements: disappearingAgreements.length,
419
+ requiresConfirmation, confirmation, identity: null, invoiceIdentity: null, scope, blocked, warnings, notes,
420
+ };
421
+ }
422
+
423
+ function layout(baseHeaders, partHeaders) {
424
+ const headers = [...baseHeaders];
425
+ const positions = new Map(headers.map((header, index) => [normalizeHeader(header), index]));
426
+ const added = [];
427
+ for (const header of partHeaders) if (header && !positions.has(normalizeHeader(header))) { positions.set(normalizeHeader(header), headers.length); headers.push(header); added.push(header); }
428
+ const missing = baseHeaders.filter(header => header && !partHeaders.some(item => normalizeHeader(item) === normalizeHeader(header)));
429
+ const map = partHeaders.map(header => header ? positions.get(normalizeHeader(header)) : undefined);
430
+ const warnings = [];
431
+ if (added.length) warnings.push(`新文件多了 ${added.join('、')} 列,已一并保留;表头变化后,已保存的处理决定可能需要重新确认。`);
432
+ if (missing.length) warnings.push(`新文件缺少 ${missing.join('、')} 列,这些列在新数据里留空。`);
433
+ return {
434
+ headers, warnings,
435
+ widen: values => { const out = values.slice(0, headers.length); while (out.length < headers.length) out.push(null); return out; },
436
+ project: values => { const out = new Array(headers.length).fill(null); values.forEach((value, index) => { if (map[index] !== undefined) out[map[index]] = value; }); return out; },
437
+ };
438
+ }
439
+ function keeper(mode, start, end) {
440
+ if (mode === 'incremental') return () => true;
441
+ if (mode === 'range') return row => !row.date || row.date < start || row.date > end;
442
+ throw new Error('整份替换不需要合并。');
443
+ }
444
+
445
+ /** In-memory composition (small sources and tests). Headers follow the current source; new columns are appended. */
446
+ export function compose({ moduleId, base, part, mode, start, end }) {
447
+ const plan = layout(base.headers, part.headers), keep = keeper(mode, start, end);
448
+ const rows = [...base.rows.filter(keep).map(row => plan.widen(row.values)), ...part.rows.map(row => plan.project(row.values))];
449
+ return { sheetName: base.sheetName, headers: plan.headers, rows, dateColumn: base.dateColumn, time: !!FLOW[moduleId ?? base.moduleId]?.time, warnings: plan.warnings, kept: rows.length - part.rows.length, appended: part.rows.length };
450
+ }
451
+
452
+ function writer(file, sheetName, headers, dateColumn, time = false) {
453
+ const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ filename: file, useSharedStrings: true, useStyles: true });
454
+ const sheet = workbook.addWorksheet(sheetName);
455
+ sheet.addRow(headers).commit();
456
+ return {
457
+ add(values) { const row = sheet.addRow(values); if (values[dateColumn] instanceof Date) row.getCell(dateColumn + 1).numFmt = time ? 'yyyy-mm-dd hh:mm:ss' : 'yyyy-mm-dd'; row.commit(); },
458
+ async close() { sheet.commit(); await workbook.commit(); },
459
+ };
460
+ }
461
+ export async function writeSource(file, { sheetName, headers, rows, dateColumn, time = false }) {
462
+ const out = writer(file, sheetName, headers, dateColumn, time);
463
+ for (const values of rows) out.add(values);
464
+ await out.close();
465
+ }
466
+
467
+ /** Streaming composition: the current source is read once and never held in memory. */
468
+ export async function composeFile({ baseFile, baseValidation, part, mode, start, end, outFile, moduleId }) {
469
+ const keep = keeper(mode, start, end);
470
+ let plan = null, out = null, kept = 0;
471
+ await streamSource(baseFile, baseValidation, moduleId, info => {
472
+ plan = layout(info.headers, part.headers);
473
+ out = writer(outFile, info.sheetName, plan.headers, info.dateColumn, !!FLOW[moduleId].time);
474
+ }, row => { if (keep(row)) { out.add(plan.widen(row.values)); kept++; } });
475
+ for (const row of part.rows) out.add(plan.project(row.values));
476
+ await out.close();
477
+ return { warnings: plan.warnings, kept, appended: part.rows.length, rows: kept + part.rows.length };
478
+ }
479
+
480
+ /** Earlier source fingerprints this upload was composed from (newest first). */
481
+ export function lineageShas(state, uploadId) {
482
+ const result = [], seen = new Set();
483
+ let current = state?.uploads?.find(upload => upload.id === uploadId);
484
+ while (current?.composition?.baseUploadId && !seen.has(current.id) && result.length < 5000) {
485
+ seen.add(current.id);
486
+ const base = state.uploads.find(upload => upload.id === current.composition.baseUploadId);
487
+ if (!base?.sha256) break;
488
+ result.push(base.sha256.toLowerCase());
489
+ current = base;
490
+ }
491
+ return result;
492
+ }
@@ -0,0 +1,58 @@
1
+ import { readSource, aggregate, aggregator, aggregateFile, keyMatcher, receipt, streamSource, composeFile, summarizeFile, isWholeModule } from './flow.mjs';
2
+ import { streamSheetRows } from './xlsx-rows.mjs';
3
+ import { sourceDate } from '../review-engine.mjs';
4
+ import { normalizeHeader } from '../modules.mjs';
5
+
6
+ const COVERAGE_DATE = { invoice: '业务日期', movement: '扫码日期', opening: '抽奖日期', terminal: '签约日期', inventory: '提交时间' };
7
+
8
+ /** Earliest and latest date of a source, for uploads saved before coverage was recorded. */
9
+ async function coverageOf(file, validation, moduleId) {
10
+ const header = COVERAGE_DATE[moduleId], headerRow = validation.headerRow ?? 1, ref = { value: false };
11
+ if (!header) return { start: null, end: null };
12
+ let column = -1, start = null, end = null;
13
+ await streamSheetRows(file, validation.sheet, (rowNumber, cells) => {
14
+ if (rowNumber < headerRow) return;
15
+ if (rowNumber === headerRow) { column = cells.findIndex(value => normalizeHeader(value instanceof Date ? '' : String(value ?? '').trim()) === normalizeHeader(header)); return; }
16
+ if (column < 0) return;
17
+ const day = sourceDate(cells[column], ref.value);
18
+ if (day) { if (!start || day < start) start = day; if (!end || day > end) end = day; }
19
+ }, ref);
20
+ return { start, end };
21
+ }
22
+
23
+ /** Worker-side update operations. Each reads only files the server has already validated. */
24
+ export async function runFlowJob(job) {
25
+ if (job.kind === 'aggregate') return aggregateFile(job.file, job.validation, job.moduleId);
26
+ if (job.kind === 'coverage') return coverageOf(job.file, job.validation, job.moduleId);
27
+ if (job.kind === 'analyze' && isWholeModule(job.moduleId)) {
28
+ const part = await summarizeFile(job.partFile, job.partValidation, job.moduleId);
29
+ const base = job.baseFile ? await summarizeFile(job.baseFile, job.baseValidation, job.moduleId) : null;
30
+ return { part, base, existingByDate: {} };
31
+ }
32
+ if (job.kind === 'analyze') {
33
+ const part = await readSource(job.partFile, job.partValidation, job.moduleId);
34
+ const partAggregate = aggregate(part, job.moduleId);
35
+ if (!job.baseFile) return { part: partAggregate, base: null, existingByDate: {} };
36
+ const needAggregate = !job.baseAggregate, matcher = keyMatcher(job.moduleId, part);
37
+ if (needAggregate || matcher) {
38
+ const acc = needAggregate ? aggregator(job.moduleId) : null;
39
+ await streamSource(job.baseFile, job.baseValidation, job.moduleId,
40
+ info => { acc?.header(info); matcher?.header(info); }, row => { acc?.row(row); matcher?.row(row); });
41
+ return { part: partAggregate, base: acc ? acc.result() : job.baseAggregate, existingByDate: matcher ? matcher.result() : {} };
42
+ }
43
+ return { part: partAggregate, base: job.baseAggregate, existingByDate: {} };
44
+ }
45
+ if (job.kind === 'compose') {
46
+ const part = await readSource(job.partFile, job.partValidation, job.moduleId);
47
+ const partAggregate = aggregate(part, job.moduleId);
48
+ // Recheck against the files themselves rather than the earlier preview.
49
+ const acc = aggregator(job.moduleId), matcher = keyMatcher(job.moduleId, part);
50
+ await streamSource(job.baseFile, job.baseValidation, job.moduleId, info => { acc.header(info); matcher?.header(info); }, row => { acc.row(row); matcher?.row(row); });
51
+ const checked = receipt({ moduleId: job.moduleId, base: acc.result(), part: partAggregate, mode: job.mode, start: job.start, end: job.end, existingByDate: matcher ? matcher.result() : {} });
52
+ if (checked.blocked.length) throw new Error(checked.blocked.join(' '));
53
+ if (checked.requiresConfirmation && !job.confirmMissing) throw new Error('有组织在新文件里缺失,请先核对并确认后再提交。');
54
+ 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 });
55
+ return { receipt: checked, warnings: [...checked.warnings, ...composed.warnings], kept: composed.kept, appended: composed.appended, rows: composed.rows };
56
+ }
57
+ throw new Error('Unknown flow operation');
58
+ }