dsh-data-dashboard 0.0.0-stage → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +35 -2
  2. package/assets/theater-board.svg +1 -0
  3. package/backend/incremental/flow.mjs +492 -0
  4. package/backend/incremental/jobs.mjs +58 -0
  5. package/backend/incremental/xlsx-rows.mjs +145 -0
  6. package/backend/job-worker.mjs +22 -0
  7. package/backend/modules/banquet/index.mjs +46 -0
  8. package/backend/modules/inventory/index.mjs +45 -0
  9. package/backend/modules/inventory/legacy-fields.mjs +83 -0
  10. package/backend/modules/invoice/index.mjs +72 -0
  11. package/backend/modules/movement/index.mjs +68 -0
  12. package/backend/modules/opening/index.mjs +48 -0
  13. package/backend/modules/target/index.mjs +45 -0
  14. package/backend/modules/terminal/index.mjs +114 -0
  15. package/backend/modules.mjs +12 -0
  16. package/backend/public/admin.css +220 -0
  17. package/backend/public/admin.js +772 -0
  18. package/backend/public/board.css +70 -0
  19. package/backend/public/board.html +50 -0
  20. package/backend/public/board.js +153 -0
  21. package/backend/public/index.html +113 -0
  22. package/backend/public/org-mapping.js +49 -0
  23. package/backend/public/review.css +5 -0
  24. package/backend/public/review.js +452 -0
  25. package/backend/real-data/generate-dashboard.mjs +137 -0
  26. package/backend/real-data/inventory-history.mjs +316 -0
  27. package/backend/real-data/organization-mapping.mjs +166 -0
  28. package/backend/real-data/source-payload.mjs +459 -0
  29. package/backend/real-data/terminal-components.mjs +280 -0
  30. package/backend/real-data/terminal-structure.css +105 -0
  31. package/backend/real-data/terminal-structure.mjs +276 -0
  32. package/backend/real-data/v10-components.mjs +112 -0
  33. package/backend/real-data/v10-details.css +18 -0
  34. package/backend/real-data/v10-details.mjs +251 -0
  35. package/backend/real-data/v10-layout.css +27 -0
  36. package/backend/real-data/v10-model.mjs +568 -0
  37. package/backend/real-data/v10-overview-data.mjs +253 -0
  38. package/backend/real-data/v10-overview.css +370 -0
  39. package/backend/real-data/v10-overview.mjs +340 -0
  40. package/backend/real-data/v10-presentation.mjs +354 -0
  41. package/backend/real-data/v10-shell.html +1097 -0
  42. package/backend/real-data/v10-template.mjs +353 -0
  43. package/backend/recognition/fingerprint.mjs +32 -0
  44. package/backend/recognition/headers.mjs +2 -0
  45. package/backend/recognition/module-definition.mjs +4 -0
  46. package/backend/recognition/result.mjs +29 -0
  47. package/backend/recognition/upload-limits.mjs +14 -0
  48. package/backend/review-engine.mjs +364 -0
  49. package/backend/review-service.mjs +182 -0
  50. package/backend/server.mjs +569 -0
  51. package/backend/store.mjs +68 -0
  52. package/backend/target-template.mjs +47 -0
  53. package/backend/validate-workbook.mjs +251 -0
  54. package/backend/web-sync/README.md +37 -0
  55. package/backend/web-sync/client.mjs +63 -0
  56. package/backend/web-sync/exporter.mjs +260 -0
  57. package/backend/web-sync/local.html +34 -0
  58. package/backend/web-sync/server.mjs +147 -0
  59. package/build-manifest.json +80 -0
  60. package/client.js +54 -0
  61. package/cordis.patch.yml +3 -0
  62. package/index.js +117 -0
  63. package/lib/dist-manifest.mjs +19 -0
  64. package/lib/market-index.mjs +56 -0
  65. package/lib/package-audit.mjs +34 -0
  66. package/lib/settings.mjs +71 -0
  67. package/lib/tool-definitions.mjs +56 -0
  68. package/lib/tools.mjs +255 -0
  69. package/locale/en.json +6 -0
  70. package/locale/zh.json +6 -0
  71. package/package.json +71 -4
@@ -0,0 +1,316 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ const SOURCE_HEADERS = [
4
+ '经销商名称', '经销商编码', '营销组织', '营销公司', '事业部', '大区', '办事处', '客户主任单元',
5
+ '提交人', '手机号', '提交时间', '经销商类型', '盘点编码', '产品名称', '库存瓶数', '提交时实时库存数',
6
+ '提交时实时库存数金额', '差异', '是否存在盘点偏差', '偏差数量(瓶)', '是否发起补录', '补录单数据状态',
7
+ ];
8
+ const NUMBER_FIELDS = [
9
+ ['counted', '库存瓶数'], ['system', '提交时实时库存数'],
10
+ ['systemAmount', '提交时实时库存数金额'], ['sourceVariance', '偏差数量(瓶)'],
11
+ ];
12
+ const rawText = value => value === null || value === undefined ? '' : String(value);
13
+ const text = value => rawText(value).trim();
14
+ const absent = value => value === null || value === undefined || typeof value === 'string' && !value.trim();
15
+ const pad = value => String(value).padStart(2, '0');
16
+
17
+ function sourceNumber(value) {
18
+ if (absent(value)) return { value: null, status: 'missing' };
19
+ if (typeof value !== 'number' && typeof value !== 'string') return { value: null, status: 'invalid' };
20
+ let normalized = text(value);
21
+ if (normalized.includes(',')) {
22
+ if (!/^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d+)?$/.test(normalized)) return { value: null, status: 'invalid' };
23
+ normalized = normalized.replaceAll(',', '');
24
+ }
25
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(normalized)) return { value: null, status: 'invalid' };
26
+ const number = Number(normalized);
27
+ return Number.isFinite(number) ? { value: number, status: 'valid' } : { value: null, status: 'invalid' };
28
+ }
29
+
30
+ // Source numbers may contain decimals. Subtract their decimal representations
31
+ // without introducing a binary artefact such as 0.3 - 0.2 = 0.09999999999999998.
32
+ function difference(left, right) {
33
+ if (left === null || right === null) return null;
34
+ const parts = [left, right].map(value => {
35
+ const match = String(value).match(/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i);
36
+ let digits = BigInt(`${match[1]}${match[2]}${match[3] ?? ''}`);
37
+ let scale = (match[3]?.length ?? 0) - Number(match[4] ?? 0);
38
+ if (scale < 0) { digits *= 10n ** BigInt(-scale); scale = 0; }
39
+ return { digits, scale };
40
+ });
41
+ const scale = Math.max(...parts.map(part => part.scale));
42
+ const result = parts[0].digits * 10n ** BigInt(scale - parts[0].scale) - parts[1].digits * 10n ** BigInt(scale - parts[1].scale);
43
+ const number = Number(result) / 10 ** scale;
44
+ return Number.isFinite(number) ? number : null;
45
+ }
46
+
47
+ function submittedTime(value, date1904) {
48
+ // Excel serial dates have no timezone. Preserve the workbook's wall-clock
49
+ // components, including its fractional day, at the contracted second precision.
50
+ if (typeof value === 'number') {
51
+ if (!Number.isFinite(value) || value < 0 || value >= 2958466 || !date1904 && Math.floor(value) === 60) return null;
52
+ const epoch = Date.UTC(date1904 ? 1904 : 1899, date1904 ? 0 : 11, date1904 ? 1 : 30);
53
+ const early1900Correction = !date1904 && value < 60 ? 86400000 : 0;
54
+ const parsed = new Date(epoch + early1900Correction + Math.round(value * 86400) * 1000);
55
+ if (!Number.isFinite(parsed.valueOf())) return null;
56
+ value = parsed.toISOString();
57
+ }
58
+ // A trailing Z is accepted from the shared Excel Date scalar adapter. No
59
+ // timezone offset is applied; explicit non-zero offsets require source review.
60
+ const match = text(value).match(/^(\d{4})[-/](\d{1,2})[-/](\d{1,2})(?:[ T](\d{1,2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?)?Z?$/);
61
+ if (!match) return null;
62
+ const [year, month, day, hour, minute, second] = match.slice(1).map(value => Number(value ?? 0));
63
+ if (year < 1000 || month < 1 || month > 12 || day < 1 || hour > 23 || minute > 59 || second > 59) return null;
64
+ const parsed = new Date(Date.UTC(year, month - 1, day, hour, minute, second));
65
+ if (parsed.getUTCFullYear() !== year || parsed.getUTCMonth() !== month - 1 || parsed.getUTCDate() !== day) return null;
66
+ return `${year}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:${pad(second)}`;
67
+ }
68
+
69
+ function organization(row) {
70
+ const get = row.get;
71
+ const sourceOrgPath = rawText(get('营销组织'));
72
+ const segments = sourceOrgPath.split('/').map(part => part.trim());
73
+ const company = text(get('营销公司')), region = text(get('大区'));
74
+ const office = text(get('办事处')), unit = text(get('客户主任单元'));
75
+ const companyIndices = segments.flatMap((part, index) => company && part === company ? [index] : []);
76
+ const companyIndex = companyIndices.length === 1 ? companyIndices[0] : -1;
77
+ const anchors = [region, office, unit];
78
+ // The explicit columns can assign adjacent roles to the same source node
79
+ // (e.g. a directly managed office is both region and office). Accept that
80
+ // exact node once in the source suffix, but preserve both explicit roles in
81
+ // orgPath. This is source-field expansion, not an alias to another source.
82
+ const collapsedAnchors = anchors.filter((part, index) => !index || part !== anchors[index - 1]);
83
+ const suffixes = anchors.every(part => part === anchors[0])
84
+ ? [anchors, anchors.slice(0, 2), collapsedAnchors] : [anchors, collapsedAnchors];
85
+ let middle = [], parsed = false;
86
+ if (companyIndex >= 0 && anchors.every(Boolean)) for (const suffix of suffixes) {
87
+ if (!suffix.every((part, index) => segments.at(index - suffix.length) === part)) continue;
88
+ const between = segments.slice(companyIndex + 1, -suffix.length);
89
+ if (companyIndex >= segments.length - suffix.length || ![1, 2].includes(between.length) || !between.every(Boolean)) continue;
90
+ middle = between; parsed = true; break;
91
+ }
92
+ // An unparsed path is an independent identity. In particular, matching short
93
+ // region/office/unit labels cannot silently join an ambiguous source path.
94
+ const org = parsed ? {
95
+ marketingCompany: company, businessUnit: middle.length === 2 ? middle[0] : '',
96
+ theater: middle.at(-1), region, office, unit,
97
+ } : {
98
+ marketingCompany: sourceOrgPath || `未提供营销组织(${row.sheet ?? ''} 第 ${row.row ?? ''} 行)`,
99
+ businessUnit: '', theater: '', region: '', office: '', unit: '',
100
+ };
101
+ const orgPath = Object.values(org);
102
+ return { org, orgPath, orgKey: JSON.stringify(orgPath), sourceOrgPath, inventoryOrganizationUnparsed: parsed ? 0 : 1 };
103
+ }
104
+
105
+ const addTo = (map, key, value) => {
106
+ const values = map.get(key);
107
+ if (values) values.push(value); else map.set(key, [value]);
108
+ };
109
+ const compareRecords = (left, right) => left.submittedAt.localeCompare(right.submittedAt) ||
110
+ left.inventoryGroupKey.localeCompare(right.inventoryGroupKey) || left.sourceRef.row - right.sourceRef.row;
111
+ const evidence = row => ({ sheet: row.sheet ?? '拜访采集-库存盘点', row: row.row });
112
+
113
+ function addPreviousComparison(observations, invalidDate) {
114
+ // Resolve the immediately preceding distinct timestamp before month-end
115
+ // compression. A missing count or a tied bucket is still the preceding
116
+ // observation; never skip it in favour of an older, usable number.
117
+ const buckets = new Map();
118
+ for (const record of observations) addTo(buckets, record.submittedAt, record);
119
+ let previous = null;
120
+ for (const timestamp of [...buckets.keys()].sort()) {
121
+ const current = buckets.get(timestamp);
122
+ for (const record of current) {
123
+ record.previousSubmittedAt = !invalidDate && previous ? previous[0].submittedAt : null;
124
+ record.previousCounted = !invalidDate && previous?.length === 1 ? previous[0].counted : null;
125
+ record.changeFromPrevious = null;
126
+ if (invalidDate) record.inventoryComparisonStatus = 'invalid-date';
127
+ else if (current.length > 1) record.inventoryComparisonStatus = 'current-conflict';
128
+ else if (previous?.length > 1) record.inventoryComparisonStatus = 'previous-conflict';
129
+ else if (!previous) record.inventoryComparisonStatus = 'no-previous';
130
+ else if (record.counted === null || record.previousCounted === null) record.inventoryComparisonStatus = 'missing-counted';
131
+ else {
132
+ const change = difference(record.counted, record.previousCounted);
133
+ record.inventoryComparisonStatus = change === null ? 'invalid-change' : 'comparable';
134
+ record.changeFromPrevious = change;
135
+ }
136
+ }
137
+ previous = current;
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Normalize historical inventory observations without changing input rows.
143
+ * `records` contains every tied month-end candidate for each exact dealer/name
144
+ * group. `latestRecords` contains all globally latest candidates. Neither array
145
+ * is an additive historical inventory series. Local-only diagnostics retain
146
+ * excluded-row references and duplicate evidence; callers should not embed them
147
+ * in offline HTML. Unknown dates are exposed separately for filtered blocking.
148
+ */
149
+ export function processInventoryHistory(rows, { date1904 = false } = {}) {
150
+ const diagnostics = {
151
+ sourceRows: 0, missingDealerCodes: 0, missingProductNames: 0,
152
+ missingIdentityRows: 0, invalidNumbers: 0, missingNumbers: 0, invalidDates: 0,
153
+ exactDuplicateRows: 0, exactDuplicateGroups: 0, sameTimeDuplicateRows: 0,
154
+ sameTimeDuplicateGroups: 0, sameStocktakeDuplicateRows: 0, sameStocktakeDuplicateGroups: 0,
155
+ latestRows: 0, latestTieGroups: 0, latestTieRows: 0, monthEndRows: 0,
156
+ historyCompressedRows: 0, validObservationRows: 0, groupCount: 0,
157
+ unparsedOrganizationRows: 0, organizationChangedGroups: 0,
158
+ negativeSystemRows: 0, negativeCountedRows: 0, negativeSystemAmountRows: 0,
159
+ supplementReviewRows: 0, missingIdentity: [], numericIssues: [], invalidDateRows: [],
160
+ invalidDateGroupKeys: [], duplicateGroups: [], organizationChanges: [],
161
+ unparsedOrganizations: [], compressedRows: [],
162
+ };
163
+ const all = [], groups = new Map(), exact = new Map(), byTime = new Map(), byStocktake = new Map();
164
+ const uncertain = new Map(), groupOrganizations = new Map();
165
+ let earliest = null, latest = null;
166
+ for (const row of rows) {
167
+ diagnostics.sourceRows++;
168
+ const get = row.get, sourceRef = evidence(row), issues = [];
169
+ const values = Array.isArray(row.values) ? row.values : SOURCE_HEADERS.map(header => get(header));
170
+ const digest = createHash('sha256').update(JSON.stringify(values)).digest('hex');
171
+ addTo(exact, digest, sourceRef);
172
+ const dealerCode = rawText(get('经销商编码')), productName = rawText(get('产品名称'));
173
+ const missingCode = !dealerCode.trim(), missingProduct = !productName.trim();
174
+ if (missingCode) diagnostics.missingDealerCodes++;
175
+ if (missingProduct) diagnostics.missingProductNames++;
176
+ const inventoryGroupKey = missingCode || missingProduct ? null : JSON.stringify([dealerCode, productName]);
177
+ const submittedAt = submittedTime(get('提交时间'), date1904);
178
+ if (submittedAt) {
179
+ if (!earliest || submittedAt < earliest) earliest = submittedAt;
180
+ if (!latest || submittedAt > latest) latest = submittedAt;
181
+ } else {
182
+ diagnostics.invalidDates++;
183
+ diagnostics.invalidDateRows.push({ ...sourceRef, inventoryGroupKey, value: get('提交时间') ?? null });
184
+ }
185
+ const org = organization(row);
186
+ if (org.inventoryOrganizationUnparsed) {
187
+ diagnostics.unparsedOrganizationRows++;
188
+ diagnostics.unparsedOrganizations.push({ ...sourceRef, sourceOrgPath: org.sourceOrgPath });
189
+ issues.push('完整组织路径未解析');
190
+ }
191
+ const numbers = {};
192
+ for (const [field, header] of NUMBER_FIELDS) {
193
+ const parsed = sourceNumber(get(header));
194
+ numbers[field] = parsed.value;
195
+ if (parsed.status !== 'valid') {
196
+ diagnostics[parsed.status === 'missing' ? 'missingNumbers' : 'invalidNumbers']++;
197
+ diagnostics.numericIssues.push({ ...sourceRef, field, header, status: parsed.status, value: get(header) ?? null });
198
+ // A missing source variance is preserved; it does not invalidate the
199
+ // independently calculated difference when both source counts exist.
200
+ if (field !== 'sourceVariance' || parsed.status === 'invalid') issues.push(`${header}${parsed.status === 'missing' ? '缺失' : '无法转换'}`);
201
+ }
202
+ }
203
+ if (numbers.system !== null && numbers.system < 0) { diagnostics.negativeSystemRows++; issues.push('系统库存为负'); }
204
+ if (numbers.counted !== null && numbers.counted < 0) { diagnostics.negativeCountedRows++; issues.push('盘点库存为负'); }
205
+ if (numbers.systemAmount !== null && numbers.systemAmount < 0) { diagnostics.negativeSystemAmountRows++; issues.push('系统金额为负'); }
206
+ const supplementRequested = text(get('是否发起补录')), supplementStatus = text(get('补录单数据状态'));
207
+ if (['审批中', '审批不通过'].includes(supplementStatus) || supplementRequested === '是' && !supplementStatus) {
208
+ diagnostics.supplementReviewRows++;
209
+ issues.push(supplementStatus ? `补录${supplementStatus}` : '补录状态缺失');
210
+ }
211
+ if (inventoryGroupKey) {
212
+ let organizations = groupOrganizations.get(inventoryGroupKey);
213
+ if (!organizations) { organizations = new Map(); groupOrganizations.set(inventoryGroupKey, organizations); }
214
+ if (!organizations.has(org.sourceOrgPath)) organizations.set(org.sourceOrgPath, { ...org, sourceRefs: [] });
215
+ organizations.get(org.sourceOrgPath).sourceRefs.push(sourceRef);
216
+ if (!submittedAt) {
217
+ let uncertainty = uncertain.get(inventoryGroupKey);
218
+ if (!uncertainty) {
219
+ uncertainty = { inventoryGroupKey, dealerCode, productName, sourceRefs: [], reason: 'invalid-date', organizations: [] };
220
+ uncertain.set(inventoryGroupKey, uncertainty);
221
+ }
222
+ uncertainty.sourceRefs.push(sourceRef);
223
+ }
224
+ }
225
+ if (missingCode || missingProduct) {
226
+ diagnostics.missingIdentityRows++;
227
+ diagnostics.missingIdentity.push({ ...sourceRef, missingDealerCode: missingCode, missingProductName: missingProduct });
228
+ continue;
229
+ }
230
+ if (!submittedAt) continue;
231
+ const signedVariance = difference(numbers.counted, numbers.system);
232
+ const record = {
233
+ sourceRef, ...org, date: submittedAt.slice(0, 10), submittedAt,
234
+ dealerCode, dealerName: rawText(get('经销商名称')), dealerType: text(get('经销商类型')),
235
+ productCode: '', productName, brand: null, category: null,
236
+ ...numbers, countAmount: null, stockAmount: null, signedVariance,
237
+ absoluteVariance: signedVariance === null ? null : Math.abs(signedVariance),
238
+ varianceFlag: text(get('是否存在盘点偏差')), safety: '', stocktakeCode: rawText(get('盘点编码')),
239
+ inventoryGroupKey, inventoryConflict: 0, inventoryDateUncertain: 0,
240
+ supplementRequested, supplementStatus, inventoryIssues: issues.join(';'),
241
+ };
242
+ all.push(record);
243
+ addTo(groups, inventoryGroupKey, record);
244
+ addTo(byTime, JSON.stringify([inventoryGroupKey, submittedAt]), sourceRef);
245
+ if (record.stocktakeCode.trim()) addTo(byStocktake, JSON.stringify([inventoryGroupKey, record.stocktakeCode]), sourceRef);
246
+ }
247
+ for (const [kind, map, rowCount, groupCount] of [
248
+ ['exact', exact, 'exactDuplicateRows', 'exactDuplicateGroups'],
249
+ ['same-time', byTime, 'sameTimeDuplicateRows', 'sameTimeDuplicateGroups'],
250
+ ['same-stocktake', byStocktake, 'sameStocktakeDuplicateRows', 'sameStocktakeDuplicateGroups'],
251
+ ]) {
252
+ for (const refs of map.values()) if (refs.length > 1) {
253
+ diagnostics[rowCount] += refs.length;
254
+ diagnostics[groupCount]++;
255
+ diagnostics.duplicateGroups.push({ kind, sourceRefs: refs });
256
+ }
257
+ }
258
+ const appendIssue = (record, issue) => { record.inventoryIssues = [record.inventoryIssues, issue].filter(Boolean).join(';'); };
259
+ const records = [], latestRecords = [];
260
+ for (const [key, observations] of groups) {
261
+ addPreviousComparison(observations, uncertain.has(key));
262
+ const organizations = groupOrganizations.get(key);
263
+ if (organizations.size > 1) {
264
+ diagnostics.organizationChangedGroups++;
265
+ diagnostics.organizationChanges.push({ inventoryGroupKey: key, organizations: [...organizations.values()] });
266
+ }
267
+ const months = new Map();
268
+ let latestTime = null;
269
+ for (const record of observations) {
270
+ if (organizations.size > 1) appendIssue(record, '历史组织路径变化');
271
+ if (uncertain.has(key)) { record.inventoryDateUncertain = 1; appendIssue(record, '组内日期无效,最新状态待核实'); }
272
+ if (!latestTime || record.submittedAt > latestTime) latestTime = record.submittedAt;
273
+ const month = record.date.slice(0, 7), candidates = months.get(month);
274
+ if (!candidates || record.submittedAt > candidates[0].submittedAt) months.set(month, [record]);
275
+ else if (record.submittedAt === candidates[0].submittedAt) candidates.push(record);
276
+ }
277
+ const selected = new Set();
278
+ for (const candidates of months.values()) {
279
+ if (candidates.length > 1) for (const record of candidates) { record.inventoryConflict = 1; appendIssue(record, '同组最新时间并列'); }
280
+ for (const record of candidates) { records.push(record); selected.add(record); }
281
+ }
282
+ const globalCandidates = observations.filter(record => record.submittedAt === latestTime);
283
+ latestRecords.push(...globalCandidates);
284
+ if (globalCandidates.length > 1) { diagnostics.latestTieGroups++; diagnostics.latestTieRows += globalCandidates.length; }
285
+ for (const record of observations) if (!selected.has(record)) diagnostics.compressedRows.push(record.sourceRef);
286
+ }
287
+ const uncertaintyGroups = [...uncertain.values()].map(group => ({
288
+ ...group,
289
+ organizations: [...groupOrganizations.get(group.inventoryGroupKey).values()].map(({ sourceRefs, ...org }) => org),
290
+ }));
291
+ diagnostics.invalidDateGroupKeys = [...uncertain.keys()];
292
+ diagnostics.validObservationRows = all.length;
293
+ diagnostics.groupCount = groupOrganizations.size;
294
+ diagnostics.latestRows = latestRecords.length;
295
+ diagnostics.monthEndRows = records.length;
296
+ diagnostics.historyCompressedRows = all.length - records.length;
297
+ records.sort(compareRecords);
298
+ latestRecords.sort((left, right) => left.inventoryGroupKey.localeCompare(right.inventoryGroupKey) || left.sourceRef.row - right.sourceRef.row);
299
+ const warnings = [];
300
+ if (diagnostics.missingIdentityRows) warnings.push(`${diagnostics.missingIdentityRows} 行缺少分组身份,未进入库存候选。`);
301
+ if (diagnostics.invalidDates) warnings.push(`${diagnostics.invalidDates} 行提交时间无效;相关组的最新库存状态待核实。`);
302
+ if (diagnostics.invalidNumbers) warnings.push(`${diagnostics.invalidNumbers} 个数字无法转换,保留为缺失,不回填旧值。`);
303
+ if (diagnostics.sameTimeDuplicateRows) warnings.push(`${diagnostics.sameTimeDuplicateRows} 行属于同组同时间候选;并列候选保留,选择时阻断相关汇总。`);
304
+ if (diagnostics.unparsedOrganizationRows) warnings.push(`${diagnostics.unparsedOrganizationRows} 行完整组织无法可靠拆解,保持独立路径。`);
305
+ if (diagnostics.organizationChangedGroups) warnings.push(`${diagnostics.organizationChangedGroups} 个分组存在历史组织变化,按所选最新记录归属筛选。`);
306
+ return {
307
+ sourceFormat: 'visit-history', records, latestRecords, diagnostics, uncertaintyGroups,
308
+ coverage: {
309
+ start: earliest?.slice(0, 10) ?? null, end: latest?.slice(0, 10) ?? null,
310
+ startSubmittedAt: earliest, endSubmittedAt: latest,
311
+ semantics: 'stocktake-observation-history-not-real-time-stock',
312
+ status: diagnostics.invalidDates ? 'partial' : earliest ? 'observed' : 'missing', productFilter: false,
313
+ },
314
+ warnings,
315
+ };
316
+ }
@@ -0,0 +1,166 @@
1
+ const ORG_FIELDS = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
2
+ const MODULES = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet'];
3
+ const validPath = path => Array.isArray(path) && path.length === 6 && path.every(value => typeof value === 'string' && value.length <= 1000);
4
+ const fullPath = path => validPath(path) && path.every(Boolean);
5
+ const key = path => JSON.stringify(path);
6
+ const isObject = value => value && typeof value === 'object' && !Array.isArray(value);
7
+ const SHA = /^[a-f0-9]{64}$/i;
8
+ const shaMatches = (payload, moduleId, sha) => typeof sha === 'string' && SHA.test(sha) && payload.sources[moduleId]?.sha256 === sha.toLowerCase() && payload.modules[moduleId]?.state !== 'unavailable';
9
+ // v10 业务确认「组织映射生效条件修订(2026-11-26)」: target paths are verified
10
+ // against the current reference boards; their SHAs are recorded, not gates.
11
+ export const REFERENCE_MODULES = ['invoice', 'movement', 'terminal', 'inventory'];
12
+ const KINDS = ['parent-completion', 'confirmed-alias'];
13
+ const LIST_LIMIT = 500;
14
+ // The shape parent completion addresses: upper three levels missing, lower three present.
15
+ const missingParents = path => validPath(path) && path.slice(0, 3).every(value => !value) && path.slice(3).every(Boolean);
16
+ const shaOrNull = sha => typeof sha === 'string' && SHA.test(sha) ? sha.toLowerCase() : null;
17
+
18
+ function reviewedAgainst(decision) {
19
+ // version 2 stores the reviewed versions explicitly; version 1 kept the same
20
+ // facts in referenceSources / sources.*.sourceSha256 (formerly gates).
21
+ const recorded = decision.version === 2 ? decision.reviewedAgainst : null;
22
+ const references = isObject(recorded?.references) ? recorded.references : isObject(decision.referenceSources) ? decision.referenceSources : {};
23
+ const sources = isObject(recorded?.sources) ? recorded.sources : Object.fromEntries(Object.entries(decision.sources).map(([id, source]) => [id, source?.sourceSha256]));
24
+ const clean = values => Object.fromEntries(Object.entries(values).filter(([id]) => MODULES.includes(id)).map(([id, sha]) => [id, shaOrNull(sha)]));
25
+ return { references: clean(references), sources: clean(sources) };
26
+ }
27
+
28
+ /** Apply reviewed, exact from → to organization paths one by one. A mapping
29
+ * applies only when its from path occurs in the mapped board, its full target
30
+ * path occurs in the current reference boards (invoice, movement, terminal,
31
+ * inventory), parent completion is a unique fill of the missing upper levels,
32
+ * and no other target is listed for the same from. Anything else is rejected
33
+ * on its own and reported; the rest still apply. No suffix rewriting or fuzzy
34
+ * matching. Original paths stay on every row for traceability.
35
+ */
36
+ export function applyOrganizationMapping(payload, decision) {
37
+ const report = { version: 2, rules: 'path-verified', status: 'not-configured', contractVersion: null, reviewedAgainst: { references: {}, sources: {} }, actualSources: { references: {}, sources: {} }, appliedSources: {}, modules: {}, errors: [] };
38
+ const referencePaths = new Set();
39
+ for (const id of MODULES) for (const row of payload.modules[id]?.records || []) row.originalOrgPath ??= [...row.orgPath];
40
+ for (const id of REFERENCE_MODULES) {
41
+ if (payload.modules[id]?.state === 'unavailable') continue;
42
+ if (payload.sources[id]?.sha256) report.actualSources.references[id] = payload.sources[id].sha256;
43
+ for (const row of payload.modules[id]?.records || []) if (fullPath(row.originalOrgPath)) referencePaths.add(key(row.originalOrgPath));
44
+ }
45
+ const pendingFor = (id, applied) => {
46
+ const counts = new Map();
47
+ for (const row of payload.modules[id]?.records || []) { const from = key(row.originalOrgPath); if (!applied.has(from) && missingParents(row.originalOrgPath)) counts.set(from, (counts.get(from) || 0) + 1); }
48
+ const all = [...counts].map(([path, rows]) => ({ path: JSON.parse(path), rows })).sort((a, b) => b.rows - a.rows);
49
+ return { pendingPathCount: all.length, pendingRows: all.reduce((sum, item) => sum + item.rows, 0), pendingPaths: all.slice(0, LIST_LIMIT) };
50
+ };
51
+ const finish = () => {
52
+ // Paths still missing their parents are never silent, configured or not.
53
+ for (const id of MODULES) if (!report.modules[id]) { const pending = pendingFor(id, new Set()); if (pending.pendingPathCount) report.modules[id] = { configured: false, ...pending, rejected: [], rejectedCount: 0, status: 'partial' }; }
54
+ if (report.status !== 'invalid' && Object.values(report.modules).some(detail => detail.rejectedCount || detail.pendingPathCount)) report.status = 'partial';
55
+ return report;
56
+ };
57
+ if (!decision) return finish();
58
+ if (!isObject(decision) || ![1, 2].includes(decision.version) || !isObject(decision.sources)) {
59
+ report.status = 'invalid'; report.errors.push('组织映射合同格式不受支持。'); return finish();
60
+ }
61
+ report.contractVersion = decision.version;
62
+ report.reviewedAgainst = reviewedAgainst(decision);
63
+ report.status = 'applied';
64
+ const referenceList = [...referencePaths].map(path => JSON.parse(path));
65
+ for (const [id, source] of Object.entries(decision.sources)) {
66
+ if (!MODULES.includes(id)) { report.errors.push(`组织映射含未知板块 ${String(id).slice(0, 40)},已忽略。`); continue; }
67
+ if (payload.sources[id]?.sha256) report.actualSources.sources[id] = payload.sources[id].sha256;
68
+ const detail = { configured: true, mappings: 0, appliedPaths: 0, appliedRows: 0, parentCompletionPaths: 0, parentCompletionRows: 0, aliasPaths: 0, aliasRows: 0, notInSourceMappings: 0, rejected: [], rejectedCount: 0, status: 'applied' };
69
+ report.modules[id] = detail;
70
+ const records = payload.modules[id]?.records || [];
71
+ const present = new Map(); for (const row of records) { const from = key(row.originalOrgPath); present.set(from, (present.get(from) || 0) + 1); }
72
+ const rejectedFroms = new Set();
73
+ const reject = (mapping, reason) => {
74
+ const from = validPath(mapping?.from) ? mapping.from : null;
75
+ if (from) rejectedFroms.add(key(from));
76
+ detail.rejectedCount++;
77
+ if (detail.rejected.length < LIST_LIMIT) detail.rejected.push({ from, to: validPath(mapping?.to) ? mapping.to : null, kind: KINDS.includes(mapping?.kind) ? mapping.kind : null, reason, rows: from ? present.get(key(from)) || 0 : 0 });
78
+ };
79
+ const mappings = Array.isArray(source?.mappings) ? source.mappings : null;
80
+ if (!mappings) { reject(null, 'malformed'); }
81
+ // Group by from first: one from with two different targets rejects all of them (d).
82
+ const byFrom = new Map();
83
+ for (const mapping of mappings || []) {
84
+ detail.mappings++;
85
+ if (!validPath(mapping?.from) || !fullPath(mapping?.to) || !KINDS.includes(mapping.kind)
86
+ || (mapping.kind === 'parent-completion' && (mapping.from.slice(3).some((value, i) => value !== mapping.to[i + 3]) || mapping.from.slice(0, 3).some((value, i) => value && value !== mapping.to[i])))) { reject(mapping, 'malformed'); continue; }
87
+ const from = key(mapping.from), group = byFrom.get(from) ?? new Map();
88
+ group.set(key(mapping.to) + mapping.kind, mapping); byFrom.set(from, group);
89
+ }
90
+ const accepted = new Map();
91
+ for (const [from, group] of byFrom) {
92
+ const list = [...group.values()];
93
+ if (new Set(list.map(mapping => key(mapping.to))).size !== 1 || list.length !== 1) { for (const mapping of list) reject(mapping, 'ambiguous'); continue; }
94
+ const [mapping] = list;
95
+ if (!present.has(from)) { detail.notInSourceMappings++; continue; } // (a) nothing to apply in this version
96
+ if (!referencePaths.has(key(mapping.to))) { reject(mapping, 'target-missing'); continue; } // (b)
97
+ if (mapping.kind === 'parent-completion') { // (c) unique among current reference paths
98
+ let matches = 0;
99
+ for (const candidate of referenceList) if (mapping.from.every((value, index) => !value || value === candidate[index])) matches++;
100
+ if (matches !== 1) { reject(mapping, 'ambiguous'); continue; }
101
+ }
102
+ accepted.set(from, mapping);
103
+ }
104
+ const appliedPaths = new Map();
105
+ for (const row of records) {
106
+ const from = key(row.originalOrgPath), mapping = accepted.get(from);
107
+ if (!mapping) continue;
108
+ row.orgPath = [...mapping.to]; row.org = Object.fromEntries(ORG_FIELDS.map((field, index) => [field, row.orgPath[index]])); row.orgKey = key(row.orgPath);
109
+ row.organizationMapping = { version: 2, kind: mapping.kind, status: 'applied' };
110
+ detail.appliedRows++; appliedPaths.set(from, mapping.kind);
111
+ if (mapping.kind === 'parent-completion') detail.parentCompletionRows++; else detail.aliasRows++;
112
+ }
113
+ detail.appliedPaths = appliedPaths.size;
114
+ detail.parentCompletionPaths = [...appliedPaths.values()].filter(kind => kind === 'parent-completion').length;
115
+ detail.aliasPaths = detail.appliedPaths - detail.parentCompletionPaths;
116
+ // Rows of a rejected mapping are listed once, under the rejection.
117
+ Object.assign(detail, pendingFor(id, new Set([...appliedPaths.keys(), ...rejectedFroms])));
118
+ if (detail.rejectedCount || detail.pendingPathCount) detail.status = 'partial';
119
+ if (detail.appliedRows && payload.sources[id]?.sha256) report.appliedSources[id] = payload.sources[id].sha256;
120
+ }
121
+ return finish();
122
+ }
123
+
124
+ const SUMMARY_ITEMS = 100;
125
+ /** Compact copy of the mapping report for the generation record (state.json):
126
+ * counts per board plus the first rejected / pending paths for the 查看 list. */
127
+ export function summarizeOrganizationMapping(report) {
128
+ if (!isObject(report)) return null;
129
+ const modules = {}, items = [];
130
+ for (const [id, detail] of Object.entries(report.modules || {})) {
131
+ modules[id] = Object.fromEntries(['appliedPaths', 'appliedRows', 'parentCompletionPaths', 'parentCompletionRows', 'aliasPaths', 'aliasRows', 'rejectedCount', 'pendingPathCount', 'pendingRows', 'notInSourceMappings'].map(name => [name, Number.isSafeInteger(detail[name]) ? detail[name] : 0]));
132
+ for (const item of detail.rejected || []) items.push({ moduleId: id, path: item.from, rows: item.rows || 0, reason: item.reason });
133
+ for (const item of detail.pendingPaths || []) items.push({ moduleId: id, path: item.path, rows: item.rows, reason: 'pending' });
134
+ }
135
+ return { version: 2, status: report.status, contractVersion: report.contractVersion ?? null, errors: (report.errors || []).slice(0, 5), modules, items: items.slice(0, SUMMARY_ITEMS), itemCount: items.length };
136
+ }
137
+
138
+ const RULES = {
139
+ terminalIdentity: { status: 'confirmed', dependencies: ['terminal', 'movement'] },
140
+ crossTableMetrics: { status: 'confirmed', dependencies: ['invoice', 'movement', 'opening', 'inventory'] },
141
+ banquetOpeningSubset: { status: 'not-guaranteed', dependencies: ['banquet', 'opening'] },
142
+ };
143
+ /** Make source bindings explicit in the exported decision contract. A source
144
+ * change disables its dependent rule even when an older decision file remains.
145
+ */
146
+ export function buildDecisionContract(payload, decisions, mappingReport) {
147
+ const contract = {
148
+ version: 1, decisionId: typeof decisions?.decisionId === 'string' ? decisions.decisionId : null,
149
+ confirmedAt: typeof decisions?.confirmedAt === 'string' ? decisions.confirmedAt : null,
150
+ timeZone: typeof decisions?.timeZone === 'string' ? decisions.timeZone : null,
151
+ // version 2: path-verified rules; status is the mapping report's own (applied / partial / invalid / not-configured).
152
+ organizationMapping: { status: ['applied', 'partial', 'invalid', 'not-configured'].includes(mappingReport.status) ? mappingReport.status : 'invalid', version: 2, appliedSources: mappingReport.appliedSources || {} },
153
+ agreementFulfillment: { status: 'pending' }, banquetReward: { status: 'pending' }, inventoryValuationBasis: { status: 'pending' },
154
+ };
155
+ for (const [name, rule] of Object.entries(RULES)) {
156
+ const configured = decisions?.businessRules?.[name];
157
+ // Visit inventory has no amount/product relation. Its disabled estimate must
158
+ // not invalidate unchanged invoice/movement/opening source-bound ratios.
159
+ const dependencies = name === 'crossTableMetrics' && payload.modules.inventory.inventoryMode === 'visit-history'
160
+ ? rule.dependencies.filter(id => id !== 'inventory') : rule.dependencies;
161
+ const valid = configured?.status === rule.status && isObject(configured.sources) && dependencies.every(id => shaMatches(payload, id, configured.sources[id]));
162
+ contract[name] = { status: valid ? rule.status : 'pending', sourceMatches: Object.fromEntries(dependencies.map(id => [id, shaMatches(payload, id, configured?.sources?.[id])])), sources: valid ? Object.fromEntries(dependencies.map(id => [id, configured.sources[id].toLowerCase()])) : {} };
163
+ if (name === 'terminalIdentity') contract[name].key = 'original-code';
164
+ }
165
+ return contract;
166
+ }