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
@@ -0,0 +1,364 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import ExcelJS from 'exceljs';
4
+ import { moduleById, normalizeHeader } from './modules.mjs';
5
+ import { validateWorkbook } from './validate-workbook.mjs';
6
+
7
+ // This module is pure apart from workbook reads. Persisted decisions and source
8
+ // promotion remain the server's responsibility; original workbooks are never edited.
9
+ const VERSION = 1;
10
+ const ORG_FIELDS = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
11
+ const DATE_MODULES = new Set(['invoice', 'movement', 'opening']);
12
+ const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
13
+ const text = value => value === null || value === undefined ? '' : String(value).trim();
14
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
15
+ const validPath = path => Array.isArray(path) && path.length === 6 && path.every(value => typeof value === 'string' && value.length <= 1000);
16
+ const pathKey = path => JSON.stringify(path);
17
+ const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
18
+ const alive = record => !record.revokedAt && record.disabled !== true;
19
+ // A source composed from earlier versions (incremental / range updates) keeps
20
+ // decisions made on those versions; changed groups no longer match by content.
21
+ const boundTo = (record, source) => record.remember === true || record.sourceSha256 === source.sha256 || (Array.isArray(source.lineage) && source.lineage.includes(record.sourceSha256));
22
+
23
+ function scalar(value) {
24
+ if (value === null || value === undefined) return null;
25
+ if (value instanceof Date) return value.toISOString();
26
+ if (typeof value !== 'object') return value;
27
+ if ('formula' in value || 'sharedFormula' in value) return scalar(value.result);
28
+ if (value.richText) return value.richText.map(part => part.text).join('');
29
+ if ('text' in value) return value.text;
30
+ return null;
31
+ }
32
+
33
+ export function sourceDate(value, date1904 = false) {
34
+ if (value instanceof Date) value = value.toISOString();
35
+ if (typeof value === 'number' && value > 0 && value < 100000) {
36
+ if (!date1904 && Math.floor(value) === 60) return null;
37
+ const correction = !date1904 && value < 60 ? 86400000 : 0;
38
+ value = new Date(Date.UTC(date1904 ? 1904 : 1899, date1904 ? 0 : 11, date1904 ? 1 : 30) + Math.floor(value) * 86400000 + correction).toISOString();
39
+ }
40
+ const match = text(value).match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[ T].*)?$/);
41
+ if (!match) return null;
42
+ const result = `${match[1]}-${match[2].padStart(2, '0')}-${match[3].padStart(2, '0')}`;
43
+ const parsed = new Date(`${result}T00:00:00Z`);
44
+ return Number.isFinite(parsed.valueOf()) && parsed.toISOString().slice(0, 10) === result ? result : null;
45
+ }
46
+
47
+ function numeric(value) {
48
+ if (value === null || value === undefined || text(value) === '' || typeof value === 'boolean') return null;
49
+ const raw = text(value);
50
+ if (raw.includes(',') && !/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/.test(raw)) return null;
51
+ const clean = raw.replaceAll(',', '');
52
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(clean)) return null;
53
+ const result = Number(clean);
54
+ return Number.isFinite(result) ? result : null;
55
+ }
56
+
57
+ function canonical(header, value, date1904) {
58
+ value = scalar(value);
59
+ if (value === null || value === undefined || typeof value === 'string' && !value.trim()) return null;
60
+ // Only declared dates/numbers are normalized. Codes and document line IDs
61
+ // retain leading zeros and never pass through numeric conversion.
62
+ if (/日期$/.test(header)) return sourceDate(value, date1904) ?? text(value);
63
+ if (/金额|数量|瓶数|件数|拆分比例|含税单价|毫升/.test(header) && !/编号|编码/.test(header)) return numeric(value) ?? text(value);
64
+ return typeof value === 'string' ? value.trim() : value;
65
+ }
66
+
67
+ function fieldAccess(headers, values, positions = new Map(headers.map((header, index) => [normalizeHeader(header), index]))) {
68
+ return (...names) => {
69
+ for (const name of names) {
70
+ const index = positions.get(normalizeHeader(name));
71
+ if (index !== undefined) return values[index];
72
+ }
73
+ return null;
74
+ };
75
+ }
76
+
77
+ // Keep visit-history path interpretation aligned with inventory-history.mjs:
78
+ // the raw complete source path is the identity when explicit anchors cannot
79
+ // uniquely locate its hierarchy. A same-named short path is never substituted.
80
+ function visitOrganization(row) {
81
+ const get = row.get;
82
+ const rawPath = get('营销组织') === null || get('营销组织') === undefined ? '' : String(get('营销组织'));
83
+ const segments = rawPath.split('/').map(part => part.trim());
84
+ const company = text(get('营销公司'));
85
+ const anchors = [text(get('大区')), text(get('办事处')), text(get('客户主任单元'))];
86
+ const positions = segments.flatMap((part, index) => company && part === company ? [index] : []);
87
+ const companyIndex = positions.length === 1 ? positions[0] : -1;
88
+ const collapsed = anchors.filter((part, index) => !index || part !== anchors[index - 1]);
89
+ const suffixes = anchors.every(part => part === anchors[0]) ? [anchors, anchors.slice(0, 2), collapsed] : [anchors, collapsed];
90
+ if (companyIndex >= 0 && anchors.every(Boolean)) for (const suffix of suffixes) {
91
+ if (!suffix.every((part, index) => segments.at(index - suffix.length) === part)) continue;
92
+ const between = segments.slice(companyIndex + 1, -suffix.length);
93
+ if (companyIndex >= segments.length - suffix.length || ![1, 2].includes(between.length) || !between.every(Boolean)) continue;
94
+ return [company, between.length === 2 ? between[0] : '', between.at(-1), ...anchors];
95
+ }
96
+ return [rawPath || `未提供营销组织(${row.sheet ?? ''} 第 ${row.row ?? ''} 行)`, '', '', '', '', ''];
97
+ }
98
+
99
+ function organization(moduleId, row, sourceFormat) {
100
+ if (moduleId === 'inventory' && sourceFormat === 'visit-history') return visitOrganization(row);
101
+ const headers = {
102
+ invoice: ['销售大区', '办事处', '客户主任单元'], movement: ['大区名称', '办事处名称', '主任单元名称'],
103
+ opening: ['产品所属-大区', '产品所属-办事处', '产品所属-主任单元'], terminal: ['大区', '办事处', '主任单元'],
104
+ inventory: ['大区名称', '办事处名称', '单元名称'], banquet: ['大区', '办事处', '主任单元'], target: ['大区', '办事处', '主任单元'],
105
+ }[moduleId];
106
+ return [text(row.get('营销公司名称')), text(row.get('事业部名称', '事业部')), text(row.get('战区名称')), ...headers.map(header => text(row.get(header)))];
107
+ }
108
+
109
+ function recordDate(moduleId, row, date1904) {
110
+ const header = { invoice: '业务日期', movement: '扫码日期', opening: '抽奖日期', terminal: '签约日期', inventory: '提交时间' }[moduleId];
111
+ return header ? sourceDate(row.get(header), date1904) : null;
112
+ }
113
+
114
+ export async function inspectWorkbook({ file, moduleId, sha256, validation }) {
115
+ if (!moduleById.has(moduleId)) throw new Error('没有这个资料入口。');
116
+ validation ??= await validateWorkbook(file, moduleId);
117
+ if (!validation.ok) throw new Error('工作簿结构校验未通过,不能检查业务记录。');
118
+ const bytes = await readFile(file);
119
+ const actualSha = createHash('sha256').update(bytes).digest('hex');
120
+ if (sha256 && actualSha !== sha256.toLowerCase()) throw new Error('检查时文件内容已变化,请重新上传。');
121
+ const workbook = new ExcelJS.Workbook();
122
+ await workbook.xlsx.load(bytes);
123
+ const sheet = workbook.getWorksheet(validation.sheet);
124
+ if (!sheet) throw new Error('已验证的工作表无法读取。');
125
+ const headerRow = validation.headerRow ?? 1;
126
+ const count = Math.min(sheet.columnCount, moduleById.get(moduleId).sourceColumnLimit ?? sheet.columnCount);
127
+ const headers = Array.from({ length: count }, (_, index) => text(scalar(sheet.getRow(headerRow).getCell(index + 1).value)));
128
+ const rows = [];
129
+ sheet.eachRow({ includeEmpty: false }, (source, row) => {
130
+ if (row <= headerRow) return;
131
+ const values = headers.map((_, index) => scalar(source.getCell(index + 1).value));
132
+ if (values.some(value => text(value) !== '')) rows.push({ row, sheet: sheet.name, values });
133
+ });
134
+ return inspectRows({ moduleId, headers, rows, sheet: sheet.name, sha256: actualSha, date1904: workbook.properties.date1904, sourceFormat: validation.sourceFormat });
135
+ }
136
+
137
+ export function inspectRows({ moduleId, headers, rows, sheet, sha256, date1904 = false, sourceFormat }) {
138
+ if (!moduleById.has(moduleId)) throw new Error('未知板块,无法检查。');
139
+ const limited = headers.slice(0, moduleById.get(moduleId).sourceColumnLimit ?? headers.length);
140
+ const normalized = limited.map(header => normalizeHeader(header));
141
+ const positions = new Map(normalized.map((header, index) => [header, index]));
142
+ const sortedHeaders = [...normalized].sort();
143
+ const formatKey = hash([VERSION, moduleId, sheet, sourceFormat ?? '', sortedHeaders]);
144
+ const inspected = { version: VERSION, moduleId, sha256, sheet, formatKey, sourceFormat: sourceFormat ?? null,
145
+ rowCount: rows.length, coverage: { start: null, end: null }, groups: [], organizations: [], errors: [] };
146
+ const candidates = new Map(), organizations = new Map(), occurrences = new Map(), missingIdentityRows = [];
147
+ const duplicatesAllowed = moduleId === 'invoice' || moduleId === 'terminal';
148
+ for (const source of rows) {
149
+ const row = { ...source, sheet: source.sheet ?? sheet, get: fieldAccess(limited, source.values, positions) };
150
+ const date = recordDate(moduleId, row, date1904);
151
+ if (date) {
152
+ if (!inspected.coverage.start || date < inspected.coverage.start) inspected.coverage.start = date;
153
+ if (!inspected.coverage.end || date > inspected.coverage.end) inspected.coverage.end = date;
154
+ }
155
+ const orgPath = organization(moduleId, row, sourceFormat);
156
+ const orgKey = pathKey(orgPath);
157
+ const org = organizations.get(orgKey) ?? { key: hash([formatKey, orgPath]), path: orgPath, count: 0, start: null, end: null, missingDates: 0 };
158
+ org.count++;
159
+ if (date) { if (!org.start || date < org.start) org.start = date; if (!org.end || date > org.end) org.end = date; }
160
+ else org.missingDates++;
161
+ organizations.set(orgKey, org);
162
+ if (!duplicatesAllowed) continue;
163
+ const values = Object.fromEntries(limited.map((header, index) => [header, scalar(row.values[index])]));
164
+ const canonicalFields = normalized.map((header, index) => [header, canonical(header, row.values[index], date1904)]).sort((a, b) => a[0].localeCompare(b[0]));
165
+ let identity;
166
+ if (moduleId === 'invoice') {
167
+ const fields = ['单据类型', '单据编码', '单据行号'].map(field => text(row.get(field)));
168
+ if (fields.some(value => !value)) { missingIdentityRows.push(row.row); continue; }
169
+ identity = JSON.stringify(fields);
170
+ } else identity = JSON.stringify(canonicalFields.filter(([header]) => header !== normalizeHeader('协议编号')));
171
+ const fingerprint = hash([formatKey, canonicalFields]);
172
+ const occurrence = (occurrences.get(fingerprint) ?? 0) + 1;
173
+ occurrences.set(fingerprint, occurrence);
174
+ const evidence = { key: `${fingerprint}:${occurrence}`, row: row.row, values, orgPath, date,
175
+ amount: numeric(row.get('发票金额')), quantity: numeric(row.get('计价数量')), agreementId: text(row.get('协议编号')) || null };
176
+ const group = candidates.get(identity) ?? [];
177
+ group.push(evidence); candidates.set(identity, group);
178
+ }
179
+ if (missingIdentityRows.length) inspected.errors.push(`${missingIdentityRows.length} 行缺少单据类型、编码或行号,无法核对身份;Excel 行号:${missingIdentityRows.slice(0, 30).join('、')}${missingIdentityRows.length > 30 ? '等' : ''}。请补充来源后重新上传。`);
180
+ for (const [identity, members] of candidates) {
181
+ if (members.length < 2) continue;
182
+ const key = hash([VERSION, moduleId, formatKey, identity, members.map(member => member.key).sort()]);
183
+ inspected.groups.push({ id: key, key, reason: moduleId === 'invoice' ? '单据类型、单据编码和单据行号相同,需要确认哪些记录计入。' : '前 36 列除协议编号外内容相同,需要确认哪些协议计入。',
184
+ rows: members, differentFields: limited.filter(header => new Set(members.map(member => JSON.stringify(canonical(normalizeHeader(header), member.values[header], date1904)))).size > 1) });
185
+ }
186
+ inspected.organizations = [...organizations.values()].sort((a, b) => pathKey(a.path).localeCompare(pathKey(b.path)));
187
+ return inspected;
188
+ }
189
+
190
+ function legacySelection(inspection, group, legacy) {
191
+ const decision = legacy?.[inspection.moduleId];
192
+ if (!decision || !(decision.sourceSha256 === inspection.sha256 || inspection.lineage?.includes(decision.sourceSha256)) || decision.sheet !== inspection.sheet) return null;
193
+ if (inspection.moduleId === 'invoice') {
194
+ for (const pair of decision.duplicateDisposition?.groups ?? []) {
195
+ if (group.rows.length !== 2) continue;
196
+ const matches = item => group.rows.find(row => row.row === item?.row && isObject(item.values) && Object.keys(item.values).length && Object.entries(item.values).every(([field, expected]) => {
197
+ const actual = row.values[field];
198
+ if (/^\d{4}-\d{2}-\d{2}$/.test(text(expected))) return sourceDate(actual) === expected;
199
+ if (/金额|数量|瓶数|件数|拆分比例/.test(field)) return numeric(actual) !== null && numeric(actual) === numeric(expected);
200
+ return text(actual) === text(expected);
201
+ }));
202
+ const keep = matches(pair.keep), exclude = matches(pair.excludeInFutureProcessedResult);
203
+ if (keep && exclude && keep.key !== exclude.key) return [keep.key];
204
+ }
205
+ }
206
+ if (inspection.moduleId === 'terminal') {
207
+ const ids = group.rows.map(row => row.agreementId);
208
+ if (!ids.every(id => /^SD\d{13}$/.test(id ?? '')) || new Set(ids).size !== ids.length) return null;
209
+ if (!(decision.duplicateGroups ?? []).some(candidate => Array.isArray(candidate.agreementIds) && same([...candidate.agreementIds].sort(), [...ids].sort()))) return null;
210
+ const keep = group.rows.reduce((left, right) => BigInt(left.agreementId.slice(2)) > BigInt(right.agreementId.slice(2)) ? left : right);
211
+ return [keep.key];
212
+ }
213
+ return null;
214
+ }
215
+
216
+ export function validateDecision(inspection, body) {
217
+ if (!isObject(body)) throw new Error('处理决定格式无效。');
218
+ const group = inspection.groups.find(item => item.key === body.groupKey);
219
+ if (!group) throw new Error('这组候选已经变化,请刷新检查结果。');
220
+ if (body.remember !== true && body.remember !== false) throw new Error('请选择仅本次使用或记住这一组。');
221
+ if (!Array.isArray(body.keepKeys) || !body.keepKeys.length || body.keepKeys.length > group.rows.length || new Set(body.keepKeys).size !== body.keepKeys.length || body.keepKeys.some(key => !group.rows.some(row => row.key === key))) throw new Error('请至少选择一条本组记录,不能选择其他组或重复选择。');
222
+ return { moduleId: inspection.moduleId, formatKey: inspection.formatKey, groupKey: group.key, keepKeys: [...body.keepKeys].sort(), remember: body.remember, sourceSha256: inspection.sha256 };
223
+ }
224
+
225
+ export function resolveInspection(inspection, reviewState = {}, legacyDecisions = {}) {
226
+ const result = structuredClone(inspection);
227
+ result.pendingCount = 0; result.resolvedCount = 0;
228
+ for (const group of result.groups) {
229
+ const known = (reviewState.decisions ?? []).filter(record => record.moduleId === inspection.moduleId && record.formatKey === inspection.formatKey && record.groupKey === group.key);
230
+ const candidates = known.filter(record => alive(record) && boundTo(record, inspection));
231
+ const signatures = new Map();
232
+ let invalid = false;
233
+ for (const record of candidates) {
234
+ try {
235
+ const valid = validateDecision(inspection, record);
236
+ signatures.set(JSON.stringify(valid.keepKeys), { record, keepKeys: valid.keepKeys });
237
+ } catch { invalid = true; }
238
+ }
239
+ let selected = !invalid && signatures.size === 1 ? [...signatures.values()][0] : null;
240
+ if (!selected && !known.length) {
241
+ const keepKeys = legacySelection(inspection, group, legacyDecisions);
242
+ if (keepKeys) selected = { record: { id: `legacy:${inspection.sha256}:${group.key}`, sourceSha256: inspection.sha256 }, keepKeys };
243
+ }
244
+ group.status = selected ? 'resolved' : 'pending';
245
+ group.keepKeys = selected?.keepKeys ?? [];
246
+ group.decisionId = selected?.record.id ?? null;
247
+ group.reused = !!selected && selected.record.sourceSha256 !== inspection.sha256;
248
+ group.legacy = !!selected?.record.id?.startsWith('legacy:');
249
+ group.conflict = invalid || signatures.size > 1;
250
+ if (group.conflict) group.message = '已保存的处理决定冲突或失效,请撤销冲突决定后重新选择。';
251
+ if (selected) result.resolvedCount++; else result.pendingCount++;
252
+ }
253
+ result.organizationIssues = organizationIssues(inspection, reviewState);
254
+ result.errors = [...new Set([...result.errors, ...result.organizationIssues])];
255
+ return result;
256
+ }
257
+
258
+ function organizationIssues(inspection, reviewState) {
259
+ const issues = [];
260
+ const rules = (reviewState.organizationRules ?? []).filter(rule => alive(rule) && rule.moduleId === inspection.moduleId);
261
+ for (const org of inspection.organizations) {
262
+ const related = rules.filter(rule => validPath(rule.from) && same(rule.from, org.path));
263
+ if (!related.length) continue;
264
+ const applicable = related.filter(rule => rule.formatKey === inspection.formatKey && boundTo(rule, inspection));
265
+ const label = org.path.filter(Boolean).join(' / ');
266
+ const stale = related.some(rule => rule.remember === true && rule.formatKey !== inspection.formatKey);
267
+ // A new explicit mapping (including keep-original) is the user's scoped
268
+ // acknowledgment of a changed source format. Unrelated missing paths do
269
+ // not make this file pending.
270
+ if (stale && !applicable.length) issues.push(`组织“${label}”此前保存过对应关系,但本次来源格式已变化。请为当前格式确认对应关系,或选择保持原表归属。`);
271
+ const valid = [];
272
+ for (const rule of applicable) {
273
+ try { valid.push(validateOrganizationRule(inspection, rule)); }
274
+ catch (error) { issues.push(`组织“${label}”的已保存关系需要重新确认:${error.message}`); }
275
+ }
276
+ for (let i = 0; i < valid.length; i++) for (let j = i + 1; j < valid.length; j++) {
277
+ if (same(valid[i].to, valid[j].to)) continue;
278
+ const start = [valid[i].start ?? '0000', valid[j].start ?? '0000', org.start ?? '0000'].sort().at(-1);
279
+ const end = [valid[i].end ?? '9999', valid[j].end ?? '9999', org.end ?? '9999'].sort()[0];
280
+ if (start <= end || org.missingDates > 0) issues.push(`组织“${label}”在相同期间命中了不同的归属决定,请撤销冲突关系后重新确认。`);
281
+ }
282
+ }
283
+ return [...new Set(issues)];
284
+ }
285
+
286
+ export function applyDuplicateDecisions(rows, inspection, resolved) {
287
+ if (inspection.errors.length) throw new Error(inspection.errors.join(';'));
288
+ if (resolved.moduleId !== inspection.moduleId || resolved.sha256 !== inspection.sha256 || resolved.formatKey !== inspection.formatKey || resolved.groups.length !== inspection.groups.length) throw new Error('检查结果与当前文件不一致,请重新检查。');
289
+ const excluded = new Set();
290
+ for (const group of inspection.groups) {
291
+ const selected = resolved.groups.find(candidate => candidate.key === group.key);
292
+ if (selected?.status !== 'resolved') throw new Error('当前来源还有重复候选待确认,请在导入检查中选择计入记录。');
293
+ validateDecision(inspection, { groupKey: group.key, keepKeys: selected.keepKeys, remember: false });
294
+ const kept = new Set(selected.keepKeys);
295
+ for (const row of group.rows) if (!kept.has(row.key)) excluded.add(row.row);
296
+ }
297
+ return { rows: rows.filter(row => !excluded.has(row.row)), excludedRows: [...excluded].sort((a, b) => a - b) };
298
+ }
299
+
300
+ export function validateOrganizationRule(inspection, body) {
301
+ if (!isObject(body) || !['alias', 'transfer', 'merge', 'keep'].includes(body.kind)) throw new Error('请选择组织改名、归属调整、合并或保持原表。');
302
+ if (!validPath(body.from) || !validPath(body.to)) throw new Error('组织路径必须包含六个明确的层级位置。');
303
+ const from = body.from.map(text), to = body.to.map(text);
304
+ if (!inspection.organizations.some(org => same(org.path, from))) throw new Error('原组织不在当前文件中,请刷新检查结果。');
305
+ if (!from.some(Boolean)) throw new Error('原组织完全缺失,不能建立可复用的身份对应。');
306
+ if (body.kind === 'keep' ? !same(from, to) : !to.every(Boolean)) throw new Error(body.kind === 'keep' ? '保持原表时目标路径必须与原路径一致。' : '请补齐目标组织的完整六级路径。');
307
+ if (body.remember !== true && body.remember !== false) throw new Error('请选择本次使用或记住组织对应关系。');
308
+ if (body.remember && inspection.moduleId === 'inventory' && from[0].startsWith('未提供营销组织(')) throw new Error('原营销组织缺失,目前只能按这份文件的具体行处理,不能记住并跨文件复用。');
309
+ const start = body.start === null || body.start === undefined || body.start === '' ? null : body.start;
310
+ const end = body.end === null || body.end === undefined || body.end === '' ? null : body.end;
311
+ for (const value of [start, end]) if (value !== null && (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || sourceDate(value) !== value)) throw new Error('组织规则期间必须填写有效的 YYYY-MM-DD 日期。');
312
+ if (start && end && start > end) throw new Error('组织规则开始日期不能晚于结束日期。');
313
+ if ((start || end) && !DATE_MODULES.has(inspection.moduleId)) throw new Error('该来源没有已确认的逐笔归属日期,不能按签约日期、库存提交时间或上传时间推断组织调整期间。请选择整份来源范围。');
314
+ const source = inspection.organizations.find(org => same(org.path, from));
315
+ if ((start || end) && source.missingDates > 0) throw new Error('该组织有日期缺失记录,不能确定期间归属;请先核实来源,或明确选择整份来源范围。');
316
+ return { moduleId: inspection.moduleId, formatKey: inspection.formatKey, from, to, start, end, remember: body.remember, sourceSha256: inspection.sha256, kind: body.kind };
317
+ }
318
+
319
+ export function applyOrganizationRules(payload, reviewState = {}) {
320
+ const report = { status: 'not-configured', appliedRows: 0, appliedRules: [], conflicts: [], errors: [], modules: {} };
321
+ const rules = (reviewState.organizationRules ?? []).filter(alive);
322
+ if (!rules.length) return report;
323
+ report.status = 'confirmed';
324
+ const appliedRules = new Set();
325
+ for (const [moduleId, output] of Object.entries(payload.modules)) {
326
+ const source = payload.sources[moduleId];
327
+ if (!source) continue;
328
+ const selected = rules.filter(rule => rule.moduleId === moduleId && rule.formatKey === source.formatKey && boundTo(rule, source));
329
+ if (!selected.length) continue;
330
+ const detail = { appliedRows: 0, conflicts: 0, errors: [] };
331
+ report.modules[moduleId] = detail;
332
+ for (const row of output.records) {
333
+ row.originalOrgPath ??= [...row.orgPath];
334
+ const matches = selected.filter(rule => validPath(rule.from) && same(rule.from, row.originalOrgPath));
335
+ if (!matches.length) continue;
336
+ const applicable = [];
337
+ let invalid = false;
338
+ for (const rule of matches) {
339
+ const badPath = !validPath(rule.to) || (rule.kind !== 'keep' && !rule.to.every(Boolean)) || !['alias', 'transfer', 'merge', 'keep'].includes(rule.kind) || (rule.kind === 'keep' && !same(rule.from, rule.to)) || (moduleId === 'inventory' && rule.remember && rule.from[0].startsWith('未提供营销组织('));
340
+ const badPeriod = [rule.start, rule.end].some(value => value != null && (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || sourceDate(value) !== value)) || (rule.start && rule.end && rule.start > rule.end);
341
+ if (badPath || badPeriod || (rule.start || rule.end) && (!DATE_MODULES.has(moduleId) || !row.date)) { invalid = true; break; }
342
+ if (rule.start && row.date < rule.start || rule.end && row.date > rule.end) continue;
343
+ applicable.push(rule);
344
+ }
345
+ const destinations = new Set(applicable.map(rule => pathKey(rule.to)));
346
+ if (invalid || destinations.size > 1) {
347
+ detail.conflicts++;
348
+ row.reviewOrganizationConflict = true;
349
+ report.conflicts.push({ moduleId, sourceRef: row.sourceRef, from: row.originalOrgPath, ruleIds: matches.map(rule => rule.id), reason: invalid ? '组织规则缺少可靠的路径或日期依据。' : '相同记录命中了不同的组织归属决定。' });
350
+ continue;
351
+ }
352
+ if (!applicable.length) continue;
353
+ const destination = applicable[0].to;
354
+ row.orgPath = [...destination]; row.orgKey = pathKey(destination);
355
+ row.org = Object.fromEntries(ORG_FIELDS.map((field, index) => [field, destination[index]]));
356
+ row.reviewOrganization = { ruleIds: applicable.map(rule => rule.id), kinds: [...new Set(applicable.map(rule => rule.kind))], status: 'applied' };
357
+ for (const rule of applicable) appliedRules.add(rule.id);
358
+ detail.appliedRows++; report.appliedRows++;
359
+ }
360
+ }
361
+ report.appliedRules = [...appliedRules];
362
+ if (report.conflicts.length) report.status = 'pending';
363
+ return report;
364
+ }
@@ -0,0 +1,182 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { atomicJson } from './store.mjs';
5
+ import { moduleDefinitions } from './modules.mjs';
6
+ import { resolveInspection, validateDecision, validateOrganizationRule } from './review-engine.mjs';
7
+ import { lineageShas } from './incremental/flow.mjs';
8
+
9
+ export const emptyReview = () => ({ version: 1, revision: 0, decisions: [], organizationRules: [], history: [] });
10
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
11
+ const error = (message, status = 400) => Object.assign(new Error(message), { status });
12
+ const live = rule => !rule.revokedAt;
13
+ function validated(fn, ...args) { try { return fn(...args); } catch (e) { throw error(e.message); } }
14
+ function organizationConflict(a, b) {
15
+ return live(a) && live(b) && a.moduleId === b.moduleId && a.formatKey === b.formatKey && same(a.from, b.from)
16
+ && (a.remember || b.remember || a.sourceSha256 === b.sourceSha256)
17
+ && (a.start || '0000') <= (b.end || '9999') && (b.start || '0000') <= (a.end || '9999')
18
+ && !same(a.to, b.to);
19
+ }
20
+
21
+ export function createReviewService({ store, dataDir, scan }) {
22
+ const cache = new Map();
23
+ const settings = () => store.state.review ?? emptyReview();
24
+ function resolveCurrent(raw, rules, old) {
25
+ return resolveInspection(raw, rules, old);
26
+ }
27
+ async function legacy() {
28
+ try { return JSON.parse(await readFile(resolve(dataDir, 'generation-decisions.json'), 'utf8')); }
29
+ catch (e) { if (e.code === 'ENOENT') return {}; throw error('原业务决定文件无法读取,请先核实文件。', 422); }
30
+ }
31
+ async function inspection(upload) {
32
+ if (!upload) return null;
33
+ if (cache.has(upload.id)) return cache.get(upload.id);
34
+ try {
35
+ const result = JSON.parse(await readFile(resolve(dataDir, 'uploads', upload.id, 'inspection.json'), 'utf8'));
36
+ if (result.sha256 !== upload.sha256 || result.moduleId !== upload.moduleId || result.version !== 1) throw error('检查记录与来源不一致,请重新检查。', 422);
37
+ cache.set(upload.id, result); return result;
38
+ } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
39
+ }
40
+ async function saveInspection(upload, result) {
41
+ await atomicJson(resolve(dataDir, 'uploads', upload.id, 'inspection.json'), result);
42
+ cache.set(upload.id, result);
43
+ }
44
+ async function inspect(upload) {
45
+ const result = await scan({ file: resolve(dataDir, 'uploads', upload.id, 'source.xlsx'), moduleId: upload.moduleId, sha256: upload.sha256, validation: upload.validation });
46
+ await saveInspection(upload, result); return result;
47
+ }
48
+ const selected = (state, id) => state.uploads.find(u => u.id === (state.candidates?.[id] || state.active[id]) && u.moduleId === id);
49
+ async function view() {
50
+ const rules = settings(), old = await legacy();
51
+ const modules = [];
52
+ for (const module of moduleDefinitions) {
53
+ const upload = selected(store.state, module.id);
54
+ const raw = await inspection(upload);
55
+ const result = raw ? resolveCurrent({ ...raw, lineage: lineageShas(store.state, upload.id) }, rules, old) : null;
56
+ modules.push({ id: module.id, title: module.title, uploadId: upload?.id ?? null, filename: upload?.filename ?? null,
57
+ sha256: upload?.sha256 ?? null, activeUploadId: store.state.active[module.id] ?? null,
58
+ status: !upload ? 'missing' : !result ? 'unchecked' : result.errors.length ? 'error' : result.pendingCount ? 'pending' : 'ready', inspection: result });
59
+ }
60
+ return { revision: rules.revision, modules, decisions: rules.decisions, organizationRules: rules.organizationRules, history: rules.history };
61
+ }
62
+ async function update(change, action, detail = {}) {
63
+ await store.update(async next => {
64
+ next.review ??= emptyReview(); next.candidates ??= {};
65
+ await change(next);
66
+ next.review.revision++;
67
+ next.review.history.push({ id: randomUUID(), action, at: new Date().toISOString(), ...detail });
68
+ });
69
+ }
70
+ async function promote(next) {
71
+ const old = await legacy();
72
+ for (const module of moduleDefinitions) {
73
+ const upload = selected(next, module.id), raw = await inspection(upload);
74
+ if (!raw) continue;
75
+ const result = resolveCurrent({ ...raw, lineage: lineageShas(next, upload.id) }, next.review, old);
76
+ upload.reviewStatus = result.errors.length ? 'error' : result.pendingCount ? 'pending' : 'ready';
77
+ if (!result.pendingCount && !result.errors.length) {
78
+ next.active[module.id] = upload.id; delete next.candidates[module.id];
79
+ } else next.candidates[module.id] = upload.id;
80
+ }
81
+ }
82
+ async function check() {
83
+ // Continue checking independent sources even when another source cannot be read.
84
+ for (const module of moduleDefinitions) {
85
+ const upload = selected(store.state, module.id);
86
+ if (!upload) continue;
87
+ try { await inspect(upload); }
88
+ catch (e) {
89
+ await saveInspection(upload, { version: 1, moduleId: module.id, sha256: upload.sha256, sheet: upload.validation?.sheet ?? '', formatKey: '', rowCount: upload.validation?.rowCount ?? 0, coverage: { start: null, end: null }, groups: [], organizations: [], errors: [e.message] });
90
+ }
91
+ }
92
+ await update(promote, 'check');
93
+ return view();
94
+ }
95
+ function assertRevision(body) {
96
+ if (!Number.isSafeInteger(body.revision) || body.revision !== settings().revision) throw error('检查结果已变化,请刷新后再保存;原选择尚未改写。', 409);
97
+ }
98
+ async function currentInspection(body) {
99
+ const upload = store.state.uploads.find(u => u.id === body.uploadId);
100
+ if (!upload || selected(store.state, upload.moduleId)?.id !== upload.id) throw error('当前来源已变化,请刷新检查结果。', 409);
101
+ const result = await inspection(upload);
102
+ if (!result || result.errors.length) throw error('请先完成来源检查并处理无法读取的问题。', 422);
103
+ return result;
104
+ }
105
+ async function mutate(action, body) {
106
+ assertRevision(body);
107
+ if (action === 'decisions') {
108
+ const raw = await currentInspection(body), clean = validated(validateDecision, raw, body);
109
+ const id = randomUUID(), createdAt = new Date().toISOString();
110
+ await update(async next => {
111
+ // Saving a new explicit choice revises this group's previous choices, not unrelated groups.
112
+ for (const item of next.review.decisions) if (live(item) && item.moduleId === clean.moduleId && item.formatKey === clean.formatKey && item.groupKey === clean.groupKey && (item.remember || clean.remember || item.sourceSha256 === clean.sourceSha256)) item.revokedAt = createdAt;
113
+ next.review.decisions.push({ id, createdAt, ...clean }); await promote(next);
114
+ }, 'decision', { decisionId: id, moduleId: clean.moduleId, uploadId: body.uploadId });
115
+ } else if (action === 'organizations') {
116
+ const raw = await currentInspection(body), clean = validated(validateOrganizationRule, raw, body);
117
+ if (settings().organizationRules.some(rule => organizationConflict(rule, clean))) throw error('此期间已有不同的组织对应关系,请先撤销原关系再保存。', 409);
118
+ const id = randomUUID();
119
+ await update(async next => { next.review.organizationRules.push({ id, createdAt: new Date().toISOString(), ...clean }); await promote(next); }, 'organization', { ruleId: id, moduleId: clean.moduleId });
120
+ } else if (action === 'revoke') {
121
+ if (typeof body.id === 'string' && body.id.startsWith('legacy:')) {
122
+ const current = await view();
123
+ const module = current.modules.find(module => module.inspection?.groups.some(group => group.decisionId === body.id));
124
+ const group = module?.inspection.groups.find(group => group.decisionId === body.id);
125
+ if (!group || group.status !== 'resolved') throw error('原处理记录已变化,请刷新后重试。', 409);
126
+ const clean = validateDecision(module.inspection, { groupKey: group.key, keepKeys: group.keepKeys, remember: false });
127
+ const id = randomUUID(), at = new Date().toISOString();
128
+ await update(async next => { next.review.decisions.push({ id, ...clean, createdAt: at, revokedAt: at, legacyDecisionId: body.id }); await promote(next); }, 'revoke', { recordId: id });
129
+ return view();
130
+ }
131
+ const item = [...settings().decisions, ...settings().organizationRules].find(item => item.id === body.id && live(item));
132
+ if (!item) throw error('没有可撤销的处理记录,请刷新后重试。', 404);
133
+ await update(async next => {
134
+ [...next.review.decisions, ...next.review.organizationRules].find(item => item.id === body.id).revokedAt = new Date().toISOString();
135
+ await promote(next);
136
+ }, 'revoke', { recordId: body.id });
137
+ } else if (action === 'select') {
138
+ const upload = store.state.uploads.find(u => u.id === body.uploadId && u.moduleId === body.moduleId);
139
+ if (!upload) throw error('上传版本不存在。', 404);
140
+ if (!await inspection(upload)) await inspect(upload);
141
+ await update(async next => { next.candidates[body.moduleId] = upload.id; await promote(next); }, 'select', { uploadId: upload.id, moduleId: upload.moduleId });
142
+ } else if (action === 'restore') {
143
+ const backup = body.backup;
144
+ if (!backup || backup.kind !== 'theater-review-settings' || backup.version !== 1 || !Array.isArray(backup.decisions) || !Array.isArray(backup.organizationRules) || backup.decisions.length + backup.organizationRules.length > 20000) throw error('不是受支持的处理设置备份。');
145
+ const imported = { decisions: [], organizationRules: [] };
146
+ const ids = new Set([...settings().decisions, ...settings().organizationRules].map(item => item.id));
147
+ for (const type of ['decisions', 'organizationRules']) for (const item of backup[type]) {
148
+ if (!item || typeof item.id !== 'string' || !/^[a-f0-9-]{36}$/.test(item.id) || !Number.isFinite(Date.parse(item.createdAt)) || (item.revokedAt && !Number.isFinite(Date.parse(item.revokedAt)))) throw error('备份中的处理记录无效。');
149
+ if (ids.has(item.id)) {
150
+ const existing = [...settings().decisions, ...settings().organizationRules].find(row => row.id === item.id);
151
+ if (!same(existing, item)) throw error('备份与本机同一处理记录不同,未覆盖本机决定。', 409);
152
+ continue;
153
+ }
154
+ const source = store.state.uploads.find(u => u.moduleId === item.moduleId && u.sha256 === item.sourceSha256);
155
+ if (!source) throw error('备份对应的原始上传尚未恢复;请先恢复或导入对应 Excel。', 422);
156
+ const raw = await inspection(source) ?? await inspect(source);
157
+ const clean = validated(type === 'decisions' ? validateDecision : validateOrganizationRule, raw, item);
158
+ if (clean.formatKey !== item.formatKey || clean.sourceSha256 !== item.sourceSha256) throw error('备份与来源核对不一致。');
159
+ const record = { id: item.id, createdAt: item.createdAt, ...clean, ...(item.revokedAt ? { revokedAt: item.revokedAt } : {}) };
160
+ const candidates = [...settings()[type], ...imported[type]];
161
+ if (type === 'organizationRules' && candidates.some(row => organizationConflict(row, record))) throw error('备份中存在冲突的组织关系,未导入。', 409);
162
+ if (type === 'decisions' && live(record) && candidates.some(row => live(row) && row.moduleId === record.moduleId && row.formatKey === record.formatKey && row.groupKey === record.groupKey && (row.remember || record.remember || row.sourceSha256 === record.sourceSha256) && !same([...row.keepKeys].sort(), record.keepKeys))) throw error('备份中存在冲突的重复处理决定,未导入。', 409);
163
+ imported[type].push(record); ids.add(record.id);
164
+ }
165
+ const history = backup.history ?? [];
166
+ if (!Array.isArray(history) || history.length > 100000) throw error('备份的操作记录格式无效。');
167
+ const restoredHistory = history.map(item => {
168
+ if (!item || typeof item.id !== 'string' || !/^[a-f0-9-]{36}$/.test(item.id) || typeof item.action !== 'string' || item.action.length > 50 || !Number.isFinite(Date.parse(item.at))) throw error('备份的操作记录无效。');
169
+ return Object.fromEntries(Object.entries(item).filter(([key, value]) => ['id', 'action', 'at', 'decisionId', 'ruleId', 'recordId', 'moduleId', 'uploadId', 'imported'].includes(key) && (typeof value === 'string' && value.length < 1000 || typeof value === 'number' && Number.isSafeInteger(value))));
170
+ });
171
+ await update(async next => {
172
+ next.review.decisions.push(...imported.decisions); next.review.organizationRules.push(...imported.organizationRules);
173
+ const seen = new Set(next.review.history.map(item => item.id));
174
+ for (const item of restoredHistory) if (!seen.has(item.id)) { next.review.history.push(item); seen.add(item.id); }
175
+ await promote(next);
176
+ }, 'restore', { imported: imported.decisions.length + imported.organizationRules.length });
177
+ } else throw error('没有这个检查操作。', 404);
178
+ return view();
179
+ }
180
+ function backup() { return { kind: 'theater-review-settings', version: 1, exportedAt: new Date().toISOString(), decisions: settings().decisions, organizationRules: settings().organizationRules, history: settings().history, note: '仅包含处理设置,不包含原始 Excel。完整业务迁移请保留整个本机数据目录。' }; }
181
+ return { view, check, mutate, backup, inspect, inspection, saveInspection, promote, settings, legacy };
182
+ }