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.
- package/README.md +35 -2
- package/assets/theater-board.svg +1 -0
- package/backend/incremental/flow.mjs +492 -0
- package/backend/incremental/jobs.mjs +58 -0
- package/backend/incremental/xlsx-rows.mjs +145 -0
- package/backend/job-worker.mjs +22 -0
- package/backend/modules/banquet/index.mjs +46 -0
- package/backend/modules/inventory/index.mjs +45 -0
- package/backend/modules/inventory/legacy-fields.mjs +83 -0
- package/backend/modules/invoice/index.mjs +72 -0
- package/backend/modules/movement/index.mjs +68 -0
- package/backend/modules/opening/index.mjs +48 -0
- package/backend/modules/target/index.mjs +45 -0
- package/backend/modules/terminal/index.mjs +114 -0
- package/backend/modules.mjs +12 -0
- package/backend/public/admin.css +192 -0
- package/backend/public/admin.js +713 -0
- package/backend/public/board.css +43 -0
- package/backend/public/board.html +47 -0
- package/backend/public/board.js +96 -0
- package/backend/public/index.html +110 -0
- package/backend/public/review.css +5 -0
- package/backend/public/review.js +452 -0
- package/backend/real-data/generate-dashboard.mjs +135 -0
- package/backend/real-data/inventory-history.mjs +316 -0
- package/backend/real-data/organization-mapping.mjs +102 -0
- package/backend/real-data/source-payload.mjs +459 -0
- package/backend/real-data/terminal-components.mjs +280 -0
- package/backend/real-data/terminal-structure.css +105 -0
- package/backend/real-data/terminal-structure.mjs +276 -0
- package/backend/real-data/v10-components.mjs +112 -0
- package/backend/real-data/v10-details.css +18 -0
- package/backend/real-data/v10-details.mjs +251 -0
- package/backend/real-data/v10-layout.css +27 -0
- package/backend/real-data/v10-model.mjs +521 -0
- package/backend/real-data/v10-overview-data.mjs +248 -0
- package/backend/real-data/v10-overview.css +264 -0
- package/backend/real-data/v10-overview.mjs +263 -0
- package/backend/real-data/v10-presentation.mjs +342 -0
- package/backend/real-data/v10-shell.html +1097 -0
- package/backend/real-data/v10-template.mjs +351 -0
- package/backend/recognition/fingerprint.mjs +32 -0
- package/backend/recognition/headers.mjs +2 -0
- package/backend/recognition/module-definition.mjs +4 -0
- package/backend/recognition/result.mjs +29 -0
- package/backend/recognition/upload-limits.mjs +14 -0
- package/backend/review-engine.mjs +364 -0
- package/backend/review-service.mjs +182 -0
- package/backend/server.mjs +545 -0
- package/backend/store.mjs +68 -0
- package/backend/target-template.mjs +47 -0
- package/backend/validate-workbook.mjs +251 -0
- package/backend/web-sync/README.md +37 -0
- package/backend/web-sync/client.mjs +63 -0
- package/backend/web-sync/exporter.mjs +260 -0
- package/backend/web-sync/local.html +34 -0
- package/backend/web-sync/server.mjs +147 -0
- package/build-manifest.json +79 -0
- package/client.js +24 -0
- package/cordis.patch.yml +3 -0
- package/index.js +117 -0
- package/lib/dist-manifest.mjs +19 -0
- package/lib/market-index.mjs +56 -0
- package/lib/package-audit.mjs +34 -0
- package/lib/settings.mjs +71 -0
- package/lib/tool-definitions.mjs +56 -0
- package/lib/tools.mjs +255 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- 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,102 @@
|
|
|
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 shaMatches = (payload, moduleId, sha) => typeof sha === 'string' && /^[a-f0-9]{64}$/i.test(sha) && payload.sources[moduleId]?.sha256 === sha.toLowerCase() && payload.modules[moduleId]?.state !== 'unavailable';
|
|
8
|
+
|
|
9
|
+
/** Apply only enumerated, source-bound mappings. No suffix rewriting or fuzzy
|
|
10
|
+
* organization matching is performed here. All original paths stay available
|
|
11
|
+
* internally so a changed grouping can be traced back to the uploaded source.
|
|
12
|
+
*/
|
|
13
|
+
export function applyOrganizationMapping(payload, decision) {
|
|
14
|
+
const report = { version: 1, status: 'not-configured', appliedSources: {}, referenceSourceMatches: {}, modules: {}, errors: [] };
|
|
15
|
+
const observedTargets = new Set();
|
|
16
|
+
for (const id of MODULES) for (const row of payload.modules[id].records) {
|
|
17
|
+
row.originalOrgPath ??= [...row.orgPath];
|
|
18
|
+
if (fullPath(row.orgPath)) observedTargets.add(key(row.orgPath));
|
|
19
|
+
}
|
|
20
|
+
if (!decision) return report;
|
|
21
|
+
if (decision.version !== 1 || !isObject(decision.sources) || !isObject(decision.referenceSources)) {
|
|
22
|
+
report.status = 'invalid'; report.errors.push('组织映射合同格式不受支持。'); return report;
|
|
23
|
+
}
|
|
24
|
+
const references = Object.entries(decision.referenceSources);
|
|
25
|
+
report.referenceSourceMatches = Object.fromEntries(references.map(([id, sha]) => [id, shaMatches(payload, id, sha)]));
|
|
26
|
+
if (!references.length || references.some(([id, sha]) => !MODULES.includes(id) || !shaMatches(payload, id, sha))) {
|
|
27
|
+
report.status = 'stale'; report.errors.push('组织映射参考来源 SHA 已变化,未应用旧映射。'); return report;
|
|
28
|
+
}
|
|
29
|
+
report.status = 'confirmed';
|
|
30
|
+
for (const [id, source] of Object.entries(decision.sources)) {
|
|
31
|
+
if (!MODULES.includes(id)) { report.status = 'partial'; report.errors.push('组织映射含未知板块,已忽略。'); continue; }
|
|
32
|
+
const detail = { sourceShaMatches: isObject(source) && shaMatches(payload, id, source.sourceSha256), appliedRows: 0, appliedPaths: 0, parentCompletionRows: 0, aliasRows: 0, unmatchedIncompletePaths: [], ambiguousPaths: [], rejectedMappings: 0, status: 'confirmed' };
|
|
33
|
+
report.modules[id] = detail;
|
|
34
|
+
if (!MODULES.includes(id) || !isObject(source) || !shaMatches(payload, id, source.sourceSha256) || !Array.isArray(source.mappings)) {
|
|
35
|
+
detail.status = 'stale'; report.status = 'partial'; continue;
|
|
36
|
+
}
|
|
37
|
+
const candidates = new Map(), invalidKeys = new Set();
|
|
38
|
+
for (const mapping of source.mappings) {
|
|
39
|
+
const from = validPath(mapping?.from) ? key(mapping.from) : null;
|
|
40
|
+
if (from === null || !fullPath(mapping.to) || !['parent-completion', 'confirmed-alias'].includes(mapping.kind) || !observedTargets.has(key(mapping.to))) {
|
|
41
|
+
detail.rejectedMappings++; if (from !== null) invalidKeys.add(from); continue;
|
|
42
|
+
}
|
|
43
|
+
// Parent completion may fill only missing parents; explicit aliases may
|
|
44
|
+
// change names, but only through the exact reviewed from/to pair.
|
|
45
|
+
if (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]))) {
|
|
46
|
+
detail.rejectedMappings++; invalidKeys.add(from); continue;
|
|
47
|
+
}
|
|
48
|
+
if (mapping.kind === 'parent-completion') {
|
|
49
|
+
const matches = [...observedTargets].map(path => JSON.parse(path)).filter(path => mapping.from.every((value, index) => !value || value === path[index]));
|
|
50
|
+
if (matches.length !== 1) { detail.rejectedMappings++; invalidKeys.add(from); detail.ambiguousPaths.push(mapping.from); continue; }
|
|
51
|
+
}
|
|
52
|
+
const targets = candidates.get(from) ?? new Map();
|
|
53
|
+
targets.set(key(mapping.to), mapping); candidates.set(from, targets);
|
|
54
|
+
}
|
|
55
|
+
for (const [from, targets] of candidates) if (targets.size !== 1) { invalidKeys.add(from); detail.ambiguousPaths.push(JSON.parse(from)); }
|
|
56
|
+
detail.ambiguousPaths = [...new Map(detail.ambiguousPaths.map(path => [key(path), path])).values()];
|
|
57
|
+
const applied = new Set(), incomplete = new Map();
|
|
58
|
+
for (const row of payload.modules[id].records) {
|
|
59
|
+
const from = key(row.originalOrgPath), targets = candidates.get(from);
|
|
60
|
+
const mapping = !invalidKeys.has(from) && targets?.size === 1 ? [...targets.values()][0] : null;
|
|
61
|
+
if (mapping) {
|
|
62
|
+
row.orgPath = [...mapping.to]; row.org = Object.fromEntries(ORG_FIELDS.map((field, index) => [field, row.orgPath[index]])); row.orgKey = key(row.orgPath);
|
|
63
|
+
row.organizationMapping = { version: 1, kind: mapping.kind, status: 'applied' };
|
|
64
|
+
detail.appliedRows++; applied.add(from);
|
|
65
|
+
if (mapping.kind === 'parent-completion') detail.parentCompletionRows++; else detail.aliasRows++;
|
|
66
|
+
} else if (!fullPath(row.orgPath)) incomplete.set(from, row.orgPath);
|
|
67
|
+
}
|
|
68
|
+
detail.appliedPaths = applied.size; detail.unmatchedIncompletePaths = [...incomplete.values()];
|
|
69
|
+
if (detail.rejectedMappings || detail.ambiguousPaths.length) { detail.status = 'partial'; report.status = 'partial'; }
|
|
70
|
+
report.appliedSources[id] = source.sourceSha256.toLowerCase();
|
|
71
|
+
}
|
|
72
|
+
return report;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const RULES = {
|
|
76
|
+
terminalIdentity: { status: 'confirmed', dependencies: ['terminal', 'movement'] },
|
|
77
|
+
crossTableMetrics: { status: 'confirmed', dependencies: ['invoice', 'movement', 'opening', 'inventory'] },
|
|
78
|
+
banquetOpeningSubset: { status: 'not-guaranteed', dependencies: ['banquet', 'opening'] },
|
|
79
|
+
};
|
|
80
|
+
/** Make source bindings explicit in the exported decision contract. A source
|
|
81
|
+
* change disables its dependent rule even when an older decision file remains.
|
|
82
|
+
*/
|
|
83
|
+
export function buildDecisionContract(payload, decisions, mappingReport) {
|
|
84
|
+
const contract = {
|
|
85
|
+
version: 1, decisionId: typeof decisions?.decisionId === 'string' ? decisions.decisionId : null,
|
|
86
|
+
confirmedAt: typeof decisions?.confirmedAt === 'string' ? decisions.confirmedAt : null,
|
|
87
|
+
timeZone: typeof decisions?.timeZone === 'string' ? decisions.timeZone : null,
|
|
88
|
+
organizationMapping: { status: mappingReport.status === 'confirmed' ? 'confirmed' : 'pending', version: 1, appliedSources: mappingReport.appliedSources },
|
|
89
|
+
agreementFulfillment: { status: 'pending' }, banquetReward: { status: 'pending' }, inventoryValuationBasis: { status: 'pending' },
|
|
90
|
+
};
|
|
91
|
+
for (const [name, rule] of Object.entries(RULES)) {
|
|
92
|
+
const configured = decisions?.businessRules?.[name];
|
|
93
|
+
// Visit inventory has no amount/product relation. Its disabled estimate must
|
|
94
|
+
// not invalidate unchanged invoice/movement/opening source-bound ratios.
|
|
95
|
+
const dependencies = name === 'crossTableMetrics' && payload.modules.inventory.inventoryMode === 'visit-history'
|
|
96
|
+
? rule.dependencies.filter(id => id !== 'inventory') : rule.dependencies;
|
|
97
|
+
const valid = configured?.status === rule.status && isObject(configured.sources) && dependencies.every(id => shaMatches(payload, id, configured.sources[id]));
|
|
98
|
+
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()])) : {} };
|
|
99
|
+
if (name === 'terminalIdentity') contract[name].key = 'original-code';
|
|
100
|
+
}
|
|
101
|
+
return contract;
|
|
102
|
+
}
|