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.
- 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 +220 -0
- package/backend/public/admin.js +772 -0
- package/backend/public/board.css +70 -0
- package/backend/public/board.html +50 -0
- package/backend/public/board.js +153 -0
- package/backend/public/index.html +113 -0
- package/backend/public/org-mapping.js +49 -0
- package/backend/public/review.css +5 -0
- package/backend/public/review.js +452 -0
- package/backend/real-data/generate-dashboard.mjs +137 -0
- package/backend/real-data/inventory-history.mjs +316 -0
- package/backend/real-data/organization-mapping.mjs +166 -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 +568 -0
- package/backend/real-data/v10-overview-data.mjs +253 -0
- package/backend/real-data/v10-overview.css +370 -0
- package/backend/real-data/v10-overview.mjs +340 -0
- package/backend/real-data/v10-presentation.mjs +354 -0
- package/backend/real-data/v10-shell.html +1097 -0
- package/backend/real-data/v10-template.mjs +353 -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 +569 -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 +80 -0
- package/client.js +54 -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,353 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { createV10Model } from './v10-model.mjs';
|
|
4
|
+
import { createV10Components } from './v10-components.mjs';
|
|
5
|
+
import { buildTerminalStructure } from './terminal-structure.mjs';
|
|
6
|
+
import { createTerminalComponents } from './terminal-components.mjs';
|
|
7
|
+
import { createV10Presentation } from './v10-presentation.mjs';
|
|
8
|
+
import { createV10Details } from './v10-details.mjs';
|
|
9
|
+
import { createV10OverviewData } from './v10-overview-data.mjs';
|
|
10
|
+
import { createV10Overview } from './v10-overview.mjs';
|
|
11
|
+
|
|
12
|
+
export { createV10Model } from './v10-model.mjs';
|
|
13
|
+
export const V10_TEMPLATE_SHA256 = 'b58e609411d0b9ab2d77d7079ea580e8210d11946999a8c11cea1fc34bf9b886';
|
|
14
|
+
export const V10_SCRIPT_SHA256 = 'd11a689940d80a4010c5f45786ac2da7d3106cb8309216b4df2d55c8dac4599c';
|
|
15
|
+
export const V10_RENDERER_VERSION = 20;
|
|
16
|
+
export const V10_SHELL_SHA256 = 'd5118e6e2ec447cc22992c348e18ae719bfbda959a2b694352843c120522a5f1';
|
|
17
|
+
const APPLICATION_MARKER = '/*__V10_APPLICATION__*/';
|
|
18
|
+
const IDS = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet'];
|
|
19
|
+
const ORG = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
|
|
20
|
+
const NUMERIC = {
|
|
21
|
+
invoice: ['amount'], movement: ['amount', 'bottles', 'boxes', 'cases'], opening: ['bottles', 'amount'],
|
|
22
|
+
terminal: [], inventory: ['counted', 'system', 'countAmount', 'systemAmount', 'absoluteVariance', 'signedVariance', 'sourceVariance'], banquet: ['events', 'bottles'],
|
|
23
|
+
};
|
|
24
|
+
const TEXT = { invoice: ['brand', 'category', 'dealerCode', 'dealerName', 'productCode', 'productName'], movement: ['brand', 'category', 'quantityUnit', 'terminalCode', 'terminalName', 'channel', 'movementType', 'productCode', 'productName', 'variety', 'dealerCode', 'dealerName'], opening: ['city'], terminal: ['terminalCode', 'terminalName', 'star', 'agreementId', 'type', 'series', 'signLevel', 'signVariety'], inventory: ['brand', 'category', 'safety', 'dealerCode', 'dealerName', 'productCode', 'productName'], banquet: [] };
|
|
25
|
+
const OPTIONAL_DISPLAY_TEXT = new Set(['productCode', 'productName', 'variety', 'terminalName', 'channel', 'movementType', 'agreementId', 'type', 'series', 'signLevel', 'signVariety']);
|
|
26
|
+
const hash = text => createHash('sha256').update(text).digest('hex');
|
|
27
|
+
const isObject = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
28
|
+
const fail = message => { throw new Error(`v10 看板校验失败:${message}`); };
|
|
29
|
+
const string = (value, name, nullable = false) => {
|
|
30
|
+
if (nullable && value === null) return null;
|
|
31
|
+
if (typeof value !== 'string' || value.length > 1000) fail(`${name} 必须是有限长度字符串`);
|
|
32
|
+
return value;
|
|
33
|
+
};
|
|
34
|
+
const validDate = value => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(`${value}T00:00:00Z`)) && new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value;
|
|
35
|
+
|
|
36
|
+
/** Project internal records onto only fields required by this offline view.
|
|
37
|
+
* Raw rows, sourceRef, contact details, diagnostic reports and machine paths
|
|
38
|
+
* are intentionally not copied. Missing business values remain null.
|
|
39
|
+
*/
|
|
40
|
+
export function sanitizeV10Payload(input) {
|
|
41
|
+
if (!isObject(input) || input.schemaVersion !== 1 || !['real-preview', 'real'].includes(input.mode)) fail('不支持的数据合同或数据模式');
|
|
42
|
+
if (!isObject(input.modules) || !isObject(input.sources) || !isObject(input.coverage)) fail('缺少 modules / sources / coverage');
|
|
43
|
+
if (typeof input.generatedAt !== 'string' || !Number.isFinite(Date.parse(input.generatedAt))) fail('缺少有效生成时间');
|
|
44
|
+
const result = { schemaVersion: 1, mode: input.mode, generatedAt: input.generatedAt, sources: {}, coverage: {}, modules: {} };
|
|
45
|
+
if (input.decisionContract !== undefined) {
|
|
46
|
+
const contract = input.decisionContract;
|
|
47
|
+
if (!isObject(contract) || contract.version !== 1) fail('不支持的已确认规则合同');
|
|
48
|
+
result.decisionContract = { version: 1 };
|
|
49
|
+
if (contract.decisionId !== undefined && contract.decisionId !== null) result.decisionContract.decisionId = string(contract.decisionId, 'decisionContract.decisionId');
|
|
50
|
+
for (const key of ['organizationMapping', 'terminalIdentity', 'crossTableMetrics', 'banquetOpeningSubset', 'banquetReward', 'inventoryValuationBasis']) {
|
|
51
|
+
const rule = contract[key];
|
|
52
|
+
if (!rule) continue;
|
|
53
|
+
// Organization mapping v2 reports its own path-verified status (v10 业务确认 2026-11-26).
|
|
54
|
+
const statuses = key === 'organizationMapping' ? ['applied', 'partial', 'invalid', 'not-configured', 'confirmed', 'pending'] : ['confirmed', 'pending', 'not-guaranteed'];
|
|
55
|
+
if (!isObject(rule) || !statuses.includes(rule.status)) fail(`规则 ${key} 状态无效`);
|
|
56
|
+
const clean = { status: rule.status };
|
|
57
|
+
for (const field of ['sources', 'appliedSources']) if (rule[field]) {
|
|
58
|
+
if (!isObject(rule[field])) fail(`规则 ${key} 来源绑定无效`);
|
|
59
|
+
clean[field] = Object.fromEntries(Object.entries(rule[field]).map(([id, sha]) => {
|
|
60
|
+
if (!IDS.includes(id) || typeof sha !== 'string' || !/^[a-f0-9]{64}$/i.test(sha)) fail(`规则 ${key} 来源指纹无效`);
|
|
61
|
+
return [id, sha.toLowerCase()];
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
if (key === 'terminalIdentity' && rule.key !== undefined) clean.key = string(rule.key, 'terminalIdentity.key');
|
|
65
|
+
if (key === 'organizationMapping' && rule.version !== undefined) {
|
|
66
|
+
if (!Number.isSafeInteger(rule.version) || rule.version < 1) fail('组织映射版本无效');
|
|
67
|
+
clean.version = rule.version;
|
|
68
|
+
}
|
|
69
|
+
result.decisionContract[key] = clean;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const id of IDS) {
|
|
73
|
+
const module = input.modules[id];
|
|
74
|
+
if (!isObject(module) || !['ready', 'partial', 'unavailable'].includes(module.state) || !Array.isArray(module.records) || !isObject(module.metrics) || !Array.isArray(module.unavailable)) fail(`${id} 模块合同不完整`);
|
|
75
|
+
if (module.state === 'unavailable' && module.records.length) fail(`${id} 不可用模块不能带可展示记录`);
|
|
76
|
+
const source = input.sources[id];
|
|
77
|
+
if (module.state !== 'unavailable' && !source) fail(`${id} 缺少锁定来源`);
|
|
78
|
+
if (source) {
|
|
79
|
+
if (!isObject(source) || typeof source.sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(source.sha256)) fail(`${id} SHA-256 无效`);
|
|
80
|
+
const name = source.originalName === null ? '未提供文件名' : string(source.originalName, `${id}.originalName`);
|
|
81
|
+
result.sources[id] = { uploadId: string(source.uploadId, `${id}.uploadId`), sha256: source.sha256.toLowerCase(), originalName: name.replaceAll('\\', '/').split('/').at(-1) };
|
|
82
|
+
if (!result.sources[id].uploadId) fail(`${id} 上传版本为空`);
|
|
83
|
+
}
|
|
84
|
+
const coverage = input.coverage[id];
|
|
85
|
+
if (module.state !== 'unavailable' && !isObject(coverage)) fail(`${id} 缺少期间说明`);
|
|
86
|
+
if (coverage) {
|
|
87
|
+
for (const key of ['start', 'end']) if (coverage[key] !== null && !validDate(coverage[key])) fail(`${id} 期间 ${key} 无效`);
|
|
88
|
+
if (coverage.start && coverage.end && coverage.start > coverage.end) fail(`${id} 期间倒置`);
|
|
89
|
+
result.coverage[id] = { start: coverage.start, end: coverage.end, semantics: string(coverage.semantics, `${id}.coverage.semantics`, module.state === 'unavailable') };
|
|
90
|
+
}
|
|
91
|
+
const records = module.records.map((row, index) => {
|
|
92
|
+
const where = `${id}[${index}]`;
|
|
93
|
+
if (!isObject(row) || !isObject(row.org) || !Array.isArray(row.orgPath) || row.orgPath.length !== 6) fail(`${where} 缺少完整六级组织路径`);
|
|
94
|
+
const orgPath = row.orgPath.map((value, i) => string(value, `${where}.orgPath[${i}]`));
|
|
95
|
+
const org = Object.fromEntries(ORG.map((key, i) => {
|
|
96
|
+
const value = string(row.org[key], `${where}.org.${key}`);
|
|
97
|
+
if (value !== orgPath[i]) fail(`${where} 组织字段与完整路径不一致`);
|
|
98
|
+
return [key, value];
|
|
99
|
+
}));
|
|
100
|
+
if (row.date !== null && !validDate(row.date)) fail(`${where}.date 无效`);
|
|
101
|
+
if (id === 'banquet' && row.date !== null) fail('宴席必须保持来源固定期间');
|
|
102
|
+
const clean = { org, orgPath, date: row.date };
|
|
103
|
+
for (const key of NUMERIC[id]) {
|
|
104
|
+
if (!(key in row)) fail(`${where}.${key} 缺失,不能静默补零`);
|
|
105
|
+
const value = row[key];
|
|
106
|
+
if (value !== null && (typeof value !== 'number' || !Number.isFinite(value))) fail(`${where}.${key} 必须为有限数或 null`);
|
|
107
|
+
clean[key] = value;
|
|
108
|
+
}
|
|
109
|
+
for (const key of TEXT[id]) clean[key] = string(row[key] ?? ((OPTIONAL_DISPLAY_TEXT.has(key) || id !== 'invoice' && ['dealerCode', 'dealerName'].includes(key)) ? '' : row[key]), `${where}.${key}`, ['brand', 'category'].includes(key));
|
|
110
|
+
if (id === 'inventory' && module.inventoryMode === 'visit-history') {
|
|
111
|
+
for (const key of ['submittedAt', 'inventoryGroupKey', 'sourceOrgPath', 'inventoryIssues', 'supplementRequested', 'supplementStatus', 'stocktakeCode']) clean[key] = string(row[key] ?? '', `${where}.${key}`);
|
|
112
|
+
const prior = row.previousSubmittedAt;
|
|
113
|
+
if (prior !== null && (typeof prior !== 'string' || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(prior)
|
|
114
|
+
|| !validDate(prior.slice(0, 10)) || prior.slice(11, 13) > '23' || prior.slice(14, 16) > '59' || prior.slice(17, 19) > '59'
|
|
115
|
+
|| prior >= row.submittedAt)) fail(`${where}.previousSubmittedAt 必须为空或严格早于本次的有效提交时间`);
|
|
116
|
+
clean.previousSubmittedAt = prior;
|
|
117
|
+
for (const key of ['previousCounted', 'changeFromPrevious']) {
|
|
118
|
+
if (!(key in row) || row[key] !== null && (typeof row[key] !== 'number' || !Number.isFinite(row[key]))) fail(`${where}.${key} 必须为有限数或 null`);
|
|
119
|
+
clean[key] = row[key];
|
|
120
|
+
}
|
|
121
|
+
const statuses = ['comparable', 'no-previous', 'invalid-date', 'current-conflict', 'previous-conflict', 'missing-counted', 'invalid-change'];
|
|
122
|
+
if (!statuses.includes(row.inventoryComparisonStatus)) fail(`${where}.inventoryComparisonStatus 无效`);
|
|
123
|
+
clean.inventoryComparisonStatus = row.inventoryComparisonStatus;
|
|
124
|
+
if (row.inventoryComparisonStatus === 'comparable' && (prior === null || row.previousCounted === null || row.counted === null || row.changeFromPrevious === null || row.inventoryConflict || row.inventoryDateUncertain)) fail(`${where} 可比较状态缺少有效前次或差值,或存在时间冲突`);
|
|
125
|
+
if (row.inventoryComparisonStatus !== 'comparable' && row.changeFromPrevious !== null) fail(`${where} 不可比较记录不能带变化瓶数`);
|
|
126
|
+
for (const key of ['inventoryConflict', 'inventoryDateUncertain']) {
|
|
127
|
+
if (![0, 1].includes(row[key] ?? 0)) fail(`${where}.${key} 必须为 0 或 1`);
|
|
128
|
+
clean[key] = row[key] ?? 0;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return clean;
|
|
132
|
+
});
|
|
133
|
+
// Metrics are recomputed for the selected scope; global totals are never
|
|
134
|
+
// reused as filtered values. Internal pending keys are not user-facing text.
|
|
135
|
+
const gates = Object.fromEntries(Object.entries(module.metrics).filter(([key]) => id !== 'terminal' || !['target', 'stageTarget', 'received', 'receivedAmount', 'achievement', 'movementCoverage'].includes(key)).map(([key, metric]) => {
|
|
136
|
+
if (!isObject(metric) || !['available', 'pending', 'missing'].includes(metric.status)) fail(`${id}.${key} 指标状态无效`);
|
|
137
|
+
return [key, { status: metric.status }];
|
|
138
|
+
}));
|
|
139
|
+
result.modules[id] = { state: module.state, records, metrics: gates, unavailable: [] };
|
|
140
|
+
if (module.reviewPending === true) {
|
|
141
|
+
if (module.state !== 'unavailable' || !source) fail('待确认板块必须保留来源且不输出不完整的记录汇总');
|
|
142
|
+
result.modules[id].reviewPending = true;
|
|
143
|
+
result.modules[id].reviewReason = string(module.reviewReason, `${id}.reviewReason`);
|
|
144
|
+
}
|
|
145
|
+
if (id === 'inventory' && module.inventoryMode === 'visit-history') {
|
|
146
|
+
const clean = result.modules[id];
|
|
147
|
+
clean.inventoryMode = 'visit-history';
|
|
148
|
+
clean.inventoryStats = {};
|
|
149
|
+
for (const key of ['sourceRows', 'compressedRows', 'groupCount', 'missingDealerCodes', 'invalidDates', 'invalidNumbers']) {
|
|
150
|
+
const value = module.inventoryStats?.[key] ?? 0;
|
|
151
|
+
if (!Number.isSafeInteger(value) || value < 0) fail(`inventory.inventoryStats.${key} 无效`);
|
|
152
|
+
clean.inventoryStats[key] = value;
|
|
153
|
+
}
|
|
154
|
+
clean.uncertaintyGroups = (module.uncertaintyGroups || []).map(group => ({
|
|
155
|
+
inventoryGroupKey: string(group.inventoryGroupKey, 'inventory.uncertaintyGroup.key'),
|
|
156
|
+
organizations: (group.organizations || []).map(value => {
|
|
157
|
+
if (!Array.isArray(value.orgPath) || value.orgPath.length !== 6) fail('无效时间组缺少组织路径');
|
|
158
|
+
return { orgPath: value.orgPath.map(part => string(part, 'inventory.uncertaintyGroup.orgPath')) };
|
|
159
|
+
}),
|
|
160
|
+
}));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
const target = input.modules.target;
|
|
164
|
+
if (target !== undefined) {
|
|
165
|
+
if (!isObject(target) || !Array.isArray(target.records) || !['ready', 'partial', 'unavailable'].includes(target.state)) fail('经营目标模块合同不完整');
|
|
166
|
+
const source = input.sources.target, ready = target.state !== 'unavailable' && source;
|
|
167
|
+
if (ready && (!isObject(source) || typeof source.sha256 !== 'string' || !/^[a-f0-9]{64}$/i.test(source.sha256))) fail('经营目标 SHA-256 无效');
|
|
168
|
+
result.targets = { state: ready ? 'ready' : 'unavailable', reason: ready ? null : string(target.reason ?? '未接入有效目标来源', 'target.reason'),
|
|
169
|
+
source: ready ? { uploadId: string(source.uploadId, 'target.uploadId'), sha256: source.sha256.toLowerCase(),
|
|
170
|
+
originalName: (source.originalName === null ? '未提供文件名' : string(source.originalName, 'target.originalName')).replaceAll('\\', '/').split('/').at(-1) } : null,
|
|
171
|
+
records: ready ? target.records.filter(row => isObject(row) && !row.issue).map((row, index) => {
|
|
172
|
+
const where = `target[${index}]`;
|
|
173
|
+
if (typeof row.month !== 'string' || !/^\d{4}-(0[1-9]|1[0-2])$/.test(row.month)) fail(`${where}.month 无效`);
|
|
174
|
+
if (!['invoice', 'movement', 'opening'].includes(row.metric)) fail(`${where}.metric 无效`);
|
|
175
|
+
if (row.value !== null && (typeof row.value !== 'number' || !Number.isFinite(row.value) || row.value < 0)) fail(`${where}.value 必须为非负有限数或 null`);
|
|
176
|
+
if (!isObject(row.org)) fail(`${where} 缺少组织`);
|
|
177
|
+
return { month: row.month, metric: row.metric, value: row.value, region: string(row.org.region ?? '', `${where}.region`), office: string(row.org.office ?? '', `${where}.office`), unit: string(row.org.unit ?? '', `${where}.unit`) };
|
|
178
|
+
}) : [] };
|
|
179
|
+
}
|
|
180
|
+
if (!IDS.some(id => result.modules[id].state !== 'unavailable' && result.modules[id].records.length) && !IDS.some(id => result.modules[id].reviewPending)) fail('零有效来源不能生成真实数据看板');
|
|
181
|
+
return result;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const literal = value => JSON.stringify(value).replaceAll('<', '\\u003c').replaceAll('\u2028', '\\u2028').replaceAll('\u2029', '\\u2029');
|
|
185
|
+
export function packV10Payload(payload) {
|
|
186
|
+
const paths = [], keys = new Map();
|
|
187
|
+
const modules = Object.fromEntries(IDS.map(id => {
|
|
188
|
+
const module = payload.modules[id];
|
|
189
|
+
let records = module.records.map(({ org, orgPath, ...row }) => {
|
|
190
|
+
const key = JSON.stringify(orgPath);
|
|
191
|
+
if (!keys.has(key)) { keys.set(key, paths.length); paths.push(orgPath); }
|
|
192
|
+
return { ...row, orgIndex: keys.get(key) };
|
|
193
|
+
});
|
|
194
|
+
if (id === 'inventory' && module.inventoryMode === 'visit-history' && records.length) {
|
|
195
|
+
const fields = Object.keys(records[0]);
|
|
196
|
+
// Sanitized inventory has a uniform schema. Keep the original form if a
|
|
197
|
+
// future caller supplies varying keys, rather than silently losing fields.
|
|
198
|
+
if (records.every(row => Object.keys(row).length === fields.length && fields.every(field => Object.hasOwn(row, field)))) {
|
|
199
|
+
const columns = fields.map(field => {
|
|
200
|
+
const values = records.map(row => row[field]);
|
|
201
|
+
if (values.every(value => Object.is(value, values[0]))) return { value: values[0] };
|
|
202
|
+
const plain = { values };
|
|
203
|
+
if (values.every(value => value === null || typeof value === 'string')) {
|
|
204
|
+
const dictionary = [], indexes = [], lookup = new Map();
|
|
205
|
+
for (const value of values) {
|
|
206
|
+
if (!lookup.has(value)) { lookup.set(value, dictionary.length); dictionary.push(value); }
|
|
207
|
+
indexes.push(lookup.get(value));
|
|
208
|
+
}
|
|
209
|
+
const encoded = { dictionary, indexes };
|
|
210
|
+
if (JSON.stringify(encoded).length < JSON.stringify(plain).length) return encoded;
|
|
211
|
+
}
|
|
212
|
+
return plain;
|
|
213
|
+
});
|
|
214
|
+
records = { encoding: 'inventory-columns-v1', length: records.length, fields, columns };
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return [id, { ...module, records }];
|
|
218
|
+
}));
|
|
219
|
+
return { ...payload, organizationPaths: paths, modules };
|
|
220
|
+
}
|
|
221
|
+
// Shared objects are restored in memory, so the offline file does not repeat a
|
|
222
|
+
// full six-level organization hundreds of thousands of times. Keep this function
|
|
223
|
+
// self-contained: its source is embedded directly into the offline HTML.
|
|
224
|
+
export function unpackV10Payload(payload) {
|
|
225
|
+
const fields = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
|
|
226
|
+
const orgs = payload.organizationPaths.map(path => Object.fromEntries(fields.map((field, index) => [field, path[index]])));
|
|
227
|
+
const modules = Object.fromEntries(Object.entries(payload.modules).map(([id, module]) => {
|
|
228
|
+
let records = module.records;
|
|
229
|
+
if (id === 'inventory' && module.inventoryMode === 'visit-history' && records.encoding === 'inventory-columns-v1') {
|
|
230
|
+
const packed = records;
|
|
231
|
+
records = Array.from({ length: packed.length }, (_, index) => Object.fromEntries(packed.fields.map((field, columnIndex) => {
|
|
232
|
+
const column = packed.columns[columnIndex];
|
|
233
|
+
const value = Object.prototype.hasOwnProperty.call(column, 'value') ? column.value
|
|
234
|
+
: column.dictionary ? column.dictionary[column.indexes[index]] : column.values[index];
|
|
235
|
+
return [field, value];
|
|
236
|
+
})));
|
|
237
|
+
}
|
|
238
|
+
return [id, { ...module, records: records.map(({ orgIndex, ...row }) => ({ ...row, org: orgs[orgIndex], orgPath: payload.organizationPaths[orgIndex] })) }];
|
|
239
|
+
}));
|
|
240
|
+
const { organizationPaths, ...rest } = payload;
|
|
241
|
+
return { ...rest, modules };
|
|
242
|
+
}
|
|
243
|
+
function once(source, search, replacement) {
|
|
244
|
+
const start = source.indexOf(search);
|
|
245
|
+
if (start < 0 || source.indexOf(search, start + search.length) >= 0) fail(`模板替换边界不唯一:${search.slice(0, 45)}`);
|
|
246
|
+
return source.slice(0, start) + replacement + source.slice(start + search.length);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Remove the original business snapshot and all of its calculation code.
|
|
250
|
+
* This only accepts the exact reviewed private template. The returned shell
|
|
251
|
+
* contains libraries, CSS and the data-independent layout, never source rows.
|
|
252
|
+
*/
|
|
253
|
+
export function extractV10Shell(templateHtml) {
|
|
254
|
+
if (typeof templateHtml !== 'string' || hash(templateHtml) !== V10_TEMPLATE_SHA256) fail('模板 SHA 不在已审查允许列表,拒绝套用旧替换边界');
|
|
255
|
+
const scripts = [...templateHtml.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script\s*>/gi)];
|
|
256
|
+
if (scripts.length !== 1 || !/^<script type="module">/.test(scripts[0][0])) fail('模板脚本结构改变');
|
|
257
|
+
const script = scripts[0][1];
|
|
258
|
+
if (hash(script) !== V10_SCRIPT_SHA256) fail('模板脚本 SHA 不匹配');
|
|
259
|
+
const prefixEnd = 606234, rootStart = 2916206, mountStart = 2929786;
|
|
260
|
+
if (!script.startsWith('const ZQ_RD = ', prefixEnd) || !script.startsWith('function XZ() {', rootStart) || !script.startsWith('h7.createRoot(document.getElementById("root")).render(', mountStart)) fail('已审查模板的应用边界不匹配');
|
|
261
|
+
let root = script.slice(rootStart, mountStart);
|
|
262
|
+
root = once(root, 'Array.from({ length: 10 }, (x, i) => `2026-${pad2(10 - i)}`)', '[...V10.months].reverse()');
|
|
263
|
+
root = once(root, 'children: [b.replace("-", " 年 "), " 月"]', 'children: b === "fixed" ? "来源固定期间" : [b.replace("-", " 年 "), " 月"]');
|
|
264
|
+
for (const name of ['ME', 'h', 'm']) root = once(root, `${name}.map((b) => T.jsx("option", { children: b }, b))`, `${name}.map((b) => T.jsx("option", { value: b, children: V10.label(b) }, b))`);
|
|
265
|
+
root = once(root, 'children: [b.name, T.jsx(Z4, { size: 15 })]', 'children: [V10.label(b.name), T.jsx(Z4, { size: 15 })]');
|
|
266
|
+
root = once(root, 'T.jsx("small", { children: "万元" })', 'T.jsx("small", { children: b.invoice == null ? "" : "万元" })');
|
|
267
|
+
root = once(root, '" 万元",', 'b.movement == null ? "" : " 万元",');
|
|
268
|
+
root = once(root, '"六个板块均为真实数据"', 'V10_PRESENTATION.badge');
|
|
269
|
+
root = once(root, '"六个板块均为真实明细 · 截至 2026-10-26"', 'V10_PRESENTATION.sourceLabel');
|
|
270
|
+
root = once(root, '" DESIGN PREVIEW 01"', 'V10_PRESENTATION.versionLabel');
|
|
271
|
+
root = once(root, '"V 0.1"', '"V 10"');
|
|
272
|
+
const replacement = `<script type="module">${script.slice(0, prefixEnd)}${APPLICATION_MARKER}\n${root}${script.slice(mountStart)}</script>`;
|
|
273
|
+
const shell = templateHtml.slice(0, scripts[0].index) + replacement + templateHtml.slice(scripts[0].index + scripts[0][0].length);
|
|
274
|
+
if (shell.includes('const ZQ_RD = ') || shell.includes('六个板块均为真实明细')) fail('原始快照或旧状态文案残留');
|
|
275
|
+
return shell;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function renderShell(shell, input, { mode, templateSha256 }) {
|
|
279
|
+
const payload = sanitizeV10Payload(input), payloadSha256 = hash(JSON.stringify(payload));
|
|
280
|
+
if (payload.mode !== mode) fail('生成入口与数据模式不一致');
|
|
281
|
+
const presentation = mode === 'real' ? {
|
|
282
|
+
badge: '本机上传 · 真实数据', versionLabel: ' V10 REAL DATA',
|
|
283
|
+
notice: '真实数据看板:使用本次生成时最新校验通过的上传版本;未提供来源和待确认指标明确标示。',
|
|
284
|
+
} : {
|
|
285
|
+
badge: '真实来源 · 隔离预览', versionLabel: ' V10 SOURCE PREVIEW',
|
|
286
|
+
notice: '真实数据接入预览:已锁定本机上传版本;待确认指标不计算;尚未替换正式后台生成链路。',
|
|
287
|
+
};
|
|
288
|
+
presentation.sourceLabel = `来源版本已锁定 · 数据指纹 ${payloadSha256.slice(0, 12)}`;
|
|
289
|
+
const sourceEnds = [...new Set(IDS.filter(id => payload.modules[id].state !== 'unavailable').map(id => payload.coverage[id]?.end))];
|
|
290
|
+
const cutoff = !sourceEnds.some(Boolean) ? '来源截止日期未提供' : sourceEnds.length === 1 && sourceEnds[0] ? `截至 ${sourceEnds[0]}` : `最新至 ${sourceEnds.filter(Boolean).sort().at(-1)} · 各来源截止不同`;
|
|
291
|
+
presentation.badge = `${mode === 'real' ? '真实数据' : '真实来源预览'} · ${cutoff}`;
|
|
292
|
+
const injected = `
|
|
293
|
+
const V10_PAYLOAD=(${unpackV10Payload.toString()})(${literal(packV10Payload(payload))});
|
|
294
|
+
const V10_PRESENTATION=${literal(presentation)};
|
|
295
|
+
const buildTerminalStructure=(${buildTerminalStructure.toString()});
|
|
296
|
+
const createTerminalComponents=(${createTerminalComponents.toString()});
|
|
297
|
+
const createV10Presentation=(${createV10Presentation.toString()});
|
|
298
|
+
const createV10Details=(${createV10Details.toString()});
|
|
299
|
+
const createV10OverviewData=(${createV10OverviewData.toString()});
|
|
300
|
+
const createV10Overview=(${createV10Overview.toString()});
|
|
301
|
+
const V10=(${createV10Model.toString()})(V10_PAYLOAD);
|
|
302
|
+
const pad2=x=>String(x).padStart(2,'0'),Al=V10.organizations,Ur=V10.categories,BRANDS=[...new Set(Ur.map(x=>x.brand))],ME=[...new Set(Al.map(x=>x.region))],N4=V10.defaults,mf=V10.ids;
|
|
303
|
+
const Je=V10.format,Yr=x=>typeof x==='number'&&Number.isFinite(x)?Je(x/10000,2):'无记录',DE=V10.scope,$Z=V10.select;
|
|
304
|
+
const previewIcons={invoice:nx,movement:P7,opening:I7,terminal:$7,inventory:U7,banquet:H7};
|
|
305
|
+
const Pn=Object.fromEntries(mf.map(id=>[id,{title:V10.titles[id],color:V10.colors[id],icon:previewIcons[id]}]));
|
|
306
|
+
const {z4,GZ,VZ,KZ}=(${createV10Components.toString()})({T,g,model:V10,icons:{arrow:Z4,close:B7},Pn});
|
|
307
|
+
const {Overview,PeriodFilter,UpLevel}=createV10Overview({T,g,model:V10,Pn});
|
|
308
|
+
`;
|
|
309
|
+
let html = once(shell, APPLICATION_MARKER, injected);
|
|
310
|
+
// An offline payload is immutable. Module navigation changes n, not filters e;
|
|
311
|
+
// keep the current selection stable so the presentation caches can reuse it.
|
|
312
|
+
html = once(html, ' s = $Z(e);', ' s = g.useMemo(() => $Z(e), [e]);');
|
|
313
|
+
// Month selection returns to month mode; a custom range keeps its end month
|
|
314
|
+
// as the anchor for yearly views. Organization drills keep the period.
|
|
315
|
+
html = once(html, ' const E = { ...S, [b]: x };', ' const E = b === "range" ? { ...S, period: "range", start: x.start, end: x.end, month: x.end.slice(0, 7) } : { ...S, [b]: x, ...(b === "month" ? { period: "month", start: null, end: null } : {}) };');
|
|
316
|
+
const monthLabelStart = html.indexOf('T.jsx("span", { children: "月份" })');
|
|
317
|
+
const monthOpen = html.lastIndexOf('T.jsxs("label", {', monthLabelStart), monthClose = html.indexOf('T.jsxs("label", {', monthLabelStart);
|
|
318
|
+
if (monthLabelStart < 0 || monthOpen < 0 || monthClose < 0 || html.indexOf('T.jsx("span", { children: "月份" })', monthLabelStart + 1) >= 0) fail('月份筛选替换边界不唯一');
|
|
319
|
+
html = html.slice(0, monthOpen) + 'T.jsx(PeriodFilter, { filters: e, drill: f, detail: Boolean(n) }),\n ' + html.slice(monthClose);
|
|
320
|
+
// Global one-step-up control next to the current scope, in overview and details.
|
|
321
|
+
html = once(html, ' DE(e),\n', ' DE(e),\n T.jsx(UpLevel, { filters: e, drill: f }),\n');
|
|
322
|
+
html = once(html, 'T.jsxs("div", {\n className: "scope-line",', 'n ? T.jsxs("div", {\n className: "scope-line",');
|
|
323
|
+
html = once(html, ' : "点击任意板块,展开详细信息",\n }),\n ],\n }),', ' : null,\n }),\n ],\n }) : T.jsx("div", { className: "scope-line", children: T.jsx(UpLevel, { filters: e, drill: f }) }),');
|
|
324
|
+
// The reviewed shell stays immutable. Replace only its overview branch after
|
|
325
|
+
// the original template/shell fingerprints have passed verification.
|
|
326
|
+
html = once(html, 'className: `app-shell ${n ? "detail-mode" : ""}`', 'className: `app-shell ${n ? "detail-mode" : "overview-mode"}`');
|
|
327
|
+
const overviewStart = ' : T.jsxs(T.Fragment, {', overviewEnd = ' T.jsxs("footer", {';
|
|
328
|
+
const start = html.indexOf(overviewStart), end = html.indexOf(overviewEnd, start);
|
|
329
|
+
if (start < 0 || end < 0 || html.indexOf(overviewStart, start + overviewStart.length) >= 0) fail('总览替换边界不唯一');
|
|
330
|
+
html = once(html, html.slice(start, end), ' : T.jsx(Overview, {data:s, filters:e, open:d, drill:f}),\n');
|
|
331
|
+
html = once(html, '<title>战区经营看板 · 设计原型</title>', '<title>战区经营看板 · V10 真实数据</title>');
|
|
332
|
+
html = once(html, '</head>', `<style id="v10-source-preview-style">${readFileSync(new URL('./terminal-structure.css', import.meta.url), 'utf8')}\n${readFileSync(new URL('./v10-details.css', import.meta.url), 'utf8')}\n${readFileSync(new URL('./v10-layout.css', import.meta.url), 'utf8')}\n${readFileSync(new URL('./v10-overview.css', import.meta.url), 'utf8')}</style></head>`);
|
|
333
|
+
html = once(html, '<body>', `<body><div class="v10-source-notice" role="note">${presentation.notice}</div>`);
|
|
334
|
+
return { html, templateSha256, payloadSha256, rendererVersion: V10_RENDERER_VERSION,
|
|
335
|
+
moduleStates: Object.fromEntries(IDS.map(id => [id, payload.modules[id].state])), sources: payload.sources };
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** Preserve the private-template preview entry point for isolated reviews. */
|
|
339
|
+
export function renderV10Preview(templateHtml, input) {
|
|
340
|
+
const shell = extractV10Shell(templateHtml);
|
|
341
|
+
return renderShell(shell, input, { mode: 'real-preview', templateSha256: V10_TEMPLATE_SHA256 });
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Production generation uses only this repository's data-free shell.
|
|
345
|
+
* Source processors may still use the preview contract internally; only an
|
|
346
|
+
* already supported real contract may be promoted to the production view.
|
|
347
|
+
*/
|
|
348
|
+
export function renderV10Dashboard(input) {
|
|
349
|
+
if (!isObject(input) || !['real-preview', 'real'].includes(input.mode)) fail('不支持的数据合同或数据模式');
|
|
350
|
+
const shell = readFileSync(new URL('./v10-shell.html', import.meta.url), 'utf8');
|
|
351
|
+
if (hash(shell) !== V10_SHELL_SHA256) fail('内置模板 SHA 不匹配,请检查代码版本');
|
|
352
|
+
return renderShell(shell, { ...input, mode: 'real' }, { mode: 'real', templateSha256: V10_SHELL_SHA256 });
|
|
353
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile, readdir } from 'node:fs/promises';
|
|
3
|
+
import { resolve, dirname } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { moduleById } from '../modules.mjs';
|
|
6
|
+
|
|
7
|
+
const backendRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
8
|
+
|
|
9
|
+
// Hash code bytes, not the imported module cache. Editing another module must not
|
|
10
|
+
// invalidate this module; editing shared parsing code must invalidate all six.
|
|
11
|
+
export async function validationFingerprint(moduleId, root = backendRoot) {
|
|
12
|
+
if (!moduleById.has(moduleId)) throw new Error('Unsupported module');
|
|
13
|
+
const files = ['modules.mjs', 'validate-workbook.mjs', 'job-worker.mjs', '../package.json', '../package-lock.json'];
|
|
14
|
+
async function walk(directory) {
|
|
15
|
+
for (const entry of await readdir(resolve(root, directory), { withFileTypes: true })) {
|
|
16
|
+
const name = `${directory}/${entry.name}`;
|
|
17
|
+
if (entry.isDirectory()) await walk(name);
|
|
18
|
+
else if (entry.isFile() && /\.(mjs|json)$/.test(name)) files.push(name);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
await walk('recognition');
|
|
22
|
+
await walk(`modules/${moduleId}`);
|
|
23
|
+
const hash = createHash('sha256');
|
|
24
|
+
for (const file of files.sort()) {
|
|
25
|
+
let bytes;
|
|
26
|
+
// npm/Git-installed packages (DSH plugin) never carry package-lock.json; the hash is unchanged when it exists.
|
|
27
|
+
try { bytes = await readFile(resolve(root, file)); }
|
|
28
|
+
catch (error) { if (error.code === 'ENOENT' && file === '../package-lock.json') continue; throw error; }
|
|
29
|
+
hash.update(file).update('\0').update(bytes).update('\0');
|
|
30
|
+
}
|
|
31
|
+
return hash.digest('hex');
|
|
32
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { normalizeHeader } from './headers.mjs';
|
|
2
|
+
|
|
3
|
+
export const VALIDATION_VERSION = 2;
|
|
4
|
+
const structureNotice = '仅完成工作表、表头和非空行结构校验;尚未校验业务值、重复记录、统计期间、单位或计算口径。上传数据不参与本次演示看板计算。';
|
|
5
|
+
|
|
6
|
+
export function createRecognitionResult(moduleId) {
|
|
7
|
+
const result = {
|
|
8
|
+
validationVersion: VALIDATION_VERSION, moduleId, ok: false, level: 'structure',
|
|
9
|
+
sheet: null, headerRow: 1, headers: [], rowCount: 0, missingHeaders: [],
|
|
10
|
+
errors: [], warnings: [], sheets: [], fieldMappings: [], issues: [],
|
|
11
|
+
businessValidation: { status: 'not_run', validRowCount: null, invalidRowCount: null },
|
|
12
|
+
};
|
|
13
|
+
addIssue(result, 'warning', 'STRUCTURE_ONLY', structureNotice);
|
|
14
|
+
return result;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// One issue produces both a machine-readable record and the legacy UI message.
|
|
18
|
+
export function addIssue(result, severity, code, message, location = {}) {
|
|
19
|
+
result.issues.push({ severity, code, message, sheet: null, row: null, columns: [], field: null, ...location });
|
|
20
|
+
result[severity === 'error' ? 'errors' : 'warnings'].push(message);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function mapFields(fields, headers) {
|
|
24
|
+
return fields.map(({ key, header }) => ({
|
|
25
|
+
field: key,
|
|
26
|
+
expectedHeader: header,
|
|
27
|
+
matches: headers.flatMap((source, index) => normalizeHeader(source) === normalizeHeader(header) ? [{ column: index + 1, header: source }] : []),
|
|
28
|
+
}));
|
|
29
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
const MiB = 1024 * 1024;
|
|
2
|
+
|
|
3
|
+
// Shared by both local upload endpoints; recognition fingerprints include this file.
|
|
4
|
+
export const uploadLimits = Object.freeze({
|
|
5
|
+
fileBytes: 100 * MiB,
|
|
6
|
+
entryBytes: 512 * MiB,
|
|
7
|
+
totalBytes: 1024 * MiB,
|
|
8
|
+
entries: 10_000,
|
|
9
|
+
rows: 1_000_000,
|
|
10
|
+
columns: 512,
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
export const formatUploadMB = bytes => `${Number((bytes / MiB).toFixed(6))} MB`;
|
|
14
|
+
export const uploadSizeError = bytes => `上传文件大小为 ${formatUploadMB(bytes)},超过 ${uploadLimits.fileBytes / MiB} MB 上限。请保留所需完整数据并整理文件;多次上传不会合并。`;
|