dsh-data-dashboard 0.1.5 → 0.1.7
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 +32 -13
- package/backend/modules/banquet/index.mjs +11 -33
- package/backend/modules/distributor/index.mjs +28 -0
- package/backend/modules/opening/index.mjs +1 -1
- package/backend/modules/tunzhihu/index.mjs +27 -0
- package/backend/modules/zang10/index.mjs +30 -0
- package/backend/modules.mjs +4 -1
- package/backend/public/admin.js +15 -9
- package/backend/public/board.js +1 -1
- package/backend/real-data/generate-dashboard.mjs +11 -2
- package/backend/real-data/source-payload.mjs +116 -19
- package/backend/real-data/v10-components.mjs +5 -4
- package/backend/real-data/v10-details.mjs +27 -13
- package/backend/real-data/v10-model.mjs +59 -12
- package/backend/real-data/v10-overview-data.mjs +49 -14
- package/backend/real-data/v10-overview.css +37 -18
- package/backend/real-data/v10-overview.mjs +88 -75
- package/backend/real-data/v10-presentation.mjs +44 -30
- package/backend/real-data/v10-template.mjs +41 -5
- package/backend/review-engine.mjs +13 -2
- package/backend/server.mjs +1 -1
- package/build-manifest.json +28 -25
- package/lib/tool-definitions.mjs +2 -2
- package/lib/tools.mjs +5 -1
- package/package.json +1 -1
|
@@ -9,18 +9,20 @@ import { normalizeHeader, moduleById } from '../modules.mjs';
|
|
|
9
9
|
import { applyOrganizationMapping, buildDecisionContract } from './organization-mapping.mjs';
|
|
10
10
|
import { processInventoryHistory } from './inventory-history.mjs';
|
|
11
11
|
import { targetColumns } from '../modules/target/index.mjs';
|
|
12
|
-
import { inspectRows, resolveInspection, applyDuplicateDecisions, applyOrganizationRules } from '../review-engine.mjs';
|
|
12
|
+
import { inspectRows, resolveInspection, applyDuplicateDecisions, applyOrganizationRules, monthDay } from '../review-engine.mjs';
|
|
13
13
|
import { lineageShas } from '../incremental/flow.mjs';
|
|
14
14
|
|
|
15
|
-
const MODULES = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet', 'target'];
|
|
15
|
+
const MODULES = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet', 'target', 'zang10', 'tunzhihu', 'distributor'];
|
|
16
|
+
// 2026-11-27:两个平台的订单并入发票销售;分销商动销只作动销参考,不并入任何合计。
|
|
17
|
+
export const PLATFORM_MODULES = ['zang10', 'tunzhihu'];
|
|
16
18
|
const PENDING = {
|
|
17
19
|
invoice: ['invoiceTarget', 'invoiceQuantityConversion'],
|
|
18
20
|
movement: ['invoiceMovementRelationship'],
|
|
19
21
|
opening: ['openingMovementConversion', 'banquetOpeningOverlap'],
|
|
20
22
|
terminal: ['crossTableTerminalIdentity'],
|
|
21
23
|
inventory: ['inventoryHistory', 'inventoryValuationBasis', 'inventorySellableMonthsEstimate'],
|
|
22
|
-
banquet: ['
|
|
23
|
-
target: [],
|
|
24
|
+
banquet: ['banquetOpeningOverlap'],
|
|
25
|
+
target: [], zang10: [], tunzhihu: [], distributor: [],
|
|
24
26
|
};
|
|
25
27
|
const metric = (value, unit, status = 'available', reason) => ({ value, status, unit, ...(reason ? { reason } : {}) });
|
|
26
28
|
const text = value => value === null || value === undefined ? '' : String(value).trim();
|
|
@@ -88,10 +90,11 @@ function organization(get, moduleId) {
|
|
|
88
90
|
inventory: ['大区名称', '办事处名称', '单元名称'],
|
|
89
91
|
banquet: ['大区', '办事处', '主任单元'],
|
|
90
92
|
target: ['大区', '办事处', '主任单元'],
|
|
93
|
+
zang10: ['大区', '办事处', '客户主任单元'], tunzhihu: ['大区', '办事处', '主任单元'], distributor: ['大区', '办事处', '客户主任单元'],
|
|
91
94
|
}[moduleId];
|
|
92
95
|
const org = {
|
|
93
96
|
marketingCompany: text(get('营销公司名称')), businessUnit: text(get('事业部名称', '事业部')),
|
|
94
|
-
theater: text(get('战区名称')), region: text(get(headers[0])), office: text(get(headers[1])), unit: text(get(headers[2])),
|
|
97
|
+
theater: text(get('战区名称', '战区')), region: text(get(headers[0])), office: text(get(headers[1])), unit: text(get(headers[2])),
|
|
95
98
|
};
|
|
96
99
|
return { org, orgPath: Object.values(org), orgKey: JSON.stringify(Object.values(org)) };
|
|
97
100
|
}
|
|
@@ -106,14 +109,30 @@ function normalizedRecord(moduleId, row, workbook) {
|
|
|
106
109
|
const quantityUnit = text(get('单品单位')), quantity = number(get('扫码数量(瓶)'));
|
|
107
110
|
return { ...common, ...product(), ...dealer(), variety: text(get('品种名称')), date: parseDate(get('扫码日期')), amount: number(get('扫码金额')), quantity, quantityUnit, bottles: quantityUnit === '瓶' ? quantity : null, boxes: quantityUnit === '盒' ? quantity : null, cases: number(get('扫码件数')), terminalCode: text(get('售点编码')), terminalName: text(get('售点名称')), channel: text(get('渠道类型')), movementType: text(get('出入库名称')), orderCode: text(get('订单编码')) };
|
|
108
111
|
}
|
|
109
|
-
if (moduleId === 'opening') return { ...common, date: parseDate(get('抽奖日期')), bottles: number(get('开瓶瓶数')), amount: number(get('开瓶金额')), city: text(get('开瓶城市')), amountMeaning: '
|
|
112
|
+
if (moduleId === 'opening') return { ...common, date: parseDate(get('抽奖日期')), bottles: number(get('开瓶瓶数')), amount: number(get('开瓶金额')), city: text(get('开瓶城市')), amountMeaning: '开瓶金额', amountUnit: '元' };
|
|
113
|
+
if (moduleId === 'zang10') {
|
|
114
|
+
// 按订单归属年月归月;订单所在日期落在归属月内时保留到日,否则记为归属月 1 日。
|
|
115
|
+
const month = monthDay(get('订单归属年月'), workbook.properties.date1904);
|
|
116
|
+
const y = number(get('订单所在年')), m = number(get('订单所在月')), d = number(get('订单所在日'));
|
|
117
|
+
const day = y && m && d ? date(`${y}-${m}-${d}`) : null;
|
|
118
|
+
return { ...common, platform: 'zang10', date: month && day && day.slice(0, 7) === month.slice(0, 7) ? day : month, amount: number(get('订单金额(元)')),
|
|
119
|
+
productCode: '', productName: text(get('购货产品标准名称')), brand: null, category: null, dealerCode: '', dealerName: text(get('购货经销商名称')), dealerType: text(get('性质')),
|
|
120
|
+
documentType: text(get('账务类型')), documentCode: text(get('订单编号')), documentLine: '' };
|
|
121
|
+
}
|
|
122
|
+
if (moduleId === 'tunzhihu') return { ...common, platform: 'tunzhihu', date: parseDate(get('业务日期')), amount: number(get('发票金额')),
|
|
123
|
+
productCode: '', productName: text(get('产品名称')), brand: null, category: null, dealerCode: '', dealerName: text(get('销管客户名称', 'BI/财务系统客户名称')), dealerType: '',
|
|
124
|
+
documentType: text(get('单据类型')), documentCode: text(get('订单编号')), documentLine: '' };
|
|
125
|
+
if (moduleId === 'distributor') return { ...common, ...product(), date: parseDate(get('动销日期 (日)')), amount: number(get('总动销金额')), quantity: number(get('总动销数量')),
|
|
126
|
+
distributorName: text(get('分销商名称')), distributorCode: text(get('分销商编码')), dealerName: text(get('经销商名称')), documentType: text(get('单据类型')) };
|
|
127
|
+
if (moduleId === 'banquet') return { ...common, date: monthDay(get('执行时间(月)'), workbook.properties.date1904), events: number(get('执行场次')), bottles: number(get('开瓶数量')),
|
|
128
|
+
dealerName: text(get('经销商名称')), variety: text(get('用酒品种')) };
|
|
110
129
|
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('签约状态')) };
|
|
111
130
|
if (moduleId === 'inventory') {
|
|
112
131
|
const counted = number(get('库存瓶数(盘点)')), system = number(get('提交时实时库存数(系统)'));
|
|
113
132
|
const signedVariance = counted === null || system === null ? null : sum([counted, -system]);
|
|
114
133
|
return { ...common, ...product(), ...dealer(), date: parseDate(get('提交时间')), submittedAt: get('提交时间'), stocktakeCode: text(get('盘点编码')), counted, system, countAmount: number(get('盘点库存金额')), stockAmount: number(get('盘点库存金额')), systemAmount: number(get('提交时实时库存数金额')), sourceVariance: number(get('偏差数量')), absoluteVariance: signedVariance === null ? null : Math.abs(signedVariance), signedVariance, varianceFlag: text(get('是否存在盘点偏差')), safety: text(get('安全库存')) };
|
|
115
134
|
}
|
|
116
|
-
|
|
135
|
+
throw new Error(`未知板块:${moduleId}`);
|
|
117
136
|
}
|
|
118
137
|
// One target record per filled target cell (wide layout) or per row (long layout).
|
|
119
138
|
function targetRecords(row, headers, workbook) {
|
|
@@ -152,7 +171,8 @@ function totals(records, field, unit) {
|
|
|
152
171
|
function computeMetrics(moduleId, records) {
|
|
153
172
|
const result = { records: metric(records.length, '行') };
|
|
154
173
|
const fields = {
|
|
155
|
-
invoice: { amount: '元' }, movement: { amount: '元', cases: '源件数' }, opening: { bottles: '瓶', amount: '
|
|
174
|
+
invoice: { amount: '元' }, movement: { amount: '元', cases: '源件数' }, opening: { bottles: '瓶', amount: '元(开瓶金额)' },
|
|
175
|
+
zang10: { amount: '元' }, tunzhihu: { amount: '元' }, distributor: { amount: '元' },
|
|
156
176
|
terminal: {}, target: {}, inventory: { counted: '瓶(本次导出记录合计)', system: '瓶(本次导出记录合计)', countAmount: '元', systemAmount: '元', absoluteVariance: '瓶' }, banquet: { events: '场', bottles: '瓶' },
|
|
157
177
|
}[moduleId];
|
|
158
178
|
for (const [field, unit] of Object.entries(fields)) result[field] = totals(records, field, unit);
|
|
@@ -170,7 +190,6 @@ function computeMetrics(moduleId, records) {
|
|
|
170
190
|
result.terminalCount = metric(missingCode ? null : new Set(records.map(row => row.terminalCode)).size, '终端', missingCode ? 'missing' : 'available');
|
|
171
191
|
result.agreementCount = metric(records.length, '协议');
|
|
172
192
|
}
|
|
173
|
-
if (moduleId === 'banquet') result.reward = metric(null, '元', 'pending', '奖励字段的可加总含义尚未确认');
|
|
174
193
|
if (moduleId === 'target') {
|
|
175
194
|
result.invalidRows = metric(records.filter(row => row.issue).length, '行');
|
|
176
195
|
for (const [, id] of TARGET_METRICS) result[`${id}Rows`] = metric(records.filter(row => !row.issue && row.metric === id).length, '行');
|
|
@@ -179,13 +198,13 @@ function computeMetrics(moduleId, records) {
|
|
|
179
198
|
}
|
|
180
199
|
function coverage(moduleId, records, decisions, sha256) {
|
|
181
200
|
if (moduleId === 'banquet') {
|
|
182
|
-
|
|
183
|
-
const
|
|
184
|
-
const
|
|
185
|
-
return { start:
|
|
201
|
+
// 宴席按执行月份:期间为最早月份 1 日到最晚月份的月末。
|
|
202
|
+
const dates = records.map(row => row.date).filter(Boolean).sort(), last = dates.at(-1);
|
|
203
|
+
const end = last ? new Date(Date.UTC(Number(last.slice(0, 4)), Number(last.slice(5, 7)), 0)).toISOString().slice(0, 10) : null;
|
|
204
|
+
return { start: dates[0] ?? null, end, semantics: 'execution-month', status: dates.length ? 'confirmed' : 'missing', productFilter: false };
|
|
186
205
|
}
|
|
187
206
|
const dates = records.map(row => row.date).filter(Boolean).sort();
|
|
188
|
-
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' })[moduleId], status: dates.length === records.length ? 'observed' : 'partial', productFilter: ['invoice', 'movement', 'inventory'].includes(moduleId) };
|
|
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) };
|
|
189
208
|
}
|
|
190
209
|
function comparable(value, expected) {
|
|
191
210
|
if (typeof expected === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(expected)) return date(value) === expected;
|
|
@@ -269,6 +288,70 @@ function diagnostics(payload) {
|
|
|
269
288
|
return { organizationAliases: { collisionCount: collisions.length, candidates: collisions }, terminalIdentity: { siteCodes: siteOrgs.size, outletCodes: outletOrgs.size, intersectionCount: overlap.length, organizationInconsistentCount: inconsistent.length, inconsistentCodes: inconsistent, status: 'diagnostic-only-not-an-identity-confirmation' }, productClassification: { mappedRows: mapped, unmappedRows: unmapped, conflictRows: conflicted, conflictingCodes: [...productMap].filter(([, values]) => values.size > 1).map(([code]) => code) } };
|
|
270
289
|
}
|
|
271
290
|
|
|
291
|
+
/**
|
|
292
|
+
* 藏10、吞之乎平台订单并入发票(2026-11-27 用户确认)。平台表只有大区 / 办事处 / 主任单元:
|
|
293
|
+
* 按名称在其他来源的完整组织路径里找唯一上级补齐,找不到或不唯一时保留“上级未提供”,不猜。
|
|
294
|
+
* 产品按完全相同的产品名称从发票、分销商动销里取唯一品牌 / 品类,否则为未映射。
|
|
295
|
+
* 平台行仍留在各自模块里,只是复制一份带 platform 标记的行进入发票。
|
|
296
|
+
*/
|
|
297
|
+
const productKey = name => String(name ?? '').normalize('NFKC').replace(/\s+/g, '').toLowerCase().replace(/(?<=[\dl])[x*](?=\d)/g, '×');
|
|
298
|
+
function mergePlatforms(payload) {
|
|
299
|
+
const invoice = payload.modules.invoice, report = { merged: {}, completedPaths: 0, unresolvedPaths: 0 };
|
|
300
|
+
const parents = new Map(), products = new Map();
|
|
301
|
+
for (const id of ['invoice', 'movement', 'terminal', 'distributor']) for (const row of payload.modules[id]?.records || []) {
|
|
302
|
+
const path = row.orgPath;
|
|
303
|
+
if (!Array.isArray(path) || path.slice(0, 3).some(value => !value) || path.slice(3).some(value => !value)) continue;
|
|
304
|
+
// 完整下级路径与大区本身各记一份上级;下级路径找不到(如新开主任单元)时退到大区级唯一上级。
|
|
305
|
+
for (const key of [JSON.stringify(path.slice(3)), JSON.stringify(['region', path[3]])]) {
|
|
306
|
+
const set = parents.get(key) ?? new Map();
|
|
307
|
+
set.set(JSON.stringify(path.slice(0, 3)), path.slice(0, 3)); parents.set(key, set);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
for (const id of ['invoice', 'distributor']) for (const row of payload.modules[id]?.records || []) {
|
|
311
|
+
if (!row.productName || !row.brand || !row.category) continue;
|
|
312
|
+
// 原名精确匹配优先;再按规范化名称(去空白、x/×、全半角括号)匹配,仍要求唯一品类。
|
|
313
|
+
for (const name of [row.productName, `≈${productKey(row.productName)}`]) {
|
|
314
|
+
const set = products.get(name) ?? new Map(); set.set(JSON.stringify([row.brand, row.category]), { brand: row.brand, category: row.category }); products.set(name, set);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
const resolved = new Map();
|
|
318
|
+
const complete = path => {
|
|
319
|
+
if (!path.slice(0, 3).some(value => !value)) return path;
|
|
320
|
+
const key = JSON.stringify(path.slice(3));
|
|
321
|
+
if (!resolved.has(key)) {
|
|
322
|
+
const candidates = parents.get(key) ?? (path[3] ? parents.get(JSON.stringify(['region', path[3]])) : null);
|
|
323
|
+
const found = [...(candidates?.values() ?? [])].filter(prefix => !path[2] || prefix[2] === path[2]);
|
|
324
|
+
resolved.set(key, found.length === 1 ? found[0] : null);
|
|
325
|
+
if (found.length === 1) report.completedPaths++; else report.unresolvedPaths++;
|
|
326
|
+
}
|
|
327
|
+
const prefix = resolved.get(key);
|
|
328
|
+
return prefix ? [...prefix, ...path.slice(3)] : path;
|
|
329
|
+
};
|
|
330
|
+
const orgOf = path => Object.fromEntries(['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'].map((field, index) => [field, path[index]]));
|
|
331
|
+
// 宴席固定模板没有营销公司、事业部、战区列:已确认的组织映射之后,同样按唯一上级补齐(不唯一则保留空)。
|
|
332
|
+
if (payload.modules.banquet?.state !== 'unavailable') for (const row of payload.modules.banquet?.records || []) {
|
|
333
|
+
if (!Array.isArray(row.orgPath)) continue;
|
|
334
|
+
const path = complete(row.orgPath);
|
|
335
|
+
if (path !== row.orgPath) { row.orgPath = path; row.org = orgOf(path); row.orgKey = JSON.stringify(path); report.banquetCompleted = (report.banquetCompleted || 0) + 1; }
|
|
336
|
+
}
|
|
337
|
+
for (const id of PLATFORM_MODULES) {
|
|
338
|
+
const module = payload.modules[id];
|
|
339
|
+
if (!module || module.state === 'unavailable' || !module.records.length) continue;
|
|
340
|
+
if (invoice.state === 'unavailable') { (module.warnings ||= []).push('公司发票来源不可用,平台订单暂未并入发票。'); continue; }
|
|
341
|
+
const rows = module.records.map(row => {
|
|
342
|
+
const path = complete(row.orgPath);
|
|
343
|
+
const product = products.get(row.productName) ?? products.get(`≈${productKey(row.productName)}`);
|
|
344
|
+
const mapped = product?.size === 1 ? [...product.values()][0] : { brand: null, category: null };
|
|
345
|
+
return { ...row, org: orgOf(path), orgPath: path, orgKey: JSON.stringify(path), ...mapped };
|
|
346
|
+
});
|
|
347
|
+
invoice.records.push(...rows);
|
|
348
|
+
report.merged[id] = { rows: rows.length, amount: sum(rows.map(row => row.amount)) };
|
|
349
|
+
(payload.platforms ||= {})[id] = { rows: rows.length, coverage: payload.coverage[id] ?? null, source: payload.sources[id] ?? null };
|
|
350
|
+
}
|
|
351
|
+
if (Object.keys(report.merged).length) invoice.metrics = computeMetrics('invoice', invoice.records);
|
|
352
|
+
return report;
|
|
353
|
+
}
|
|
354
|
+
|
|
272
355
|
/** Read an immutable active-upload snapshot without changing the source store.
|
|
273
356
|
* Decisions are external: either the original invoice decision object, or
|
|
274
357
|
* { invoice: <object>, banquet: { sourceSha256, start, end, includeOrganizationPlaceholders: true } }.
|
|
@@ -398,6 +481,13 @@ export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersion
|
|
|
398
481
|
output.unavailable = ['inventoryCountAmount', 'inventoryAmountDifference', 'inventorySellableMonthsEstimate', 'inventoryProductMapping', 'inventorySafetyStock'];
|
|
399
482
|
} else {
|
|
400
483
|
output.records = moduleId === 'target' ? included.flatMap(row => targetRecords(row, headers, workbook)) : included.map(row => normalizedRecord(moduleId, row, workbook));
|
|
484
|
+
if (moduleId === 'banquet') {
|
|
485
|
+
// 没有执行月份的行不归入任何月份;场次、开瓶都为 0 的是组织占位。
|
|
486
|
+
const undated = output.records.filter(row => !row.date), valued = undated.filter(row => row.events || row.bottles);
|
|
487
|
+
output.records = output.records.filter(row => row.date);
|
|
488
|
+
if (valued.length) detail.warnings.push(`${valued.length} 行没有执行月份却有数值(开瓶 ${valued.reduce((n, row) => n + (row.bottles || 0), 0)} 瓶),不归入任何月份、不计入。`);
|
|
489
|
+
detail.skippedPlaceholderRows = undated.length - valued.length;
|
|
490
|
+
}
|
|
401
491
|
output.metrics = computeMetrics(moduleId, output.records);
|
|
402
492
|
payload.coverage[moduleId] = coverage(moduleId, output.records, decisions, sha256);
|
|
403
493
|
detail.includedRows = included.length;
|
|
@@ -413,11 +503,6 @@ export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersion
|
|
|
413
503
|
detail.missingDates = ['banquet', 'target'].includes(moduleId) ? null : output.records.filter(row => row.date === null).length;
|
|
414
504
|
if (detail.missingDates) detail.warnings.push(`${detail.missingDates} 行日期无法确认,不归入任何月份。`);
|
|
415
505
|
if (moduleId === 'movement' && output.metrics.unknownUnitRows.value) detail.warnings.push('存在未确认单品单位,金额保留,数量不归为瓶或盒。');
|
|
416
|
-
if (moduleId === 'banquet' && payload.coverage[moduleId].status !== 'confirmed') { output.unavailable.push('banquetSourcePeriod'); detail.warnings.push('当前来源固定期间未确认,不伪造日期。'); }
|
|
417
|
-
if (moduleId === 'banquet' && !(decisions?.banquet?.sourceSha256 === sha256 && decisions.banquet.includeOrganizationPlaceholders === true)) {
|
|
418
|
-
for (const [field, unit] of [['events', '场'], ['bottles', '瓶']]) output.metrics[field] = metric(null, unit, 'pending', '新来源的组织占位和汇总行粒度尚未核对,保留原值但不直接累加');
|
|
419
|
-
output.unavailable.push('banquetSourceGrain'); detail.warnings.push('宴席汇总粒度确认必须绑定当前来源 SHA。');
|
|
420
|
-
}
|
|
421
506
|
if (moduleId === 'inventory' && !visitInventory) {
|
|
422
507
|
detail.sourceVarianceNullRows = output.records.filter(row => row.sourceVariance === null).length;
|
|
423
508
|
detail.sourceVarianceMismatchRows = output.records.filter(row => row.sourceVariance !== null && row.absoluteVariance !== null && row.sourceVariance !== row.absoluteVariance).length;
|
|
@@ -432,6 +517,18 @@ export async function buildSourcePayload({ dataDir, decisionsFile, sourceVersion
|
|
|
432
517
|
}
|
|
433
518
|
}
|
|
434
519
|
report.organizationMapping = applyOrganizationMapping(payload, decisions?.organizationMapping);
|
|
520
|
+
report.platforms = mergePlatforms(payload);
|
|
521
|
+
// 宴席按唯一上级补齐后,组织映射报告里的待确认路径同步收窄,避免后台继续提示已补齐的路径。
|
|
522
|
+
const banquetMapping = report.organizationMapping?.modules?.banquet;
|
|
523
|
+
if (report.platforms.banquetCompleted && banquetMapping) {
|
|
524
|
+
const counts = new Map();
|
|
525
|
+
for (const row of payload.modules.banquet.records) if (row.orgPath.slice(0, 3).some(value => !value)) { const key = JSON.stringify(row.originalOrgPath ?? row.orgPath); counts.set(key, (counts.get(key) || 0) + 1); }
|
|
526
|
+
const pending = [...counts].map(([path, rows]) => ({ path: JSON.parse(path), rows })).sort((a, b) => b.rows - a.rows);
|
|
527
|
+
Object.assign(banquetMapping, { pendingPathCount: pending.length, pendingRows: pending.reduce((total, item) => total + item.rows, 0), pendingPaths: pending.slice(0, 500) });
|
|
528
|
+
if (!banquetMapping.configured && !pending.length) delete report.organizationMapping.modules.banquet;
|
|
529
|
+
const mapping = report.organizationMapping;
|
|
530
|
+
if (mapping.status === 'partial' && !Object.values(mapping.modules).some(detail => detail.rejectedCount || detail.pendingPathCount)) mapping.status = mapping.contractVersion ? 'applied' : 'not-configured';
|
|
531
|
+
}
|
|
435
532
|
if (state.review) {
|
|
436
533
|
report.reviewOrganizations = applyOrganizationRules(payload, state.review);
|
|
437
534
|
for (const id of new Set(report.reviewOrganizations.conflicts.map(item => item.moduleId))) {
|
|
@@ -45,13 +45,13 @@ export function createV10Components({ T, g, model, icons, Pn }) {
|
|
|
45
45
|
const m=data.modules[kind],meta=Pn[kind],hero=['invoice','movement'].includes(kind);
|
|
46
46
|
const v=kind==='terminal'?null:presentation.describe(kind,data,filters);
|
|
47
47
|
const inventoryVisit=kind==='inventory'&&m.inventoryMode==='visit-history';
|
|
48
|
-
const main=kind==='inventory'?(inventoryVisit?v.kpis.find(item=>item.key==='inventoryCounted'):{...v.kpis.find(item=>item.key==='inventoryCountAmount'),label:'当前导出所选记录盘点金额'}):m.main;
|
|
48
|
+
const main=kind==='inventory'?(inventoryVisit?v.kpis.find(item=>item.key==='inventoryCounted'):{...v.kpis.find(item=>item.key==='inventoryCountAmount'),label:'当前导出所选记录盘点金额'}):kind==='opening'?v.kpis[0]:m.main;
|
|
49
49
|
const inventorySystem=kind==='inventory'?v.kpis.find(item=>item.key===(inventoryVisit?'inventorySystem':'inventorySystemAmount')):null;
|
|
50
50
|
const inventoryDifference=kind==='inventory'?v.kpis.find(item=>item.key===(inventoryVisit?'inventoryQuantityDifference':'inventoryAmountDifference')):null;
|
|
51
51
|
const display=main.unit==='元'?money(main):number(main);
|
|
52
52
|
const ytd=hero?m.extra[0]:null;
|
|
53
53
|
const foot = kind==='opening' ? '组织口径 · 不随产品筛选'
|
|
54
|
-
:kind==='banquet' ? `${m.period} ·
|
|
54
|
+
:kind==='banquet' ? `${m.period} · 按执行月份`
|
|
55
55
|
:kind==='inventory' ? inventoryVisit ? '最近一次已知盘点 · 单位:瓶' : '当前导出盘点记录 · 单位:万元'
|
|
56
56
|
: m.period;
|
|
57
57
|
const negative=hero?m.extra[2]:null;
|
|
@@ -65,9 +65,10 @@ 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'},el('span',{}
|
|
68
|
+
el('div',{className:'card-bottom inv-bottom'},kind!=='invoice'&&el('span',{},`扫码终端 ${number(count)}${available(count)?' 家':''}`),
|
|
69
69
|
el('span',{},`负金额 ${money(negative)}${available(negative)?' 万':''}`),
|
|
70
|
-
kind==='invoice'?(att=>available(att)?el('span',{title:att.note||''}
|
|
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
|
+
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)?' 瓶':'')),
|
|
71
72
|
kind==='opening' && el(Sparkline,{view:v,color:m.color}),
|
|
72
73
|
kind==='terminal' && el(TerminalCardContent,{module:m}),
|
|
73
74
|
kind==='inventory' && el('div',{className:'stock-compare'},
|
|
@@ -15,11 +15,11 @@ export function createV10Details({ T, g, model, presentation, charts }) {
|
|
|
15
15
|
const name = item => item?.name || item?.label || '未提供名称';
|
|
16
16
|
const english = { invoice: 'INVOICE SALES', movement: 'TERMINAL SALES', opening: 'CONSUMER OPENINGS', inventory: 'INVENTORY CHECK', banquet: 'BANQUET ACTIVITY' };
|
|
17
17
|
const descriptions = {
|
|
18
|
-
invoice: '
|
|
18
|
+
invoice: '季度、当月与财年发票及达成,开票节奏、组织和产品贡献。',
|
|
19
19
|
movement: '扫码金额与开票对比、组织和产品贡献、终端渠道与集中度。',
|
|
20
|
-
opening: '
|
|
20
|
+
opening: '开瓶金额与瓶数节奏、同比环比、开瓶与动销的来源数量比及城市分布。',
|
|
21
21
|
inventory: '当前导出记录的盘点规模、提交节奏、差异与产品结构。',
|
|
22
|
-
banquet: '
|
|
22
|
+
banquet: '按执行月份统计的宴席场次、开瓶、场均开瓶及组织表现。',
|
|
23
23
|
};
|
|
24
24
|
const tones = { invoice: 'inv', movement: 'mv', opening: 'op', inventory: 'stk', banquet: 'bq' };
|
|
25
25
|
const moveTab = (event, ids, current, select) => {
|
|
@@ -43,8 +43,16 @@ export function createV10Details({ T, g, model, presentation, charts }) {
|
|
|
43
43
|
const positive = Math.max(0, ...values), negative = Math.min(0, ...values), range = positive - negative || 1;
|
|
44
44
|
const zero = -negative / range * 100;
|
|
45
45
|
const isMoney = entries.some(item => item.unit === '元');
|
|
46
|
+
// 月份多到需要横向滚动时(如库存最近盘点分布),打开即滚到所选月,没有所选月则滚到最新月。
|
|
47
|
+
const scroller = g.useRef(null);
|
|
48
|
+
g.useLayoutEffect(() => {
|
|
49
|
+
const box = scroller.current;
|
|
50
|
+
if (!box || box.scrollWidth <= box.clientWidth + 1) return;
|
|
51
|
+
const target = box.querySelector('.inv-m.sel') || box.lastElementChild;
|
|
52
|
+
if (target) box.scrollLeft = Math.max(0, target.offsetLeft - box.offsetLeft - box.clientWidth / 2 + target.offsetWidth / 2);
|
|
53
|
+
}, [entries.length, filters.month]);
|
|
46
54
|
return el(g.Fragment, {},
|
|
47
|
-
el('div', { className: `inv-months full v10-months ${kind === 'movement' ? 'mv' : ''}`, style: { '--month-count': Math.max(entries.length, 1) }, 'aria-label': kind === 'inventory' ? '盘点提交记录月度分布' : '月度来源趋势' },
|
|
55
|
+
el('div', { ref: scroller, className: `inv-months full v10-months ${kind === 'movement' ? 'mv' : ''}`, style: { '--month-count': Math.max(entries.length, 1) }, 'aria-label': kind === 'inventory' ? '盘点提交记录月度分布' : '月度来源趋势' },
|
|
48
56
|
...entries.map((item, index) => {
|
|
49
57
|
const key = item.month || item.key, month = Number(String(key).slice(-2));
|
|
50
58
|
const selected = key === filters.month, canPick = /^\d{4}-\d{2}$/.test(key || '');
|
|
@@ -55,16 +63,16 @@ export function createV10Details({ T, g, model, presentation, charts }) {
|
|
|
55
63
|
el('em', { 'data-state': item.state }, available(item) ? kind === 'opening' ? model.format(item.value / 10000, 1) : model.format(numeric(item), 0, isMoney ? 0 : 2) : '—'),
|
|
56
64
|
el('div', { className: 'bar' }, el('span', { className: 'v10-zero', style: { bottom: `${zero}%` } }), available(item) && bar(item.value, 'net'), finite(item.negative) && item.negative !== 0 && bar(item.negative, 'ded'), finite(item.comparison) && el('s', { style: { bottom: `${zero + item.comparison / range * 100}%` }, title: `同月发票:${model.format(item.comparison / 10000, 2)} 万元` }), !available(item) && el('span', { className: 'v10-missing-mark' }, '—')),
|
|
57
65
|
el('span', {}, label),
|
|
58
|
-
kind === 'opening' && el('small', { title:
|
|
66
|
+
kind === 'opening' && el('small', { title: `开瓶瓶数:${available(item.bottles) ? `${model.format(item.bottles.value, 0)} 瓶` : reason(item.bottles)}`, 'data-state': item.bottles?.state }, available(item.bottles) ? `${model.format(item.bottles.value / 10000, 1)} 万瓶` : '—'),
|
|
59
67
|
);
|
|
60
68
|
}),
|
|
61
69
|
),
|
|
62
70
|
entries.length === 0 && el(Empty, {}),
|
|
63
71
|
el('div', { className: `inv-legend ${kind === 'movement' ? 'mv' : ''}` },
|
|
64
|
-
el('span', {}, el('i', { className: 'l-net' }), kind === 'inventory' ? '提交记录' : kind === 'opening' ? '
|
|
72
|
+
el('span', {}, el('i', { className: 'l-net' }), kind === 'inventory' ? '提交记录' : kind === 'opening' ? '开瓶金额' : '净额'),
|
|
65
73
|
entries.some(item => finite(item.negative) && item.negative !== 0) && el('span', {}, el('i', { className: 'l-ded' }), kind === 'invoice' ? '负金额' : '负金额'),
|
|
66
74
|
entries.some(item => finite(item.comparison)) && el('span', {}, el('i', { className: 'l-cmp' }), '同月发票净额'),
|
|
67
|
-
el('b', {}, `单位:${kind === 'opening' ? '
|
|
75
|
+
el('b', {}, `单位:${kind === 'opening' ? '万元(柱顶);万瓶(柱下)' : unit(entries[0]) || '来源单位'} · 点击柱子切换月份;缺失不补零`),
|
|
68
76
|
),
|
|
69
77
|
);
|
|
70
78
|
}
|
|
@@ -158,11 +166,11 @@ export function createV10Details({ T, g, model, presentation, charts }) {
|
|
|
158
166
|
const columns = {
|
|
159
167
|
invoice: [['organization', '完整组织路径'], ['date', '业务日期'], ['dealerName', '经销商'], ['dealerCode', '经销商编码'], ['brand', '品牌'], ['category', '品类'], ['amount', '发票净额 / 万元', '元']],
|
|
160
168
|
movement: [['organization', '完整组织路径'], ['date', '扫码日期'], ['terminalName', '终端'], ['terminalCode', '售点编码'], ['brand', '品牌'], ['category', '品类'], ['amount', '扫码净额 / 万元', '元'], ['bottles', '瓶单位数量', '瓶'], ['boxes', '盒单位数量', '盒'], ['cases', '来源扫码件数', '源件数']],
|
|
161
|
-
opening: [['organization', '产品所属完整组织'], ['date', '抽奖日期'], ['city', '开瓶城市'], ['bottles', '开瓶 / 瓶', '瓶'], ['amount', '
|
|
169
|
+
opening: [['organization', '产品所属完整组织'], ['date', '抽奖日期'], ['city', '开瓶城市'], ['bottles', '开瓶 / 瓶', '瓶'], ['amount', '开瓶金额 / 万元', '元']],
|
|
162
170
|
inventory: inventoryMode === 'visit-history'
|
|
163
171
|
? [['organization', '源完整营销组织'], ['dealerName', '经销商'], ['dealerCode', '经销商编码'], ['productName', '完整产品名称'], ['submittedAt', '盘点提交时间'], ['system', '提交时系统 / 瓶', '瓶'], ['counted', '盘点 / 瓶', '瓶'], ['signedVariance', '盘点与系统差异 / 瓶', '瓶'], ['previousSubmittedAt', '上次盘点时间'], ['previousCounted', '上次盘点瓶数 / 瓶', '瓶'], ['changeFromPrevious', '较上次变化瓶数 / 瓶', '瓶'], ['daysSinceStocktake', '距所选截止日天数 / 天', '天'], ['comparisonStatusLabel', '比较状态'], ['absoluteVariance', '绝对差 / 瓶', '瓶'], ['sourceVariance', '源偏差 / 瓶', '瓶'], ['systemAmount', '提交时系统金额 / 万元', '元'], ['recordStatus', '核查提示'], ['supplementRequested', '是否补录'], ['supplementStatus', '补录状态']]
|
|
164
172
|
: [['organization', '完整组织路径'], ['dealerName', '经销商'], ['dealerCode', '经销商编码'], ['productCode', '产品编码'], ['productName', '产品'], ['date', '盘点提交日期'], ['system', '系统 / 瓶', '瓶'], ['counted', '盘点 / 瓶', '瓶'], ['sourceVariance', '源偏差 / 瓶', '瓶'], ['signedVariance', '盘点−系统 / 瓶', '瓶'], ['absoluteVariance', '绝对差 / 瓶', '瓶']],
|
|
165
|
-
banquet: [['organization', '完整组织路径'], ['events', '执行 / 场', '场'], ['bottles', '开瓶 / 瓶', '瓶'], ['average', '场均 / 瓶', '瓶/场']
|
|
173
|
+
banquet: [['organization', '完整组织路径'], ['events', '执行 / 场', '场'], ['bottles', '开瓶 / 瓶', '瓶'], ['average', '场均 / 瓶', '瓶/场']],
|
|
166
174
|
}[kind] || [];
|
|
167
175
|
const cell = (row, field, measureUnit) => {
|
|
168
176
|
if (kind === 'banquet' && field === 'reward') return '待确认';
|
|
@@ -231,18 +239,24 @@ export function createV10Details({ T, g, model, presentation, charts }) {
|
|
|
231
239
|
el('div', { className: `analysis-content inv-analysis ${tone}-analysis` },
|
|
232
240
|
el(Kpis, { items: description.kpis }),
|
|
233
241
|
inventoryVisit && el('p', { className: 'v10-method-note' }, `最近盘点日期:${module.inventoryStats?.latestMinDate || '未提供'} 至 ${module.inventoryStats?.latestMaxDate || '未提供'}。各条记录并非同一天盘点,不代表当天实时库存。距所选截止日天数的基准日:${module.inventoryStats?.cutoffDate || '未提供'}。${description.inventoryReviewSummary || ''}${module.inventoryStats?.conflictRows ? `有 ${model.format(module.inventoryStats.conflictRows)} 条最近候选待核实,相关数量不合并。` : ''}`),
|
|
234
|
-
kind === 'banquet' ? el('p', { className: 'sg-note bq' }, `${module.period}
|
|
242
|
+
kind === 'banquet' ? el('p', { className: 'sg-note bq' }, `${module.period}。按执行月份与组织筛选;不随产品筛选;区间按覆盖到的整月统计。`) : el(Trend, { key: kind, description: description.trend, kind, filters, drill, color: module.color }),
|
|
235
243
|
kind === 'inventory' && section(inventoryVisit ? '失效指标 · 缺少来源' : '库存健康 · 来源状态', el(Concentration, { items: description.health, tone: inventoryVisit ? 'stk' : 'stk four' }), inventoryVisit ? '缺少来源字段的指标不计算,不用其他字段替代' : '分类规则待确认时保持未知,不推断安全阈值'),
|
|
236
244
|
el(UpLevel, { filters, drill }),
|
|
237
245
|
el(Heading, { title: `${filters.unit === 'all' ? '下级组织' : '当前单元'} · ${kind === 'inventory' ? inventoryVisit ? '最近盘点瓶数' : '盘点库存金额' : kind === 'opening' ? '开瓶瓶数' : kind === 'banquet' ? '执行场次' : '当月净额'}`, note: filters.unit === 'all' ? '点击一行联动组织筛选' : '按当前完整组织路径统计' }),
|
|
238
246
|
el(Ranked, { items: description.organizations, color: module.color, drill, groupField: module.groupField, leaf: filters.unit !== 'all' }),
|
|
239
247
|
['invoice', 'movement', 'inventory'].includes(kind) && el(Products, { description, filters, drill }),
|
|
248
|
+
kind === 'invoice' && (description.platformSources || []).length > 1 && section('发票来源构成', el(Ranked, { items: description.platformSources, color: module.color, secondary: true }), '藏10、吞之乎平台订单已并入发票合计'),
|
|
249
|
+
kind === 'movement' && description.distributor && section('分销商动销(高端产品)· 参考', el(g.Fragment, {},
|
|
250
|
+
el(Concentration, { items: [{ key: 'd-main', name: description.distributor.main.label, ...description.distributor.main },
|
|
251
|
+
{ key: 'd-yoy', name: '同比', ...description.distributor.yoy, displayPrecision: 1 },
|
|
252
|
+
{ key: 'd-count', name: '有出库的分销商', label: '有出库的分销商', unit: '家', value: description.distributor.distributors, state: 'available' }], tone }),
|
|
253
|
+
el(Ranked, { items: (description.distributor.groups || []).map(item => ({ ...item, key: `d-${item.key}` })), color: module.color, secondary: true, limit: 8 })),
|
|
254
|
+
'分销商出库与终端扫码多为同一批交易,不计入动销合计与达成'),
|
|
240
255
|
kind === 'movement' && section('终端渠道结构', el(Ranked, { items: description.channels, color: module.color, secondary: true, limit: 8 }), '按来源渠道展示扫码金额'),
|
|
241
|
-
kind === 'opening' && section('下级组织 · 较昨日开瓶', el(DayChangeTable, { items: description.dayChanges }), '所选期间末日对比前一天;无记录显示 —,不补零'),
|
|
242
256
|
kind === 'opening' && section('开瓶城市 · 消费地', el(g.Fragment, {}, el(Concentration, { items: description.cities?.concentration || ranking.concentration, tone: 'op' }), el(Ranked, { items: description.cities, color: module.color, secondary: true, limit: 10 })), '与产品所属组织独立观察'),
|
|
243
|
-
['
|
|
257
|
+
['movement', 'inventory', 'banquet'].includes(kind) && section(ranking.title || ({ invoice: '客户集中度 · 经销商', movement: '终端集中度 · 售点', inventory: '库存 Top 经销商', banquet: '执行 Top 单元' })[kind], el(g.Fragment, {}, el(Concentration, { items: ranking.concentration, tone }), el(Ranked, { items: ranking.items, color: module.color, secondary: true, limit: kind === 'banquet' ? 10 : 8 })), ranking.note),
|
|
244
258
|
kind === 'inventory' && section(inventoryVisit ? '盘点与系统差异 · 逐条比较' : '盘点差异 · 逐条比较', el(ObservationTable, { items: description.deviations, kind, inventoryMode: module.inventoryMode }), '盘点减系统,按来源记录逐条比较'),
|
|
245
|
-
kind === 'banquet' && section('场均开瓶排行', el(ObservationTable, { items: description.efficiency, kind }), '同一完整组织路径 ·
|
|
259
|
+
kind === 'banquet' && section('场均开瓶排行', el(ObservationTable, { items: description.efficiency, kind }), '同一完整组织路径 · 所选月份'),
|
|
246
260
|
el('div', { className: 'v10-method-note' }, '缺失、待确认和真实零值分别展示;“—”表示缺少来源或口径待确认,不补零。'),
|
|
247
261
|
),
|
|
248
262
|
);
|
|
@@ -9,15 +9,15 @@ export function createV10Model(payload, terminalBuilder = buildTerminalStructure
|
|
|
9
9
|
const definitions = {
|
|
10
10
|
invoice: ['当月发票净额', '元', 'amount'], movement: ['当月扫码金额净额', '元', 'amount'],
|
|
11
11
|
opening: ['当月开瓶瓶数', '瓶', 'bottles'], terminal: ['截至所选月末累计签约终端', '家', 'terminalCount'],
|
|
12
|
-
inventory: ['当前导出所选记录盘点数量', '瓶', 'counted'], banquet: ['
|
|
12
|
+
inventory: ['当前导出所选记录盘点数量', '瓶', 'counted'], banquet: ['当月宴席执行场次', '场', 'events'],
|
|
13
13
|
};
|
|
14
14
|
const pending = {
|
|
15
15
|
invoice: ['达成率使用“经营目标”来源,按组织名称对应,目标不分产品;主页同比按同组织、同产品与上年同期比较,期间或基数不足时保留原因;不显示期间覆盖尚未对齐的环比。'],
|
|
16
16
|
movement: ['跨表指标按对应来源的确认状态显示;当月与年累计口径分别标明。本看板暂不显示环比。', '不同单位数量分开显示,不将未知单位当成瓶。'],
|
|
17
|
-
opening: ['
|
|
17
|
+
opening: ['开瓶金额为来源“开瓶金额”字段(2026-11-27 确认为开瓶产品金额,不是现金红包),界面以万元显示。开瓶与扫码的比例只表示来源量关系,不解释为消费者渗透率。'],
|
|
18
18
|
terminal: ['签约终端按网点编号去重,按签约日期截至所选月末累计。', '有效终端按 2026-07-01 至所选月末任一已签约品系扫码净件数达到 1 件判断。'],
|
|
19
19
|
inventory: ['本页是已上传导出的盘点记录视图,不是任意历史月份的库存快照。', '可销月数只对当前导出月份作来源估算,不重建历史库存,也不外推未提供日期。'],
|
|
20
|
-
banquet: ['
|
|
20
|
+
banquet: ['按执行月份统计,随月份筛选;自定义区间按覆盖到的整月计入;不随产品筛选。', '宴席开瓶与消费者开瓶的包含关系不保证,不展示二者占比。'],
|
|
21
21
|
};
|
|
22
22
|
if (inventoryHistory) {
|
|
23
23
|
definitions.inventory = ['最近一次已知盘点瓶数', '瓶', 'counted'];
|
|
@@ -46,7 +46,9 @@ export function createV10Model(payload, terminalBuilder = buildTerminalStructure
|
|
|
46
46
|
const labels = new Map(), fullLabels = new Map();
|
|
47
47
|
const identity = parts => {
|
|
48
48
|
const key = JSON.stringify(parts);
|
|
49
|
-
|
|
49
|
+
// 下级为空的记录(如只分到大区的平台订单)明确标为“未分配”,不与上级同名。
|
|
50
|
+
const lower = parts.slice(3).map(x => String(x ?? '').trim()), placeholder = ['', '未分配办事处', '未分配主任单元'];
|
|
51
|
+
const known = lower[0] ? lower.map((value, index) => value || placeholder[index]) : lower.filter(Boolean);
|
|
50
52
|
const short = known.join(' / ') || '未提供组织';
|
|
51
53
|
labels.set(key, `${short}${parts.slice(0, 3).some(x => !x) ? '(上级未提供)' : ''}`);
|
|
52
54
|
fullLabels.set(key, parts.map(value => value || '未提供').join(' / '));
|
|
@@ -81,6 +83,11 @@ export function createV10Model(payload, terminalBuilder = buildTerminalStructure
|
|
|
81
83
|
product: JSON.stringify([row.brand || '未映射品牌', row.category || '未映射品类']),
|
|
82
84
|
month: row.date ? row.date.slice(0, 7) : null };
|
|
83
85
|
})]));
|
|
86
|
+
// 分销商动销(高端产品):只作动销参考,不进入六个板块,也不参与组织下拉。
|
|
87
|
+
const distributorRows = (payload.distributor?.records || []).map(row => {
|
|
88
|
+
const { region, office, unit } = keysFor(row);
|
|
89
|
+
return { ...row, region, office, unit, product: JSON.stringify([row.brand || '未映射品牌', row.category || '未映射品类']), month: row.date ? row.date.slice(0, 7) : null };
|
|
90
|
+
});
|
|
84
91
|
const monthSet = new Set();
|
|
85
92
|
for (const id of ids) for (const row of normalized[id]) if (row.month) monthSet.add(row.month);
|
|
86
93
|
if (!monthSet.size) for (const coverage of Object.values(payload.coverage)) if (coverage?.end) monthSet.add(coverage.end.slice(0, 7));
|
|
@@ -91,7 +98,7 @@ export function createV10Model(payload, terminalBuilder = buildTerminalStructure
|
|
|
91
98
|
const matchesProduct = (id, row, filters) => id === 'inventory' && inventoryHistory || !['invoice', 'movement', 'inventory'].includes(id) || filters.product === 'all' || row.product === filters.product;
|
|
92
99
|
const period = (id, filters) => {
|
|
93
100
|
const coverage = payload.coverage[id];
|
|
94
|
-
if (id === 'banquet') return
|
|
101
|
+
if (id === 'banquet') { const p = periodOf(filters); return p.mode === 'range' ? `${p.start.slice(0, 7)} 至 ${p.end.slice(0, 7)} 整月;来源至 ${coverage?.end?.slice(0, 7) || '未提供'}` : `${filters.month};来源至 ${coverage?.end?.slice(0, 7) || '未提供'}`; }
|
|
95
102
|
const selected = filters.month, p = periodOf(filters);
|
|
96
103
|
if (selected === 'fixed') return '来源未提供可筛选日期';
|
|
97
104
|
const end = coverage?.end?.slice(0, 7) === selected ? coverage.end : `${selected} 月末`;
|
|
@@ -324,7 +331,8 @@ export function createV10Model(payload, terminalBuilder = buildTerminalStructure
|
|
|
324
331
|
const first = kind === 'quarter' ? `${year}-${String(Math.floor((month - 1) / 3) * 3 + 1).padStart(2, '0')}` : month >= 7 ? `${year}-07` : `${year - 1}-07`;
|
|
325
332
|
const months = Array.from({ length: kind === 'quarter' ? 3 : 12 }, (_, index) => offsetMonth(first, index));
|
|
326
333
|
const fiscal = month >= 7 ? year : year - 1;
|
|
327
|
-
|
|
334
|
+
// 财年按结束年份命名(与藏10表一致):2026-07 至 2027-06 为“2027 财年”。
|
|
335
|
+
const label = kind === 'quarter' ? `${Number(months[0].slice(5))}–${Number(months[2].slice(5))} 月` : `${fiscal + 1} 财年`;
|
|
328
336
|
const detail = kind === 'quarter' ? `${months[0]} 至 ${months[2]}(财年第 ${[3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2][month - 1]} 季度)` : `${fiscal}-07-01 至 ${fiscal + 1}-06-30`;
|
|
329
337
|
return { kind, label, detail, start: `${months[0]}-01`, end: p.end, periodEnd: monthEnd(months.at(-1)), months };
|
|
330
338
|
}
|
|
@@ -379,11 +387,13 @@ export function createV10Model(payload, terminalBuilder = buildTerminalStructure
|
|
|
379
387
|
output.period = p;
|
|
380
388
|
const inWindow = row => p.mode === 'fixed' ? row.month === f.month : Boolean(row.date) && row.date >= p.start && row.date <= p.end;
|
|
381
389
|
const upToEnd = row => p.mode === 'fixed' ? row.month <= f.month : Boolean(row.date) && row.date <= p.end;
|
|
390
|
+
// 宴席只有执行月份:按月比较,区间按覆盖到的整月。
|
|
391
|
+
const inMonths = row => Boolean(row.month) && (p.mode === 'fixed' ? row.month === f.month : row.month >= p.start.slice(0, 7) && row.month <= p.end.slice(0, 7));
|
|
382
392
|
const yearToEnd = row => Boolean(row.month) && row.month.slice(0, 4) === f.month.slice(0, 4) && (p.mode === 'fixed' ? row.month <= f.month : row.date <= p.end);
|
|
383
393
|
for (const id of ids) {
|
|
384
394
|
const sourceModule = payload.modules[id], sourceRows = id === 'inventory' && inventoryHistory ? latestInventory(p.end || '9999-12-31') : normalized[id];
|
|
385
395
|
const scoped = sourceRows.filter(row => matchesOrg(row, f) && matchesProduct(id, row, f));
|
|
386
|
-
const rows = scoped.filter(row => id === 'banquet'
|
|
396
|
+
const rows = scoped.filter(row => id === 'banquet' ? inMonths(row) : (row.month && (['inventory', 'terminal'].includes(id) ? upToEnd(row) : inWindow(row))));
|
|
387
397
|
const [baseLabel, unit, field] = definitions[id];
|
|
388
398
|
const label = p.mode === 'range' ? baseLabel.replace('当月', '区间').replace('截至所选月末', `截至 ${p.end}`) : baseLabel;
|
|
389
399
|
const main = metric(rows, field, sourceModule, label, unit);
|
|
@@ -401,8 +411,8 @@ export function createV10Model(payload, terminalBuilder = buildTerminalStructure
|
|
|
401
411
|
}
|
|
402
412
|
const ratio = (numerator, denominator, ratioLabel, ratioUnit, allowed = true) => ({ label: ratioLabel, unit: ratioUnit, value: allowed && numerator !== null && denominator !== null && denominator > 0 ? numerator / denominator : null, state: allowed && numerator !== null && denominator !== null && denominator > 0 ? 'available' : 'pending', reason: '源值缺失、规则待确认或分母不大于零' });
|
|
403
413
|
if (id === 'opening') {
|
|
404
|
-
extra.push(metric(rows, 'amount', sourceModule, '
|
|
405
|
-
extra.push(ratio(sum(rows, 'amount'), sum(rows, 'bottles'), '
|
|
414
|
+
extra.push(metric(rows, 'amount', sourceModule, '开瓶金额', '元'));
|
|
415
|
+
extra.push(ratio(sum(rows, 'amount'), sum(rows, 'bottles'), '瓶均开瓶金额', '元/瓶', main.state === 'available' && extra[0].state === 'available'));
|
|
406
416
|
}
|
|
407
417
|
if (id === 'terminal') {
|
|
408
418
|
extra.push(metric(rows, 'agreementCount', sourceModule, '按已确认去重规则保留协议数', '份'));
|
|
@@ -417,11 +427,10 @@ export function createV10Model(payload, terminalBuilder = buildTerminalStructure
|
|
|
417
427
|
extra.push({ label: '产品品类未映射记录', unit: '条', value: sourceModule.state === 'unavailable' ? null : rows.filter(row => !row.brand || !row.category).length, state: sourceModule.state === 'unavailable' ? 'missing' : 'available' });
|
|
418
428
|
}
|
|
419
429
|
if (id === 'banquet') {
|
|
420
|
-
extra.push(metric(rows, 'bottles', sourceModule, '
|
|
430
|
+
extra.push(metric(rows, 'bottles', sourceModule, '宴席开瓶', '瓶'));
|
|
421
431
|
extra.push(ratio(sum(rows, 'bottles'), sum(rows, 'events'), '场均开瓶', '瓶/场', main.state === 'available' && sourceModule.metrics.bottles?.status !== 'pending'));
|
|
422
|
-
extra.push(metric(rows, 'reward', sourceModule, '售点推荐奖励', '元', true));
|
|
423
432
|
}
|
|
424
|
-
const hasSourcePeriod = normalized[id].some(row => id === 'banquet'
|
|
433
|
+
const hasSourcePeriod = normalized[id].some(row => id === 'banquet' ? inMonths(row) : row.month && (['inventory', 'terminal'].includes(id) ? upToEnd(row) : inWindow(row)));
|
|
425
434
|
if (!hasSourcePeriod && sourceModule.state !== 'unavailable') for (const item of [main, ...extra]) { item.value = null; item.state = 'missing'; item.reason = '该期间无来源记录'; }
|
|
426
435
|
// One pass groups rows by month in their original order (same sums as filtering per month).
|
|
427
436
|
const scopedByMonth = new Map();
|
|
@@ -515,6 +524,44 @@ export function createV10Model(payload, terminalBuilder = buildTerminalStructure
|
|
|
515
524
|
progress: timeProgress(id, window.start, window.periodEnd, window.end) };
|
|
516
525
|
}
|
|
517
526
|
}
|
|
527
|
+
// 发票来源构成:公司发票与并入的两个平台,按当前期间与组织、产品筛选。
|
|
528
|
+
{
|
|
529
|
+
const module = output.modules.invoice, names = { company: '公司发票', zang10: '藏10平台', tunzhihu: '吞之乎平台' };
|
|
530
|
+
module.platformSources = ['company', 'zang10', 'tunzhihu'].filter(key => key === 'company' || payload.platforms?.[key]).map(key => {
|
|
531
|
+
const rows = module.rows.filter(row => (row.platform || 'company') === key), ok = module.main.state === 'available';
|
|
532
|
+
// 平台文件没覆盖所选期间时标“未覆盖”,不把没有记录当成零。
|
|
533
|
+
const cover = key === 'company' ? null : payload.platforms[key].coverage;
|
|
534
|
+
const uncovered = cover?.start && cover?.end && p.mode !== 'fixed' && !rows.length && (p.start > cover.end || (p.end && p.end < cover.start));
|
|
535
|
+
if (uncovered) return { key, label: names[key], unit: '元', records: 0, value: null, state: 'missing',
|
|
536
|
+
reason: `平台文件覆盖 ${cover.start} 至 ${cover.end},未覆盖所选期间`, coverage: { start: cover.start, end: cover.end } };
|
|
537
|
+
const value = ok ? (rows.length ? sum(rows, 'amount') : 0) : null;
|
|
538
|
+
return { key, label: names[key], unit: '元', records: rows.length, value, state: ok && finite(value) ? 'available' : ok ? 'pending' : module.main.state,
|
|
539
|
+
reason: ok && finite(value) ? null : module.main.reason || '存在缺失或不可用源值' };
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
// 分销商动销参考:同一期间、组织与产品筛选;同比对比去年同一段日期(来源须覆盖)。
|
|
543
|
+
{
|
|
544
|
+
const cover = payload.distributor?.coverage, grouping = f.region === 'all' ? 'region' : f.office === 'all' ? 'office' : 'unit';
|
|
545
|
+
if (!distributorRows.length) output.distributor = null;
|
|
546
|
+
else {
|
|
547
|
+
const scopedRows = distributorRows.filter(row => matchesOrg(row, f) && (f.product === 'all' || row.product === f.product));
|
|
548
|
+
const rows = scopedRows.filter(row => row.month && inWindow(row));
|
|
549
|
+
const end = p.mode === 'fixed' || !cover?.end ? null : [p.end, cover.end].sort()[0];
|
|
550
|
+
const shiftYear = date => `${Number(date.slice(0, 4)) - 1}${date.slice(4)}`.replace(/-02-29$/, '-02-28');
|
|
551
|
+
const prevRows = end && p.start <= end ? scopedRows.filter(row => row.date && row.date >= shiftYear(p.start) && row.date <= shiftYear(end)) : [];
|
|
552
|
+
const covered = end && cover?.start && cover.start <= shiftYear(p.start);
|
|
553
|
+
const value = rows.length ? sum(rows, 'amount') : null, previous = covered && prevRows.length ? sum(prevRows, 'amount') : null;
|
|
554
|
+
const groups = new Map();
|
|
555
|
+
for (const row of rows) { const list = groups.get(row[grouping]) ?? []; list.push(row); groups.set(row[grouping], list); }
|
|
556
|
+
output.distributor = {
|
|
557
|
+
main: { label: p.mode === 'range' ? '区间分销商动销' : '当月分销商动销', unit: '元', value, state: finite(value) ? 'available' : 'missing', reason: finite(value) ? null : '当前范围在所选期间没有分销商动销记录;不推定为零' },
|
|
558
|
+
yoy: { label: '同比', unit: '%', value: finite(value) && finite(previous) && previous > 0 ? (value - previous) / previous * 100 : null,
|
|
559
|
+
state: finite(value) && finite(previous) && previous > 0 ? 'available' : 'pending', reason: !covered ? '分销商来源未覆盖去年同期' : !finite(previous) ? '去年同期无记录' : previous <= 0 ? '去年同期不大于零' : null, previous },
|
|
560
|
+
records: rows.length, distributors: new Set(rows.map(row => row.distributorName).filter(Boolean)).size, coverage: cover || null,
|
|
561
|
+
groups: [...groups].map(([key, list]) => ({ key, name: label(key), value: sum(list, 'amount'), records: list.length, unit: '元', state: 'available' })).sort((a, b) => (b.value ?? -Infinity) - (a.value ?? -Infinity)),
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
}
|
|
518
565
|
const crossMetrics = crossTableMetrics(f);
|
|
519
566
|
for (const id of ids) output.modules[id].crossMetrics = crossMetrics[id] || [];
|
|
520
567
|
output.groupField = f.region === 'all' ? 'region' : f.office === 'all' ? 'office' : 'unit';
|