dsh-data-dashboard 0.1.8 → 0.1.9
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/backend/incremental/flow.mjs +105 -34
- package/backend/incremental/jobs.mjs +11 -11
- package/backend/incremental/xlsx-rows.mjs +74 -3
- package/backend/modules/distributor/index.mjs +9 -6
- package/backend/modules/movement/index.mjs +17 -64
- package/backend/modules/scan/index.mjs +62 -0
- package/backend/modules/scan/legacy.mjs +21 -0
- package/backend/modules.mjs +2 -1
- package/backend/public/admin.css +9 -2
- package/backend/public/admin.js +74 -21
- package/backend/public/board.html +1 -1
- package/backend/public/board.js +2 -2
- package/backend/public/index.html +10 -10
- package/backend/real-data/decimal-sum.mjs +22 -0
- package/backend/real-data/generate-dashboard.mjs +18 -11
- package/backend/real-data/organization-mapping.mjs +31 -11
- package/backend/real-data/source-payload.mjs +163 -86
- package/backend/real-data/terminal-components.mjs +7 -7
- package/backend/real-data/terminal-structure.mjs +5 -5
- package/backend/real-data/v10-components.mjs +2 -2
- package/backend/real-data/v10-details.mjs +7 -62
- package/backend/real-data/v10-model.mjs +74 -71
- package/backend/real-data/v10-overview-data.mjs +14 -20
- package/backend/real-data/v10-overview.mjs +16 -6
- package/backend/real-data/v10-presentation.mjs +48 -27
- package/backend/real-data/v10-template.mjs +99 -71
- package/backend/review-engine.mjs +65 -35
- package/backend/review-service.mjs +28 -13
- package/backend/server.mjs +26 -17
- package/backend/store.mjs +3 -0
- package/backend/target-template.mjs +4 -2
- package/backend/validate-workbook.mjs +5 -2
- package/backend/web-sync/exporter.mjs +55 -21
- package/build-manifest.json +41 -38
- package/index.js +1 -1
- package/lib/tool-definitions.mjs +33 -15
- package/lib/tools.mjs +318 -85
- package/package.json +1 -1
|
@@ -3,38 +3,32 @@ import { resolve, sep } from 'node:path';
|
|
|
3
3
|
import { createHash } from 'node:crypto';
|
|
4
4
|
import { promisify } from 'node:util';
|
|
5
5
|
import { gunzip, gzip } from 'node:zlib';
|
|
6
|
-
import
|
|
6
|
+
import { sumDecimal as sum } from './decimal-sum.mjs';
|
|
7
|
+
import { hashWorkbook, streamValidatedRows } from '../incremental/xlsx-rows.mjs';
|
|
7
8
|
import { validateWorkbook } from '../validate-workbook.mjs';
|
|
9
|
+
import { isDealerMovement } from '../modules/movement/index.mjs';
|
|
10
|
+
import { activeUploadId, uploadForModule, isLegacyScanUpload } from '../modules/scan/legacy.mjs';
|
|
8
11
|
import { normalizeHeader, moduleById } from '../modules.mjs';
|
|
9
|
-
import { applyOrganizationMapping, buildDecisionContract } from './organization-mapping.mjs';
|
|
12
|
+
import { applyOrganizationMapping, buildDecisionContract, organizationMappingForSourceTemplates } from './organization-mapping.mjs';
|
|
10
13
|
import { processInventoryHistory } from './inventory-history.mjs';
|
|
11
14
|
import { targetColumns } from '../modules/target/index.mjs';
|
|
12
|
-
import { inspectRows, resolveInspection, applyDuplicateDecisions, applyOrganizationRules, monthDay } from '../review-engine.mjs';
|
|
15
|
+
import { legacyScanRuleFormats, reviewForSourceTemplates, rowInspector, inspectRows, resolveInspection, applyDuplicateDecisions, applyOrganizationRules, monthDay } from '../review-engine.mjs';
|
|
13
16
|
import { lineageShas } from '../incremental/flow.mjs';
|
|
14
17
|
|
|
15
|
-
const MODULES = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet', 'target', 'zang10', 'tunzhihu', 'distributor'];
|
|
16
|
-
// 2026-11-27
|
|
18
|
+
const MODULES = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet', 'target', 'zang10', 'tunzhihu', 'distributor', 'scan'];
|
|
19
|
+
// 2026-11-27:两个平台的订单并入发票销售。
|
|
17
20
|
export const PLATFORM_MODULES = ['zang10', 'tunzhihu'];
|
|
18
21
|
const PENDING = {
|
|
19
22
|
invoice: ['invoiceTarget', 'invoiceQuantityConversion'],
|
|
20
23
|
movement: ['invoiceMovementRelationship'],
|
|
21
|
-
opening: ['
|
|
24
|
+
opening: ['banquetOpeningOverlap'],
|
|
22
25
|
terminal: ['crossTableTerminalIdentity'],
|
|
23
26
|
inventory: ['inventoryHistory', 'inventoryValuationBasis', 'inventorySellableMonthsEstimate'],
|
|
24
27
|
banquet: ['banquetOpeningOverlap'],
|
|
25
|
-
target: [], zang10: [], tunzhihu: [], distributor: [],
|
|
28
|
+
target: [], zang10: [], tunzhihu: [], distributor: [], scan: [],
|
|
26
29
|
};
|
|
27
30
|
const metric = (value, unit, status = 'available', reason) => ({ value, status, unit, ...(reason ? { reason } : {}) });
|
|
28
31
|
const text = value => value === null || value === undefined ? '' : String(value).trim();
|
|
29
|
-
function scalar(value) {
|
|
30
|
-
if (value === null || value === undefined) return null;
|
|
31
|
-
if (value instanceof Date) return value.toISOString();
|
|
32
|
-
if (typeof value !== 'object') return value;
|
|
33
|
-
if ('formula' in value || 'sharedFormula' in value) return scalar(value.result);
|
|
34
|
-
if (value.richText) return value.richText.map(part => part.text).join('');
|
|
35
|
-
if ('text' in value) return value.text;
|
|
36
|
-
return null;
|
|
37
|
-
}
|
|
38
32
|
function number(value) {
|
|
39
33
|
if (value === null || value === undefined || text(value) === '') return null;
|
|
40
34
|
if (typeof value === 'boolean') return null;
|
|
@@ -45,22 +39,6 @@ function number(value) {
|
|
|
45
39
|
const result = Number(source);
|
|
46
40
|
return Number.isFinite(result) ? result : null;
|
|
47
41
|
}
|
|
48
|
-
// Sum decimal source values exactly before returning JSON numbers. This avoids
|
|
49
|
-
// accumulated binary floating-point noise in currency and keeps source signs.
|
|
50
|
-
function sum(values) {
|
|
51
|
-
let total = 0n, scale = 0;
|
|
52
|
-
for (const value of values) {
|
|
53
|
-
if (value === null || value === undefined) continue;
|
|
54
|
-
const match = String(value).match(/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]?\d+))?$/i);
|
|
55
|
-
if (!match) continue;
|
|
56
|
-
let digits = BigInt(`${match[1]}${match[2]}${match[3] ?? ''}`);
|
|
57
|
-
let nextScale = (match[3]?.length ?? 0) - Number(match[4] ?? 0);
|
|
58
|
-
if (nextScale < 0) { digits *= 10n ** BigInt(-nextScale); nextScale = 0; }
|
|
59
|
-
if (nextScale > scale) { total *= 10n ** BigInt(nextScale - scale); scale = nextScale; }
|
|
60
|
-
total += digits * 10n ** BigInt(scale - nextScale);
|
|
61
|
-
}
|
|
62
|
-
return Number(total) / 10 ** scale;
|
|
63
|
-
}
|
|
64
42
|
function date(value, date1904 = false) {
|
|
65
43
|
if (typeof value === 'number' && value > 0 && value < 100000) {
|
|
66
44
|
value = new Date(Date.UTC(date1904 ? 1904 : 1899, date1904 ? 0 : 11, date1904 ? 1 : 30) + Math.floor(value) * 86400000).toISOString();
|
|
@@ -71,9 +49,9 @@ function date(value, date1904 = false) {
|
|
|
71
49
|
const parsed = new Date(`${result}T00:00:00Z`);
|
|
72
50
|
return Number.isFinite(parsed.valueOf()) && parsed.toISOString().slice(0, 10) === result ? result : null;
|
|
73
51
|
}
|
|
74
|
-
function fieldAccess(headers
|
|
52
|
+
function fieldAccess(headers) {
|
|
75
53
|
const columns = new Map(headers.map((header, index) => [normalizeHeader(header), index]));
|
|
76
|
-
return (...names) => {
|
|
54
|
+
return values => (...names) => {
|
|
77
55
|
for (const name of names) {
|
|
78
56
|
const index = columns.get(normalizeHeader(name));
|
|
79
57
|
if (index !== undefined) return values[index];
|
|
@@ -84,7 +62,8 @@ function fieldAccess(headers, values) {
|
|
|
84
62
|
function organization(get, moduleId) {
|
|
85
63
|
const headers = {
|
|
86
64
|
invoice: ['销售大区', '办事处', '客户主任单元'],
|
|
87
|
-
movement: ['
|
|
65
|
+
movement: ['大区', '办事处', '主任单元'],
|
|
66
|
+
scan: ['大区名称', '办事处名称', '主任单元名称'],
|
|
88
67
|
opening: ['产品所属-大区', '产品所属-办事处', '产品所属-主任单元'],
|
|
89
68
|
terminal: ['大区', '办事处', '主任单元'],
|
|
90
69
|
inventory: ['大区名称', '办事处名称', '单元名称'],
|
|
@@ -105,10 +84,11 @@ function normalizedRecord(moduleId, row, workbook) {
|
|
|
105
84
|
const dealer = () => ({ dealerCode: text(get('经销商编码', '签约经销商编码')), dealerName: text(get('经销商名称', '签约经销商')), dealerType: text(get('经销商类型')) });
|
|
106
85
|
const parseDate = value => date(value, workbook.properties.date1904);
|
|
107
86
|
if (moduleId === 'invoice') return { ...common, ...product(), ...dealer(), date: parseDate(get('业务日期')), amount: number(get('发票金额')), quantity: number(get('计价数量')), quantityUnit: text(get('计价单位')), documentType: text(get('单据类型')), documentCode: text(get('单据编码')), documentLine: text(get('单据行号')), grade: text(get('经销商分级')) };
|
|
108
|
-
if (moduleId === 'movement') {
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
87
|
+
if (moduleId === 'movement') return { ...common, ...product(), ...dealer(), source: 'dealer', variety: text(get('品种')),
|
|
88
|
+
date: parseDate(get('数据日期')), amount: number(get('总动销金额')), cases: number(get('总动销数量')),
|
|
89
|
+
documentType: text(get('单据类型')), documentCode: text(get('单据编号')), movementType: text(get('变动类型')) };
|
|
90
|
+
if (moduleId === 'scan') return { ...common, ...product(), variety: text(get('品种名称')), date: parseDate(get('扫码日期')),
|
|
91
|
+
cases: number(get('扫码件数')), terminalCode: text(get('售点编码')) };
|
|
112
92
|
if (moduleId === 'opening') return { ...common, date: parseDate(get('抽奖日期')), bottles: number(get('开瓶瓶数')), amount: number(get('开瓶金额')), city: text(get('开瓶城市')), amountMeaning: '开瓶金额', amountUnit: '元' };
|
|
113
93
|
if (moduleId === 'zang10') {
|
|
114
94
|
// 按订单归属年月归月;订单所在日期落在归属月内时保留到日,否则记为归属月 1 日。
|
|
@@ -122,8 +102,8 @@ function normalizedRecord(moduleId, row, workbook) {
|
|
|
122
102
|
if (moduleId === 'tunzhihu') return { ...common, platform: 'tunzhihu', date: parseDate(get('业务日期')), amount: number(get('发票金额')),
|
|
123
103
|
productCode: '', productName: text(get('产品名称')), brand: null, category: null, dealerCode: '', dealerName: text(get('销管客户名称', 'BI/财务系统客户名称')), dealerType: '',
|
|
124
104
|
documentType: text(get('单据类型')), documentCode: text(get('订单编号')), documentLine: '' };
|
|
125
|
-
if (moduleId === 'distributor') return { ...common, ...product(), date: parseDate(get('动销日期 (日)')), amount: number(get('总动销金额')),
|
|
126
|
-
distributorName: text(get('分销商名称')), distributorCode: text(get('分销商编码')),
|
|
105
|
+
if (moduleId === 'distributor') return { ...common, ...product(), source: 'distributor', date: parseDate(get('动销日期 (日)')), amount: number(get('总动销金额')), cases: number(get('总动销数量')),
|
|
106
|
+
...dealer(), distributorName: text(get('分销商名称')), distributorCode: text(get('分销商编码')), documentType: text(get('单据类型')) };
|
|
127
107
|
if (moduleId === 'banquet') return { ...common, date: monthDay(get('执行时间(月)'), workbook.properties.date1904), events: number(get('执行场次')), bottles: number(get('开瓶数量')),
|
|
128
108
|
dealerName: text(get('经销商名称')), variety: text(get('用酒品种')) };
|
|
129
109
|
if (moduleId === 'terminal') return { ...common, ...dealer(), date: parseDate(get('签约日期')), signDate: parseDate(get('签约日期')), startDate: parseDate(get('协议开始日期')), endDate: parseDate(get('协议结束日期')), agreementId: text(get('协议编号')), terminalCode: text(get('网点编号')), terminalName: text(get('网点名称')), type: text(get('网点类型')), series: text(get('协议名称')), star: text(get('星级')), signLevel: text(get('签约等级')), signVariety: text(get('签约品种')), manualClosed: text(get('是否手工关闭')), approvalStatus: text(get('审批状态')), signingStatus: text(get('签约状态')) };
|
|
@@ -171,8 +151,8 @@ function totals(records, field, unit) {
|
|
|
171
151
|
function computeMetrics(moduleId, records) {
|
|
172
152
|
const result = { records: metric(records.length, '行') };
|
|
173
153
|
const fields = {
|
|
174
|
-
invoice: { amount: '元' }, movement: { amount: '元', cases: '
|
|
175
|
-
zang10: { amount: '元' }, tunzhihu: { amount: '元' }, distributor: { amount: '元' },
|
|
154
|
+
invoice: { amount: '元' }, movement: { amount: '元', cases: '件' }, opening: { bottles: '瓶', amount: '元(开瓶金额)' },
|
|
155
|
+
zang10: { amount: '元' }, tunzhihu: { amount: '元' }, distributor: { amount: '元', cases: '件' }, scan: {},
|
|
176
156
|
terminal: {}, target: {}, inventory: { counted: '瓶(本次导出记录合计)', system: '瓶(本次导出记录合计)', countAmount: '元', systemAmount: '元', absoluteVariance: '瓶' }, banquet: { events: '场', bottles: '瓶' },
|
|
177
157
|
}[moduleId];
|
|
178
158
|
for (const [field, unit] of Object.entries(fields)) result[field] = totals(records, field, unit);
|
|
@@ -181,10 +161,6 @@ function computeMetrics(moduleId, records) {
|
|
|
181
161
|
result.positiveAmount = metric(complete ? sum(records.filter(row => row.amount > 0).map(row => row.amount)) : null, '元', complete ? 'available' : 'missing');
|
|
182
162
|
result.negativeAmount = metric(complete ? sum(records.filter(row => row.amount < 0).map(row => row.amount)) : null, '元', complete ? 'available' : 'missing');
|
|
183
163
|
}
|
|
184
|
-
if (moduleId === 'movement') {
|
|
185
|
-
for (const [key, unit] of [['bottles', '瓶'], ['boxes', '盒']]) result[key] = totals(records.filter(row => row.quantityUnit === unit), key, unit);
|
|
186
|
-
result.unknownUnitRows = metric(records.filter(row => !['瓶', '盒'].includes(row.quantityUnit)).length, '行');
|
|
187
|
-
}
|
|
188
164
|
if (moduleId === 'terminal') {
|
|
189
165
|
const missingCode = records.some(row => !row.terminalCode);
|
|
190
166
|
result.terminalCount = metric(missingCode ? null : new Set(records.map(row => row.terminalCode)).size, '终端', missingCode ? 'missing' : 'available');
|
|
@@ -204,7 +180,7 @@ function coverage(moduleId, records, decisions, sha256) {
|
|
|
204
180
|
return { start: dates[0] ?? null, end, semantics: 'execution-month', status: dates.length ? 'confirmed' : 'missing', productFilter: false };
|
|
205
181
|
}
|
|
206
182
|
const dates = records.map(row => row.date).filter(Boolean).sort();
|
|
207
|
-
return { start: dates[0] ?? null, end: dates.at(-1) ?? null, semantics: ({ target: 'target-month', invoice: 'business-date', movement: 'scan-date', opening: 'draw-date', terminal: 'signed-date-not-historical-validity', inventory: 'stocktake-record-date-not-historical-stock', zang10: 'attribution-month', tunzhihu: 'business-date', distributor: 'movement-date' })[moduleId], status: dates.length === records.length ? 'observed' : 'partial', productFilter: ['invoice', 'movement', 'inventory'].includes(moduleId) };
|
|
183
|
+
return { start: dates[0] ?? null, end: dates.at(-1) ?? null, semantics: ({ target: 'target-month', invoice: 'business-date', movement: 'movement-date', scan: 'scan-date', opening: 'draw-date', terminal: 'signed-date-not-historical-validity', inventory: 'stocktake-record-date-not-historical-stock', zang10: 'attribution-month', tunzhihu: 'business-date', distributor: 'movement-date' })[moduleId], status: dates.length === records.length ? 'observed' : 'partial', productFilter: ['invoice', 'movement', 'inventory'].includes(moduleId) };
|
|
208
184
|
}
|
|
209
185
|
function comparable(value, expected) {
|
|
210
186
|
if (typeof expected === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(expected)) return date(value) === expected;
|
|
@@ -268,7 +244,7 @@ function diagnostics(payload) {
|
|
|
268
244
|
}
|
|
269
245
|
const collisions = [...organizationAliases.values()].filter(group => group.size > 1).map(group => [...group.values()]);
|
|
270
246
|
const siteOrgs = new Map(), outletOrgs = new Map();
|
|
271
|
-
for (const [id, target] of [['terminal', siteOrgs], ['
|
|
247
|
+
for (const [id, target] of [['terminal', siteOrgs], ['scan', outletOrgs]]) for (const row of records(id)) {
|
|
272
248
|
if (!row.terminalCode) continue;
|
|
273
249
|
const orgs = target.get(row.terminalCode) ?? new Set(); orgs.add(row.orgKey); target.set(row.terminalCode, orgs);
|
|
274
250
|
}
|
|
@@ -366,38 +342,34 @@ const ROW_CACHE_VERSION = 1;
|
|
|
366
342
|
let parserSourceSha;
|
|
367
343
|
const gzipAsync = promisify(gzip), gunzipAsync = promisify(gunzip);
|
|
368
344
|
async function rowCacheKey(moduleId, sha256) {
|
|
369
|
-
parserSourceSha ??=
|
|
345
|
+
parserSourceSha ??= Promise.all([new URL(import.meta.url), new URL('../incremental/xlsx-rows.mjs', import.meta.url)].map(file => readFile(file)))
|
|
346
|
+
.then(parts => createHash('sha256').update(Buffer.concat(parts)).digest('hex'));
|
|
370
347
|
const { validationFingerprint } = await import('../recognition/fingerprint.mjs');
|
|
371
|
-
return createHash('sha256').update(JSON.stringify([ROW_CACHE_VERSION, moduleId, sha256, await validationFingerprint(moduleId), parserSourceSha])).digest('hex');
|
|
348
|
+
return createHash('sha256').update(JSON.stringify([ROW_CACHE_VERSION, moduleId, sha256, await validationFingerprint(moduleId), await parserSourceSha])).digest('hex');
|
|
372
349
|
}
|
|
373
350
|
// JSON cannot carry -0; every other scalar() value (string, finite number, boolean, null) round-trips exactly.
|
|
374
351
|
const encodeValue = value => Object.is(value, -0) ? { negativeZero: true } : value;
|
|
375
352
|
const decodeValue = value => value !== null && typeof value === 'object' ? (value.negativeZero ? -0 : null) : value;
|
|
376
|
-
async function readSourceRows({ file,
|
|
353
|
+
async function readSourceRows({ file, moduleId, sha256, cacheFile }) {
|
|
377
354
|
// Only the backend's own generation opts in; previews and exports never write to the data directory.
|
|
378
355
|
const key = cacheFile ? await rowCacheKey(moduleId, sha256) : null;
|
|
379
356
|
if (cacheFile) try {
|
|
380
357
|
const cached = JSON.parse((await gunzipAsync(await readFile(cacheFile))).toString('utf8'));
|
|
381
358
|
if (cached.key === key && cached.sha256 === sha256 && Array.isArray(cached.headers) && Array.isArray(cached.rows)) {
|
|
382
359
|
const { headers } = cached;
|
|
383
|
-
const
|
|
360
|
+
const access = fieldAccess(headers);
|
|
361
|
+
const rows = cached.rows.map(([row, encoded]) => { const values = encoded.map(decodeValue); return { row, sheet: cached.sheetName, values, get: access(values) }; });
|
|
384
362
|
return { validation: cached.validation, sheetName: cached.sheetName, date1904: cached.date1904, headers, rows, cached: true };
|
|
385
363
|
}
|
|
386
364
|
} catch {}
|
|
387
365
|
const validation = await validateWorkbook(file, moduleId);
|
|
388
366
|
if (!validation.ok) return { validation, rows: [], headers: [] };
|
|
389
|
-
|
|
390
|
-
const sheet = workbook.getWorksheet(validation.sheet);
|
|
391
|
-
if (!sheet) throw new Error('已验证的主工作表不可读取。');
|
|
392
|
-
const headers = Array.from({ length: Math.min(sheet.columnCount, moduleById.get(moduleId).sourceColumnLimit ?? sheet.columnCount) }, (_, index) => text(scalar(sheet.getRow(1).getCell(index + 1).value)));
|
|
367
|
+
let headers, access;
|
|
393
368
|
const rows = [];
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
rows.push({ row: index, sheet: sheet.name, values, get: fieldAccess(headers, values) });
|
|
399
|
-
});
|
|
400
|
-
const result = { validation, sheetName: sheet.name, date1904: workbook.properties.date1904, headers, rows };
|
|
369
|
+
const { date1904 } = await streamValidatedRows(file, validation, moduleById.get(moduleId).sourceColumnLimit,
|
|
370
|
+
values => { headers = values; access = fieldAccess(headers); },
|
|
371
|
+
row => { rows.push({ ...row, get: access(row.values) }); }, { preserveMerges: moduleId === 'scan' });
|
|
372
|
+
const result = { validation, sheetName: validation.sheet, date1904, headers, rows };
|
|
401
373
|
if (!cacheFile) return result;
|
|
402
374
|
// Best effort and atomic: a failed write only means the next generation reads Excel again.
|
|
403
375
|
const temp = `${cacheFile}.${process.pid}.${Date.now()}.tmp`;
|
|
@@ -408,41 +380,137 @@ async function readSourceRows({ file, buffer, moduleId, sha256, cacheFile }) {
|
|
|
408
380
|
return result;
|
|
409
381
|
}
|
|
410
382
|
|
|
383
|
+
async function readMovementSource(file, moduleId, sha256, review) {
|
|
384
|
+
const validation = await validateWorkbook(file, moduleId);
|
|
385
|
+
if (!validation.ok) return { validation };
|
|
386
|
+
const dealer = moduleId === 'movement', dateColumn = dealer ? '数据日期' : '动销日期 (日)';
|
|
387
|
+
const records = [], excludedSample = [];
|
|
388
|
+
let access, workbook, inspector, sourceRows = 0, nonMovementRows = 0, valuedRows = 0;
|
|
389
|
+
let start = null, end = null, dates = 0;
|
|
390
|
+
await streamValidatedRows(file, validation, undefined, (headers, date1904) => {
|
|
391
|
+
access = fieldAccess(headers);
|
|
392
|
+
workbook = { properties: { date1904 } };
|
|
393
|
+
if (review) inspector = rowInspector({ moduleId, headers, sheet: validation.sheet, sha256, date1904, sourceFormat: validation.sourceFormat });
|
|
394
|
+
}, row => {
|
|
395
|
+
sourceRows++;
|
|
396
|
+
inspector?.row(row);
|
|
397
|
+
const get = access(row.values);
|
|
398
|
+
const day = date(get(dateColumn), workbook.properties.date1904);
|
|
399
|
+
if (day) {
|
|
400
|
+
if (!start || day < start) start = day;
|
|
401
|
+
if (!end || day > end) end = day;
|
|
402
|
+
dates++;
|
|
403
|
+
}
|
|
404
|
+
if (!dealer || isDealerMovement(text(get('单据类型')))) records.push(normalizedRecord(moduleId, { ...row, get }, workbook));
|
|
405
|
+
else {
|
|
406
|
+
nonMovementRows++;
|
|
407
|
+
if (number(get('总动销金额')) || number(get('总动销数量'))) {
|
|
408
|
+
valuedRows++;
|
|
409
|
+
if (excludedSample.length < 10) excludedSample.push(row.row);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
const warnings = valuedRows ? [`${valuedRows} 行非经销商销售出库或销售退货的单据含非零总动销金额或数量,已排除。示例 Excel 行号:${excludedSample.join('、')}。`] : [];
|
|
414
|
+
return { validation, sheetName: validation.sheet, records, sourceRows, nonMovementRows, warnings,
|
|
415
|
+
coverage: { start, end, semantics: 'movement-date', status: dates === sourceRows ? 'observed' : 'partial', productFilter: dealer },
|
|
416
|
+
inspection: inspector?.result() };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function mergeMovement(payload) {
|
|
420
|
+
const { movement, distributor } = payload.modules;
|
|
421
|
+
const entries = [['dealer', 'movement'], ['distributor', 'distributor']];
|
|
422
|
+
const sources = payload.movementSources = {};
|
|
423
|
+
for (const [key, id] of entries) {
|
|
424
|
+
const module = payload.modules[id];
|
|
425
|
+
const cover = payload.coverage[id];
|
|
426
|
+
if (module.state !== 'unavailable') sources[key] = { rows: module.records.length, coverage: { start: cover.start, end: cover.end },
|
|
427
|
+
originalName: payload.sources[id]?.originalName ?? null, ...(module.scopeLimits ? { scopeLimits: module.scopeLimits } : {}) };
|
|
428
|
+
else if (module.scopeLimits) sources[key] = { rows: 0, coverage: { start: null, end: null }, originalName: null, scopeLimits: module.scopeLimits };
|
|
429
|
+
}
|
|
430
|
+
const hasDealer = movement.state !== 'unavailable', hasDistributor = distributor.state !== 'unavailable';
|
|
431
|
+
if (hasDealer && hasDistributor) {
|
|
432
|
+
movement.records = movement.records.concat(distributor.records);
|
|
433
|
+
movement.metrics = computeMetrics('movement', movement.records);
|
|
434
|
+
movement.warnings.push(...distributor.warnings);
|
|
435
|
+
if (distributor.state === 'partial' || Object.values(movement.metrics).some(item => item.status === 'missing')) movement.state = 'partial';
|
|
436
|
+
const dealer = sources.dealer.coverage, secondary = sources.distributor.coverage;
|
|
437
|
+
const start = [dealer.start, secondary.start].filter(Boolean).sort()[0] ?? null;
|
|
438
|
+
const end = dealer.end && secondary.end ? [dealer.end, secondary.end].sort()[0] : null;
|
|
439
|
+
Object.assign(payload.coverage.movement, { start: start && end && start <= end ? start : null, end, semantics: 'common-movement-date',
|
|
440
|
+
status: start && end && start <= end ? (payload.coverage.movement.status === 'observed' && payload.coverage.distributor.status === 'observed' ? 'observed' : 'partial') : 'missing' });
|
|
441
|
+
} else if (hasDistributor) {
|
|
442
|
+
// 只有分销商动销时照常出动销,如实标明只含分销商;经销商的失败原因留给生成步骤提示重传。
|
|
443
|
+
if (movement.reason) movement.dealerFailure = movement.reason;
|
|
444
|
+
delete movement.reviewPending;
|
|
445
|
+
delete movement.reviewReason;
|
|
446
|
+
Object.assign(movement, { state: distributor.state, records: distributor.records, metrics: computeMetrics('movement', distributor.records), reason: null,
|
|
447
|
+
unavailable: [...distributor.unavailable], warnings: [...movement.warnings, ...distributor.warnings, '本次动销只含分销商动销明细(经销商动销明细未上传或不可用)。'] });
|
|
448
|
+
payload.coverage.movement = { ...payload.coverage.distributor, semantics: 'movement-date', productFilter: true };
|
|
449
|
+
} else if (hasDealer) {
|
|
450
|
+
movement.warnings.push('本次动销只含经销商动销明细(分销商动销明细未上传或不可用)。');
|
|
451
|
+
}
|
|
452
|
+
if (distributor.scopeLimits?.invalidTemplate && hasDealer) {
|
|
453
|
+
movement.state = 'partial';
|
|
454
|
+
movement.warnings.push(distributor.scopeLimits.invalidTemplate);
|
|
455
|
+
}
|
|
456
|
+
distributor.records = [];
|
|
457
|
+
}
|
|
458
|
+
|
|
411
459
|
export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersions, allowPending = false, rowCache = false } = {}) {
|
|
412
460
|
if (!dataDir) throw new Error('必须提供后台数据目录。');
|
|
413
461
|
const root = await realpath(resolve(dataDir));
|
|
414
462
|
const state = JSON.parse(await readFile(resolve(root, 'state.json'), 'utf8'));
|
|
415
463
|
if (state.schemaVersion !== 1 || !Array.isArray(state.uploads) || !state.active || typeof state.active !== 'object') throw new Error('后台 state 格式不受支持。');
|
|
464
|
+
const oldFormats = await legacyScanRuleFormats(state, root);
|
|
465
|
+
let review = reviewForSourceTemplates(state.review, oldFormats);
|
|
416
466
|
let decisions = null, decisionError = null;
|
|
417
467
|
if (decisionsFile) { try { decisions = JSON.parse(await readFile(decisionsFile, 'utf8')); } catch { decisionError = '决定文件无法读取或不是有效 JSON。'; } }
|
|
418
|
-
const payload = { schemaVersion: 1, processingVersion:
|
|
468
|
+
const payload = { schemaVersion: 1, processingVersion: 9, mode: 'real-preview', generatedAt: new Date().toISOString(), sources: {}, coverage: {}, modules: {}, pendingDecisions: [...new Set(Object.values(PENDING).flat())] };
|
|
419
469
|
const report = { schemaVersion: 1, generatedAt: payload.generatedAt, decisionError, modules: {}, diagnostics: {}, originalStoreModified: false };
|
|
420
470
|
for (const moduleId of MODULES) {
|
|
421
471
|
const output = { state: 'unavailable', records: [], metrics: {}, unavailable: [...PENDING[moduleId]], warnings: [] };
|
|
422
472
|
payload.modules[moduleId] = output;
|
|
423
473
|
const detail = { sourceRows: 0, includedRows: 0, excludedRows: [], errors: [], warnings: [] }; report.modules[moduleId] = detail;
|
|
424
474
|
try {
|
|
425
|
-
const uploadId = sourceVersions ? sourceVersions[moduleId]?.uploadId : state
|
|
475
|
+
const uploadId = sourceVersions ? sourceVersions[moduleId]?.uploadId : activeUploadId(state, moduleId);
|
|
426
476
|
if (!uploadId) throw new Error('未选择有效上传版本。');
|
|
427
477
|
if (typeof uploadId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(uploadId)) throw new Error('上传版本标识无效。');
|
|
428
|
-
const upload = state
|
|
478
|
+
const upload = uploadForModule(state, moduleId, uploadId);
|
|
429
479
|
if (!upload || !/^[a-f0-9]{64}$/i.test(upload.sha256 ?? '')) throw new Error('上传版本或 SHA 记录不完整。');
|
|
430
480
|
const file = await realpath(resolve(root, 'uploads', uploadId, 'source.xlsx'));
|
|
431
481
|
if (!file.startsWith(`${resolve(root, 'uploads')}${sep}`)) throw new Error('上传文件路径越出后台 uploads 目录。');
|
|
432
|
-
|
|
482
|
+
// Recognize the old active slot explicitly; the same bytes are checked
|
|
483
|
+
// against their real template when the locked scan slot is processed.
|
|
484
|
+
if (moduleId === 'movement' && isLegacyScanUpload(upload)) throw new Error('工作簿结构校验失败:旧版本为终端扫码,请上传经销商动销明细表。');
|
|
485
|
+
const sha256 = await hashWorkbook(file);
|
|
433
486
|
if (sha256 !== upload.sha256.toLowerCase()) throw new Error('源文件 SHA 与有效上传记录不一致,已停止该板块计算。');
|
|
434
|
-
const
|
|
487
|
+
const dealer = moduleId === 'movement';
|
|
488
|
+
const movementSource = dealer || moduleId === 'distributor';
|
|
489
|
+
const parsed = movementSource ? await readMovementSource(file, moduleId, sha256, review)
|
|
490
|
+
: await readSourceRows({ file, moduleId, sha256, cacheFile: rowCache ? resolve(root, 'uploads', uploadId, ROW_CACHE_FILE) : null });
|
|
491
|
+
const { validation, sheetName, date1904, headers, rows = [] } = parsed;
|
|
492
|
+
if (!validation.ok && moduleId === 'distributor' && validation.missingHeaders?.length) {
|
|
493
|
+
output.scopeLimits = { invalidTemplate: `分销商动销明细缺少必需字段(${validation.missingHeaders.join('、')}),请按新模板重传。` };
|
|
494
|
+
}
|
|
435
495
|
if (!validation.ok) throw new Error(`工作簿结构校验失败:${validation.errors.map(error => typeof error === 'string' ? error : error.message).join(';')}`);
|
|
436
496
|
// Later steps only read the sheet name and the workbook date system.
|
|
437
497
|
const workbook = { properties: { date1904 } }, sheet = { name: sheetName };
|
|
438
498
|
payload.sources[moduleId] = { uploadId, sha256, originalName: upload.filename ?? null, sheet: sheet.name, validationVersion: validation.validationVersion };
|
|
439
|
-
detail.sourceRows = rows.length;
|
|
499
|
+
detail.sourceRows = movementSource ? parsed.sourceRows : rows.length;
|
|
500
|
+
if (dealer) {
|
|
501
|
+
detail.warnings.push(...parsed.warnings);
|
|
502
|
+
detail.nonMovementRows = parsed.nonMovementRows;
|
|
503
|
+
}
|
|
440
504
|
let included = rows;
|
|
441
|
-
if (
|
|
442
|
-
const inspection = inspectRows({ moduleId, headers, rows, sheet: sheet.name, sha256, date1904: workbook.properties.date1904, sourceFormat: validation.sourceFormat });
|
|
505
|
+
if (review) {
|
|
506
|
+
const inspection = parsed.inspection ?? inspectRows({ moduleId, headers, rows, sheet: sheet.name, sha256, date1904: workbook.properties.date1904, sourceFormat: validation.sourceFormat });
|
|
507
|
+
if (moduleId === 'scan') {
|
|
508
|
+
review = reviewForSourceTemplates(state.review, oldFormats, inspection);
|
|
509
|
+
payload.sources.scan.legacyFormatKey = inspection.legacyFormatKey;
|
|
510
|
+
}
|
|
443
511
|
inspection.lineage = lineageShas(state, uploadId);
|
|
444
512
|
payload.sources[moduleId].lineage = inspection.lineage;
|
|
445
|
-
const reviewed = resolveInspection(inspection,
|
|
513
|
+
const reviewed = resolveInspection(inspection, review, decisions);
|
|
446
514
|
payload.sources[moduleId].formatKey = inspection.formatKey;
|
|
447
515
|
detail.review = { pendingCount: reviewed.pendingCount, errors: reviewed.errors, groups: reviewed.groups.map(group => ({ key: group.key, status: group.status, decisionId: group.decisionId, reused: group.reused, keptRows: group.rows.filter(row => group.keepKeys.includes(row.key)).map(row => row.row), excludedRows: group.status === 'resolved' ? group.rows.filter(row => !group.keepKeys.includes(row.key)).map(row => row.row) : [] })) };
|
|
448
516
|
if (reviewed.pendingCount || reviewed.errors.length) {
|
|
@@ -480,7 +548,7 @@ export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersion
|
|
|
480
548
|
detail.warnings.push('新来源没有盘点金额和产品编码;金额差额、可销月份、品牌品类联动及安全库存判断不可用。最近盘点不代表统一时点实时库存。');
|
|
481
549
|
output.unavailable = ['inventoryCountAmount', 'inventoryAmountDifference', 'inventorySellableMonthsEstimate', 'inventoryProductMapping', 'inventorySafetyStock'];
|
|
482
550
|
} else {
|
|
483
|
-
output.records = moduleId === 'target' ? included.flatMap(row => targetRecords(row, headers, workbook)) : included.map(row => normalizedRecord(moduleId, row, workbook));
|
|
551
|
+
output.records = movementSource ? parsed.records : moduleId === 'target' ? included.flatMap(row => targetRecords(row, headers, workbook)) : included.map(row => normalizedRecord(moduleId, row, workbook));
|
|
484
552
|
if (moduleId === 'banquet') {
|
|
485
553
|
// 没有执行月份的行不归入任何月份;场次、开瓶都为 0 的是组织占位。
|
|
486
554
|
const undated = output.records.filter(row => !row.date), valued = undated.filter(row => row.events || row.bottles);
|
|
@@ -489,8 +557,17 @@ export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersion
|
|
|
489
557
|
detail.skippedPlaceholderRows = undated.length - valued.length;
|
|
490
558
|
}
|
|
491
559
|
output.metrics = computeMetrics(moduleId, output.records);
|
|
492
|
-
payload.coverage[moduleId] = coverage(moduleId, output.records, decisions, sha256);
|
|
493
|
-
|
|
560
|
+
payload.coverage[moduleId] = movementSource ? parsed.coverage : coverage(moduleId, output.records, decisions, sha256);
|
|
561
|
+
if (moduleId === 'distributor') {
|
|
562
|
+
const organization = output.records.filter(row => row.orgPath.some(value => !value)).length;
|
|
563
|
+
const product = output.records.filter(row => !row.brand || !row.category).length;
|
|
564
|
+
if (organization || product) {
|
|
565
|
+
output.scopeLimits = { organization, product };
|
|
566
|
+
if (organization) detail.warnings.push(`分销商有 ${organization} 行缺少完整组织,组织范围汇总待确认。`);
|
|
567
|
+
if (product) detail.warnings.push(`分销商有 ${product} 行缺少品牌或品类,产品范围汇总待确认。`);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
detail.includedRows = movementSource ? parsed.records.length : included.length;
|
|
494
571
|
}
|
|
495
572
|
if (moduleId === 'target') {
|
|
496
573
|
const invalid = output.records.filter(row => row.issue && row.issue !== '目标值为空');
|
|
@@ -502,7 +579,6 @@ export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersion
|
|
|
502
579
|
}
|
|
503
580
|
detail.missingDates = ['banquet', 'target'].includes(moduleId) ? null : output.records.filter(row => row.date === null).length;
|
|
504
581
|
if (detail.missingDates) detail.warnings.push(`${detail.missingDates} 行日期无法确认,不归入任何月份。`);
|
|
505
|
-
if (moduleId === 'movement' && output.metrics.unknownUnitRows.value) detail.warnings.push('存在未确认单品单位,金额保留,数量不归为瓶或盒。');
|
|
506
582
|
if (moduleId === 'inventory' && !visitInventory) {
|
|
507
583
|
detail.sourceVarianceNullRows = output.records.filter(row => row.sourceVariance === null).length;
|
|
508
584
|
detail.sourceVarianceMismatchRows = output.records.filter(row => row.sourceVariance !== null && row.absoluteVariance !== null && row.sourceVariance !== row.absoluteVariance).length;
|
|
@@ -516,7 +592,8 @@ export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersion
|
|
|
516
592
|
payload.coverage[moduleId] ??= { start: null, end: null, status: 'unavailable', semantics: null };
|
|
517
593
|
}
|
|
518
594
|
}
|
|
519
|
-
|
|
595
|
+
const mapping = organizationMappingForSourceTemplates(decisions?.organizationMapping, state.uploads);
|
|
596
|
+
report.organizationMapping = applyOrganizationMapping(payload, mapping);
|
|
520
597
|
report.platforms = mergePlatforms(payload);
|
|
521
598
|
// 宴席按唯一上级补齐后,组织映射报告里的待确认路径同步收窄,避免后台继续提示已补齐的路径。
|
|
522
599
|
const banquetMapping = report.organizationMapping?.modules?.banquet;
|
|
@@ -526,23 +603,23 @@ export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersion
|
|
|
526
603
|
const pending = [...counts].map(([path, rows]) => ({ path: JSON.parse(path), rows })).sort((a, b) => b.rows - a.rows);
|
|
527
604
|
Object.assign(banquetMapping, { pendingPathCount: pending.length, pendingRows: pending.reduce((total, item) => total + item.rows, 0), pendingPaths: pending.slice(0, 500) });
|
|
528
605
|
if (!banquetMapping.configured && !pending.length) delete report.organizationMapping.modules.banquet;
|
|
529
|
-
const
|
|
530
|
-
if (
|
|
606
|
+
const mappingReport = report.organizationMapping;
|
|
607
|
+
if (mappingReport.status === 'partial' && !Object.values(mappingReport.modules).some(detail => detail.rejectedCount || detail.pendingPathCount)) mappingReport.status = mappingReport.contractVersion ? 'applied' : 'not-configured';
|
|
531
608
|
}
|
|
532
|
-
if (
|
|
533
|
-
report.reviewOrganizations = applyOrganizationRules(payload,
|
|
609
|
+
if (review) {
|
|
610
|
+
report.reviewOrganizations = applyOrganizationRules(payload, review);
|
|
534
611
|
for (const id of new Set(report.reviewOrganizations.conflicts.map(item => item.moduleId))) {
|
|
535
612
|
report.modules[id].reviewPending = true;
|
|
536
613
|
Object.assign(payload.modules[id], { state: 'unavailable', records: [], metrics: {}, reviewPending: true, reviewReason: '组织对应关系缺少日期依据或存在冲突,请返回导入检查处理。', reason: '待确认:组织对应关系存在冲突,请返回导入检查处理。' });
|
|
537
614
|
}
|
|
538
615
|
}
|
|
616
|
+
mergeMovement(payload);
|
|
539
617
|
payload.decisionContract = buildDecisionContract(payload, decisions, report.organizationMapping);
|
|
540
618
|
const resolved = new Set();
|
|
541
619
|
if (payload.decisionContract.terminalIdentity.status === 'confirmed') { resolved.add('crossTableTerminalIdentity'); delete payload.modules.terminal.metrics.movementCoverage; }
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
}
|
|
620
|
+
const amountSources = payload.decisionContract.crossTableMetrics.sources;
|
|
621
|
+
if (amountSources.invoice) resolved.add('invoiceMovementRelationship');
|
|
622
|
+
if (amountSources.inventory) resolved.add('inventorySellableMonthsEstimate');
|
|
546
623
|
if (payload.decisionContract.banquetOpeningSubset.status === 'not-guaranteed') resolved.add('banquetOpeningOverlap');
|
|
547
624
|
payload.pendingDecisions = payload.pendingDecisions.filter(item => !resolved.has(item));
|
|
548
625
|
for (const module of Object.values(payload.modules)) module.unavailable = module.unavailable.filter(item => !resolved.has(item));
|
|
@@ -36,7 +36,7 @@ export function createTerminalComponents({ T, g, model, shared }) {
|
|
|
36
36
|
}
|
|
37
37
|
function TerminalCardContent({ module }) {
|
|
38
38
|
const structure = module.structure;
|
|
39
|
-
if (!structure || noSource(module)) return el('div', { className: 'terminal-card-summary' }, el('p', { className: 'terminal-quality-note' }, '
|
|
39
|
+
if (!structure || noSource(module)) return el('div', { className: 'terminal-card-summary' }, el('p', { className: 'terminal-quality-note' }, '上传并校验终端签约与终端扫码来源后展示签约结构及有效终端。'));
|
|
40
40
|
const total = structure.totals || {};
|
|
41
41
|
return el('div', { className: 'terminal-card-summary' },
|
|
42
42
|
el('div', { className: 'terminal-card-effective' },
|
|
@@ -88,7 +88,7 @@ export function createTerminalComponents({ T, g, model, shared }) {
|
|
|
88
88
|
el('span', { className: 'terminal-legend-item' }, '颜色深浅', el('span', { className: 'terminal-legend-scale', 'aria-hidden': true }, ...[.02, .12, .25, .45, .7, 1].map(value => el('i', { key: value, style: { background: heat(value).color } }))), mode === 'effective' ? '= 本品系有效率' : mode === 'share' ? '= 本行协议占比' : '= 协议数 / 最大格协议数'),
|
|
89
89
|
el('span', { className: 'terminal-legend-item' }, el('i', { className: 'terminal-legend-hatch', 'aria-hidden': true }), '来源未观察到此档'),
|
|
90
90
|
el('span', {}, '点击格子 → 筛选下方终端明细'),
|
|
91
|
-
el('span', {}, '有效 = 该终端在本品系 7
|
|
91
|
+
el('span', {}, '有效 = 该终端在本品系 7 月以来扫码净件数 ≥ 1 件'),
|
|
92
92
|
),
|
|
93
93
|
el('p', { className: 'terminal-caution' }, '同一星级在不同品系代表的规模不同,请按行阅读。列合计仅供数量参考,不代表同等规模;斜纹表示当前上传来源未观察到此档,不据此判断业务上未设该星级。'),
|
|
94
94
|
);
|
|
@@ -175,8 +175,8 @@ export function createTerminalComponents({ T, g, model, shared }) {
|
|
|
175
175
|
}
|
|
176
176
|
function TopTerminals({ structure }) {
|
|
177
177
|
const rows = (structure.topTerminals || []).filter(row => finite(row.cases)).slice(0, 10);
|
|
178
|
-
return el('section', { className: 'chart-section terminal-block', 'aria-label': '
|
|
179
|
-
el(Heading, { title: '
|
|
178
|
+
return el('section', { className: 'chart-section terminal-block', 'aria-label': '签约品系扫码 Top 终端' },
|
|
179
|
+
el(Heading, { title: '签约品系扫码 Top 终端', note: '按已签品系扫码净件数排序 · 前 10 家' }),
|
|
180
180
|
el('div', { className: 'preview-table-wrap' }, el('table', { className: 'terminal-data-table terminal-top-table' },
|
|
181
181
|
el('colgroup', {}, ...['name', 'office', 'series', 'star', 'cases'].map(key => el('col', { key, className: `terminal-col-${key}` }))),
|
|
182
182
|
el('thead', {}, el('tr', {}, ...['终端', '办事处', '签约品系与星级', '综合档位', '净件数'].map(label => el('th', { key: label, scope: 'col' }, label)))),
|
|
@@ -200,7 +200,7 @@ export function createTerminalComponents({ T, g, model, shared }) {
|
|
|
200
200
|
selection && el('div', { className: 'terminal-filter-chip' }, `${selection.name} · ${starName(selection.star)}`, el('button', { type: 'button', className: 'terminal-clear', onClick: clear }, '清除筛选')),
|
|
201
201
|
el('div', { className: 'preview-table-wrap' }, el('table', { className: 'terminal-data-table terminal-detail-table' },
|
|
202
202
|
el('colgroup', {}, ...['name', 'org', 'series', 'star', 'status', 'cases'].map(key => el('col', { key, className: `terminal-col-${key}` }))),
|
|
203
|
-
el('thead', {}, el('tr', {}, ...['终端', '组织', '签约品系与星级', '综合档位', '是否有效', '
|
|
203
|
+
el('thead', {}, el('tr', {}, ...['终端', '组织', '签约品系与星级', '综合档位', '是否有效', '签约品系扫码净件数'].map(label => el('th', { key: label, scope: 'col', className: label === '签约品系动销净件数' ? 'terminal-number' : undefined }, label)))),
|
|
204
204
|
el('tbody', {}, ...rows.slice(safePage * pageSize, (safePage + 1) * pageSize).map(row => el('tr', { key: row.code },
|
|
205
205
|
el('td', { className: 'terminal-detail-code' }, el('strong', {}, row.name || row.code || '终端名称未提供'), el('small', {}, row.code || '终端编码未提供')),
|
|
206
206
|
el('td', { className: 'terminal-org-cell' }, el('span', { className: 'terminal-org-text', title: row.orgLabel || '组织未提供' }, row.orgShortLabel || '组织未提供')),
|
|
@@ -235,7 +235,7 @@ export function createTerminalComponents({ T, g, model, shared }) {
|
|
|
235
235
|
),
|
|
236
236
|
notes.length > 0 && el('div', { className: 'rules-pending' }, el('h3', {}, '当前来源状态'), ...notes.map((note, index) => el('p', { key: index }, note))),
|
|
237
237
|
el('div', { className: 'preview-provenance' }, el('h3', {}, '本次来源版本'),
|
|
238
|
-
module.source ? el('dl', {}, el('dt', {}, '文件'), el('dd', {}, module.source.originalName), el('dt', {}, '上传版本'), el('dd', {}, module.source.uploadId), el('dt', {}, 'SHA-256'), el('dd', {}, module.source.sha256), el('dt', {}, '签约范围'), el('dd', {}, module.period), el('dt', {}, '
|
|
238
|
+
module.source ? el('dl', {}, el('dt', {}, '文件'), el('dd', {}, module.source.originalName), el('dt', {}, '上传版本'), el('dd', {}, module.source.uploadId), el('dt', {}, 'SHA-256'), el('dd', {}, module.source.sha256), el('dt', {}, '签约范围'), el('dd', {}, module.period), el('dt', {}, '终端扫码截止'), el('dd', {}, window.sourceEnd || '未提供')) : el('p', {}, '当前没有有效上传来源。'),
|
|
239
239
|
el('p', {}, `生成时间:${model.payload.generatedAt}`),
|
|
240
240
|
),
|
|
241
241
|
);
|
|
@@ -258,7 +258,7 @@ export function createTerminalComponents({ T, g, model, shared }) {
|
|
|
258
258
|
metric('多品系终端', finite(multi.two) && finite(multi.threePlus) ? multi.two + multi.threePlus : null, '家', `星级不一致 ${number(multi.inconsistent)} 家`),
|
|
259
259
|
];
|
|
260
260
|
return el('section', { className: 'details-panel v10-details v10-terminal', 'aria-label': '终端签约详细信息', style: { '--detail-accent': module.color } },
|
|
261
|
-
el('div', { className: 'detail-title' }, el('div', {}, el('span', { className: 'eyebrow' }, 'TERMINAL NETWORK'), el('h2', {}, '终端签约分析'), el('p', {}, '
|
|
261
|
+
el('div', { className: 'detail-title' }, el('div', {}, el('span', { className: 'eyebrow' }, 'TERMINAL NETWORK'), el('h2', {}, '终端签约分析'), el('p', {}, '签约节奏、品系星级结构、组织分布与已签品系扫码达标情况。')), el('span', { className: 'scope-tag' }, '筛选联动')),
|
|
262
262
|
el('div', { className: 'detail-context' }, el('span', {}, model.scope(filters)), el('span', {}, `签约截至 ${structure?.window?.end || filters.month}`), el('span', {}, '不随产品筛选')),
|
|
263
263
|
(!structure || noSource(module)) && el('p', { className: 'terminal-empty' }, '当前没有可用的签约来源。请上传并校验签约数据后重新生成看板。'),
|
|
264
264
|
structure && !noSource(module) && el('div', { className: 'analysis-content inv-analysis sg-analysis' },
|
|
@@ -98,8 +98,8 @@ export function buildTerminalStructure({ terminalRows = [], movementRows = [], a
|
|
|
98
98
|
'签约表仅使用 A–AJ;AJ 之后的字段不参与计算。协议数沿用已确认的来源去重结果,终端按网点编号去重。',
|
|
99
99
|
'按签约日期截至所选月末累计,不额外推定审批、关闭状态或协议有效期筛选。',
|
|
100
100
|
`有效终端:${start} 至所选月末,任一已签约品系的扫码净件数达到 1 件;采购与退货按来源正负号相加。`,
|
|
101
|
-
'
|
|
102
|
-
'矩阵格子及品系行:有效 = 该终端在本品系 7
|
|
101
|
+
'签约与有效终端均不随产品筛选;终端扫码仅按原始终端编码及完整组织路径匹配。',
|
|
102
|
+
'矩阵格子及品系行:有效 = 该终端在本品系 7 月以来扫码净件数 ≥ 1 件;有效协议数除以该格或该行协议数。终端整体有效率仍按任一已签品系达标的去重终端计算。',
|
|
103
103
|
'其他品系分别匹配酱香吞之乎、沱牌曲酒(中国名酒)、沱牌特级(2024版),不同原品系分别判断;舍之道礼盒不作为君道品系的扫码。',
|
|
104
104
|
];
|
|
105
105
|
const available = terminalState !== 'unavailable', movementAvailable = movementState !== 'unavailable';
|
|
@@ -109,9 +109,9 @@ export function buildTerminalStructure({ terminalRows = [], movementRows = [], a
|
|
|
109
109
|
const countPending = !end || unknownDates || missingCodes;
|
|
110
110
|
if (unknownDates) notes.push('存在签约日期缺失记录,无法完整判断累计范围;展示已定位记录,汇总保持待确认。');
|
|
111
111
|
if (missingCodes) notes.push('存在网点编号缺失记录,终端去重数与有效率待确认。');
|
|
112
|
-
if (!movementAvailable) notes.push('
|
|
113
|
-
if (identityState !== 'confirmed') notes.push('
|
|
114
|
-
if (sourceEnd && end && sourceEnd < end) notes.push(
|
|
112
|
+
if (!movementAvailable) notes.push('未接入有效扫码来源,有效终端保持待确认。');
|
|
113
|
+
if (identityState !== 'confirmed') notes.push('当前上传版本的签约网点编号与终端扫码售点编码关联尚未确认,有效终端保持待确认。');
|
|
114
|
+
if (sourceEnd && end && sourceEnd < end) notes.push(`扫码来源最新记录为 ${sourceEnd},所选月份未提供的后续日期不外推。`);
|
|
115
115
|
|
|
116
116
|
const scanMap = new Map(), incompleteOrg = new Set();
|
|
117
117
|
let missingScanCodes = false;
|
|
@@ -55,7 +55,7 @@ export function createV10Components({ T, g, model, icons, Pn }) {
|
|
|
55
55
|
:kind==='inventory' ? inventoryVisit ? '最近一次已知盘点 · 单位:瓶' : '当前导出盘点记录 · 单位:万元'
|
|
56
56
|
: m.period;
|
|
57
57
|
const negative=hero?m.extra[2]:null;
|
|
58
|
-
const count=
|
|
58
|
+
const count=kind==='movement'?v.kpis[1]:null;
|
|
59
59
|
const ratio=kind==='movement'?m.crossMetrics.find(x=>x.key==='invoiceMovementYtdRatio'):null;
|
|
60
60
|
return el('article',{className:`metric-card ${hero?'hero-card':'support-card'} ${kind} ${compact?'compact-card':''}`,style:{'--accent':m.color},
|
|
61
61
|
onClick:()=>open(kind),onKeyDown:event=>{if(event.target===event.currentTarget&&['Enter',' '].includes(event.key)){event.preventDefault();open(kind);}},role:compact?undefined:'button',tabIndex:compact?undefined:0,'aria-label':`查看${m.title}详情`},
|
|
@@ -65,7 +65,7 @@ export function createV10Components({ T, g, model, icons, Pn }) {
|
|
|
65
65
|
hero && el(g.Fragment,{},
|
|
66
66
|
el('div',{className:'inv-sub'},el('span',{className:'inv-ytd'},'年内截至所选月累计 ',el('b',{},money(ytd)),available(ytd)?' 万元':'')),
|
|
67
67
|
el(CardMonths,{module:m,view:v,compact,filters}),
|
|
68
|
-
el('div',{className:'card-bottom inv-bottom'},kind!=='invoice'&&el('span',{}
|
|
68
|
+
el('div',{className:'card-bottom inv-bottom'},kind!=='invoice'&&el('span',{},`动销件数 ${available(count)?model.format(count.value,0,1):number(count)}${available(count)?' 件':''}`),
|
|
69
69
|
el('span',{},`负金额 ${money(negative)}${available(negative)?' 万':''}`),
|
|
70
70
|
kind==='invoice'?(att=>available(att)?el('span',{title:att.note||''},`季度达成 ${model.format(att.value,1,1)}%`):el('span',{className:'inv-pending',title:att?.reason||'未上传经营目标'},m.targets?.available?'达成率 · 待确认':'达成率 · 未上传目标'))(m.targets?.quarter?.attainment):el('span',{},`累计动销/开票 ${number(ratio)}${available(ratio)?'%':''}`))),
|
|
71
71
|
kind==='opening' && el('div',{className:'inv-sub'},el('span',{className:'inv-ytd'},'开瓶 ',el('b',{'data-state':m.main.state},number(m.main)),available(m.main)?' 瓶':'')),
|