dsh-data-dashboard 0.0.0-stage → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -2
- package/assets/theater-board.svg +1 -0
- package/backend/incremental/flow.mjs +492 -0
- package/backend/incremental/jobs.mjs +58 -0
- package/backend/incremental/xlsx-rows.mjs +145 -0
- package/backend/job-worker.mjs +22 -0
- package/backend/modules/banquet/index.mjs +46 -0
- package/backend/modules/inventory/index.mjs +45 -0
- package/backend/modules/inventory/legacy-fields.mjs +83 -0
- package/backend/modules/invoice/index.mjs +72 -0
- package/backend/modules/movement/index.mjs +68 -0
- package/backend/modules/opening/index.mjs +48 -0
- package/backend/modules/target/index.mjs +45 -0
- package/backend/modules/terminal/index.mjs +114 -0
- package/backend/modules.mjs +12 -0
- package/backend/public/admin.css +220 -0
- package/backend/public/admin.js +772 -0
- package/backend/public/board.css +70 -0
- package/backend/public/board.html +50 -0
- package/backend/public/board.js +153 -0
- package/backend/public/index.html +113 -0
- package/backend/public/org-mapping.js +49 -0
- package/backend/public/review.css +5 -0
- package/backend/public/review.js +452 -0
- package/backend/real-data/generate-dashboard.mjs +137 -0
- package/backend/real-data/inventory-history.mjs +316 -0
- package/backend/real-data/organization-mapping.mjs +166 -0
- package/backend/real-data/source-payload.mjs +459 -0
- package/backend/real-data/terminal-components.mjs +280 -0
- package/backend/real-data/terminal-structure.css +105 -0
- package/backend/real-data/terminal-structure.mjs +276 -0
- package/backend/real-data/v10-components.mjs +112 -0
- package/backend/real-data/v10-details.css +18 -0
- package/backend/real-data/v10-details.mjs +251 -0
- package/backend/real-data/v10-layout.css +27 -0
- package/backend/real-data/v10-model.mjs +568 -0
- package/backend/real-data/v10-overview-data.mjs +253 -0
- package/backend/real-data/v10-overview.css +370 -0
- package/backend/real-data/v10-overview.mjs +340 -0
- package/backend/real-data/v10-presentation.mjs +354 -0
- package/backend/real-data/v10-shell.html +1097 -0
- package/backend/real-data/v10-template.mjs +353 -0
- package/backend/recognition/fingerprint.mjs +32 -0
- package/backend/recognition/headers.mjs +2 -0
- package/backend/recognition/module-definition.mjs +4 -0
- package/backend/recognition/result.mjs +29 -0
- package/backend/recognition/upload-limits.mjs +14 -0
- package/backend/review-engine.mjs +364 -0
- package/backend/review-service.mjs +182 -0
- package/backend/server.mjs +569 -0
- package/backend/store.mjs +68 -0
- package/backend/target-template.mjs +47 -0
- package/backend/validate-workbook.mjs +251 -0
- package/backend/web-sync/README.md +37 -0
- package/backend/web-sync/client.mjs +63 -0
- package/backend/web-sync/exporter.mjs +260 -0
- package/backend/web-sync/local.html +34 -0
- package/backend/web-sync/server.mjs +147 -0
- package/build-manifest.json +80 -0
- package/client.js +54 -0
- package/cordis.patch.yml +3 -0
- package/index.js +117 -0
- package/lib/dist-manifest.mjs +19 -0
- package/lib/market-index.mjs +56 -0
- package/lib/package-audit.mjs +34 -0
- package/lib/settings.mjs +71 -0
- package/lib/tool-definitions.mjs +56 -0
- package/lib/tools.mjs +255 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +71 -4
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
import { buildTerminalStructure } from './terminal-structure.mjs';
|
|
2
|
+
|
|
3
|
+
// Both factories are serialized into the offline dashboard.
|
|
4
|
+
export function createV10Model(payload, terminalBuilder = buildTerminalStructure) {
|
|
5
|
+
const inventoryHistory = payload.modules.inventory.inventoryMode === 'visit-history';
|
|
6
|
+
const ids = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet'];
|
|
7
|
+
const titles = { invoice: '发票销售', movement: '终端动销', opening: '消费者开瓶', terminal: '终端签约', inventory: '库存盘点', banquet: '宴席执行' };
|
|
8
|
+
const colors = { invoice: '#ab343c', movement: '#167d72', opening: '#547fa3', terminal: '#877753', inventory: '#687e88', banquet: '#9c7865' };
|
|
9
|
+
const definitions = {
|
|
10
|
+
invoice: ['当月发票净额', '元', 'amount'], movement: ['当月扫码金额净额', '元', 'amount'],
|
|
11
|
+
opening: ['当月开瓶瓶数', '瓶', 'bottles'], terminal: ['截至所选月末累计签约终端', '家', 'terminalCount'],
|
|
12
|
+
inventory: ['当前导出所选记录盘点数量', '瓶', 'counted'], banquet: ['来源固定期间执行场次', '场', 'events'],
|
|
13
|
+
};
|
|
14
|
+
const pending = {
|
|
15
|
+
invoice: ['达成率使用“经营目标”来源,按组织名称对应,目标不分产品;主页同比按同组织、同产品与上年同期比较,期间或基数不足时保留原因;不显示期间覆盖尚未对齐的环比。'],
|
|
16
|
+
movement: ['跨表指标按对应来源的确认状态显示;当月与年累计口径分别标明。本看板暂不显示环比。', '不同单位数量分开显示,不将未知单位当成瓶。'],
|
|
17
|
+
opening: ['金额仅表示现金红包金额。开瓶与扫码的比例只表示来源量关系,不解释为消费者渗透率。'],
|
|
18
|
+
terminal: ['签约终端按网点编号去重,按签约日期截至所选月末累计。', '有效终端按 2026-07-01 至所选月末任一已签约品系扫码净件数达到 1 件判断。'],
|
|
19
|
+
inventory: ['本页是已上传导出的盘点记录视图,不是任意历史月份的库存快照。', '可销月数只对当前导出月份作来源估算,不重建历史库存,也不外推未提供日期。'],
|
|
20
|
+
banquet: ['保持文件声明的固定期间,不响应月份或产品筛选。', '奖励合计继续待确认;宴席开瓶与消费者开瓶的包含关系不保证,不展示二者占比。'],
|
|
21
|
+
};
|
|
22
|
+
if (inventoryHistory) {
|
|
23
|
+
definitions.inventory = ['最近一次已知盘点瓶数', '瓶', 'counted'];
|
|
24
|
+
pending.inventory = ['按经销商编码+完整产品名称,选择截至所选月末最近一次盘点;并列候选不自动删除或相加。',
|
|
25
|
+
'各记录盘点时间不同,旧记录不自动清零,合计不是同一时点实时库存。',
|
|
26
|
+
'新表组织层级与其他来源不同,跨板块组织映射尚未确认;按源完整路径独立筛选,不按短名称合并。',
|
|
27
|
+
'新表缺少盘点金额、产品编码和安全库存依据;盘点金额、金额差额、可销月份及品牌品类联动不可用。'];
|
|
28
|
+
}
|
|
29
|
+
const finite = value => typeof value === 'number' && Number.isFinite(value);
|
|
30
|
+
const format = (value, digits = 0, maxDigits = digits) => finite(value)
|
|
31
|
+
? new Intl.NumberFormat('zh-CN', { minimumFractionDigits: digits, maximumFractionDigits: maxDigits }).format(value) : '—';
|
|
32
|
+
const formatMetric = metric => metric.state === 'available'
|
|
33
|
+
? format(metric.value, metric.precision ?? (metric.unit.startsWith('元') || metric.unit.includes('/') ? 2 : 0), metric.precision ?? (metric.unit === '元' ? 2 : 6))
|
|
34
|
+
: metric.state === 'pending' ? '待确认' : metric.state === 'unavailable' ? '不可用' : metric.reason === '未接入有效来源' ? '未接入' : '无记录';
|
|
35
|
+
const sum = (rows, field) => {
|
|
36
|
+
if (rows.some(row => !finite(row[field]))) return null;
|
|
37
|
+
let total = 0, correction = 0;
|
|
38
|
+
for (const row of rows) {
|
|
39
|
+
const next = row[field] - correction, updated = total + next;
|
|
40
|
+
correction = (updated - total) - next; total = updated;
|
|
41
|
+
}
|
|
42
|
+
return total;
|
|
43
|
+
};
|
|
44
|
+
const orgFields = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
|
|
45
|
+
const partsFor = row => row.orgPath || orgFields.map(key => row.org?.[key] || '');
|
|
46
|
+
const labels = new Map(), fullLabels = new Map();
|
|
47
|
+
const identity = parts => {
|
|
48
|
+
const key = JSON.stringify(parts);
|
|
49
|
+
const known = parts.slice(3).map(x => String(x ?? '').trim()).filter(Boolean);
|
|
50
|
+
const short = known.join(' / ') || '未提供组织';
|
|
51
|
+
labels.set(key, `${short}${parts.slice(0, 3).some(x => !x) ? '(上级未提供)' : ''}`);
|
|
52
|
+
fullLabels.set(key, parts.map(value => value || '未提供').join(' / '));
|
|
53
|
+
return key;
|
|
54
|
+
};
|
|
55
|
+
// Records of one organization share one orgPath array after unpacking; its keys
|
|
56
|
+
// (and label registrations) are computed once per path instead of once per row.
|
|
57
|
+
const orgKeys = new WeakMap();
|
|
58
|
+
const keysFor = row => {
|
|
59
|
+
const cached = row.orgPath && orgKeys.get(row.orgPath);
|
|
60
|
+
if (cached) return cached;
|
|
61
|
+
const parts = partsFor(row);
|
|
62
|
+
const result = { region: identity(parts.slice(0, 4)), office: identity(parts.slice(0, 5)), unit: identity(parts) };
|
|
63
|
+
if (row.orgPath) orgKeys.set(row.orgPath, result);
|
|
64
|
+
return result;
|
|
65
|
+
};
|
|
66
|
+
const orgMap = new Map(), categoryMap = new Map();
|
|
67
|
+
for (const id of ids) for (const row of payload.modules[id].records) {
|
|
68
|
+
const { region, office, unit } = keysFor(row);
|
|
69
|
+
if (!orgMap.has(unit)) orgMap.set(unit, { id: unit, region, office, unit, sources: new Set() });
|
|
70
|
+
orgMap.get(unit).sources.add(id);
|
|
71
|
+
if (['invoice', 'movement', 'inventory'].includes(id) && !(id === 'inventory' && inventoryHistory)) {
|
|
72
|
+
const key = JSON.stringify([row.brand || '未映射品牌', row.category || '未映射品类']);
|
|
73
|
+
if (!categoryMap.has(key)) categoryMap.set(key, { id: key, name: row.category || '未映射品类', brand: row.brand || '未映射品牌' });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const organizations = [...orgMap.values()].sort((a, b) => a.unit.localeCompare(b.unit, 'zh-CN'));
|
|
77
|
+
const categories = [...categoryMap.values()].sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
|
|
78
|
+
const normalized = Object.fromEntries(ids.map(id => [id, payload.modules[id].records.map(row => {
|
|
79
|
+
const { region, office, unit } = keysFor(row);
|
|
80
|
+
return { ...row, region, office, unit,
|
|
81
|
+
product: JSON.stringify([row.brand || '未映射品牌', row.category || '未映射品类']),
|
|
82
|
+
month: row.date ? row.date.slice(0, 7) : null };
|
|
83
|
+
})]));
|
|
84
|
+
const monthSet = new Set();
|
|
85
|
+
for (const id of ids) for (const row of normalized[id]) if (row.month) monthSet.add(row.month);
|
|
86
|
+
if (!monthSet.size) for (const coverage of Object.values(payload.coverage)) if (coverage?.end) monthSet.add(coverage.end.slice(0, 7));
|
|
87
|
+
const months = [...monthSet].sort();
|
|
88
|
+
if (!months.length) months.push('fixed');
|
|
89
|
+
const defaults = { month: months.at(-1), period: 'month', start: null, end: null, region: 'all', office: 'all', unit: 'all', product: 'all' };
|
|
90
|
+
const matchesOrg = (row, filters) => ['region', 'office', 'unit'].every(key => filters[key] === 'all' || row[key] === filters[key]);
|
|
91
|
+
const matchesProduct = (id, row, filters) => id === 'inventory' && inventoryHistory || !['invoice', 'movement', 'inventory'].includes(id) || filters.product === 'all' || row.product === filters.product;
|
|
92
|
+
const period = (id, filters) => {
|
|
93
|
+
const coverage = payload.coverage[id];
|
|
94
|
+
if (id === 'banquet') return coverage?.start && coverage?.end ? `${coverage.start} 至 ${coverage.end}(来源固定期间)` : '来源固定期间未提供';
|
|
95
|
+
const selected = filters.month, p = periodOf(filters);
|
|
96
|
+
if (selected === 'fixed') return '来源未提供可筛选日期';
|
|
97
|
+
const end = coverage?.end?.slice(0, 7) === selected ? coverage.end : `${selected} 月末`;
|
|
98
|
+
if (id === 'inventory' && inventoryHistory) {
|
|
99
|
+
const knownEnd = [p.end, coverage?.end].filter(Boolean).sort()[0];
|
|
100
|
+
return `截至 ${knownEnd} 的最近一次已知盘点(非实时库存)`;
|
|
101
|
+
}
|
|
102
|
+
if (p.mode === 'range') return ['inventory', 'terminal'].includes(id) ? `已上传记录日期 ≤ ${[p.end, coverage?.end].filter(Boolean).sort()[0]}` : `${p.start} 至 ${p.end};来源截止 ${coverage?.end || '未提供'}`;
|
|
103
|
+
return ['inventory', 'terminal'].includes(id) ? `已上传记录日期 ≤ ${end}` : `${selected};来源截止 ${coverage?.end || '未提供'}`;
|
|
104
|
+
};
|
|
105
|
+
const metric = (rows, field, module, label, unit, forcePending = false) => {
|
|
106
|
+
if (module.state === 'unavailable') return { label, unit, value: null, state: module.reviewPending ? 'pending' : 'missing', reason: module.reviewReason || '未接入有效来源' };
|
|
107
|
+
if (module.inventoryMode === 'visit-history') {
|
|
108
|
+
if (field === 'countAmount') return { label, unit, value: null, state: 'unavailable', reason: '拜访采集表没有盘点库存金额' };
|
|
109
|
+
if (!['records', 'agreementCount'].includes(field) && rows.some(row => row.inventoryConflict || row.inventoryDateUncertain)) return { label, unit, value: null, state: 'unavailable', reason: '最近盘点有同时间候选或无效提交时间,不能确定唯一库存' };
|
|
110
|
+
}
|
|
111
|
+
if (forcePending || module.metrics[field]?.status === 'pending') return { label, unit, value: null, state: 'pending', reason: '来源规则或口径待确认' };
|
|
112
|
+
const value = ['records', 'agreementCount'].includes(field) ? rows.length : field === 'terminalCount' ? rows.some(row => !row.terminalCode) ? null : new Set(rows.map(row => row.terminalCode)).size : sum(rows, field);
|
|
113
|
+
return { label, unit, value, state: value === null ? 'pending' : 'available', reason: value === null ? '存在缺失或不可用源值' : null };
|
|
114
|
+
};
|
|
115
|
+
const monthEnd = month => new Date(Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5, 7)), 0)).toISOString().slice(0, 10);
|
|
116
|
+
const inventoryCutoff = end => /^\d{4}-\d{2}-\d{2}$/.test(end || '') && payload.coverage.inventory?.end
|
|
117
|
+
? [end, payload.coverage.inventory.end].sort()[0] : null;
|
|
118
|
+
const offsetMonth = (month, offset) => new Date(Date.UTC(Number(month.slice(0, 4)), Number(month.slice(5, 7)) - 1 + offset, 1)).toISOString().slice(0, 7);
|
|
119
|
+
const ruleReady = (name, dependencies) => {
|
|
120
|
+
const rule = payload.decisionContract?.[name];
|
|
121
|
+
return payload.decisionContract?.version === 1 && rule?.status === 'confirmed'
|
|
122
|
+
&& (name !== 'terminalIdentity' || rule.key === 'original-code')
|
|
123
|
+
&& dependencies.every(id => rule.sources?.[id] && rule.sources[id] === payload.sources[id]?.sha256);
|
|
124
|
+
};
|
|
125
|
+
const failCross = (key, label, unit, reason, notes = [], state = 'unavailable') => ({ key, label, unit, value: null, state, reason, notes, precision: 2 });
|
|
126
|
+
const commonCut = (dependencies, endDate) => {
|
|
127
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(endDate || '') || dependencies.some(id => payload.modules[id].state === 'unavailable' || !payload.coverage[id]?.end)) return null;
|
|
128
|
+
return [endDate, ...dependencies.map(id => payload.coverage[id].end)].sort()[0];
|
|
129
|
+
};
|
|
130
|
+
const sourceWindowIssue = (dependencies, start, end) => {
|
|
131
|
+
if (!end || end < start) return '来源截止日尚未覆盖所选期间';
|
|
132
|
+
const required = [];
|
|
133
|
+
for (let month = start.slice(0, 7); month <= end.slice(0, 7); month = offsetMonth(month, 1)) required.push(month);
|
|
134
|
+
for (const id of dependencies) {
|
|
135
|
+
const cover = payload.coverage[id];
|
|
136
|
+
if (payload.modules[id].state === 'unavailable' || !cover?.start || !cover.end) return `${titles[id]}缺少可用来源期间`;
|
|
137
|
+
if (cover.start.slice(0, 7) > start.slice(0, 7) || cover.end < end) return `${titles[id]}来源月份未覆盖计算窗口`;
|
|
138
|
+
if (normalized[id].some(row => !row.date)) return `${titles[id]}存在日期缺失,无法完整分期`;
|
|
139
|
+
if (required.some(month => !normalized[id].some(row => row.month === month && row.date <= end))) return `${titles[id]}计算窗口有月份无来源记录,不能补零`;
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
};
|
|
143
|
+
const windowRows = (id, filters, start, end, ignoreProduct = false) => normalized[id].filter(row => matchesOrg(row, filters) && (ignoreProduct || matchesProduct(id, row, filters)) && row.date && row.date >= start && row.date <= end);
|
|
144
|
+
const ratioMetric = (key, label, unit, numerator, denominator, range, notes, scale = 100) => {
|
|
145
|
+
if (!finite(numerator) || !finite(denominator)) return failCross(key, label, unit, '计算窗口存在缺失源值', notes);
|
|
146
|
+
if (denominator <= 0) return failCross(key, label, unit, '分母不大于零,不能计算比例或估算', notes);
|
|
147
|
+
const value = numerator / denominator * scale;
|
|
148
|
+
if (!finite(value)) return failCross(key, label, unit, '计算结果超出可表示范围', notes);
|
|
149
|
+
return { key, label, unit, value, state: 'available', reason: null, numerator, denominator, range, notes, precision: 2 };
|
|
150
|
+
};
|
|
151
|
+
function crossTableMetrics(filters) {
|
|
152
|
+
const f = filters, p = periodOf(f), range = p.mode === 'range';
|
|
153
|
+
const amountRatio = cumulative => {
|
|
154
|
+
const key = cumulative ? 'invoiceMovementYtdRatio' : 'invoiceMovementMonthRatio', label = cumulative ? '年累计动销 / 开票' : range ? '区间动销 / 开票' : '当月动销 / 开票';
|
|
155
|
+
const deps = ['invoice', 'movement'];
|
|
156
|
+
if (!ruleReady('crossTableMetrics', deps)) return failCross(key, label, '%', '这两个来源版本的跨表关系尚未确认', [], 'pending');
|
|
157
|
+
const end = commonCut(deps, p.end), start = cumulative ? `${f.month.slice(0, 4)}-01-01` : p.start;
|
|
158
|
+
const notes = [`同组织、同产品;${start} 至 ${end || '未提供共同截止日'}。`, '扫码净额与发票净额分别来自各自来源;比例超过 100% 不解释为渗透率。'];
|
|
159
|
+
const issue = sourceWindowIssue(deps, start, end);
|
|
160
|
+
if (issue) return failCross(key, label, '%', issue, notes);
|
|
161
|
+
const invoices = windowRows('invoice', f, start, end), movements = windowRows('movement', f, start, end);
|
|
162
|
+
if (!invoices.length || !movements.length) return failCross(key, label, '%', '当前组织或产品范围缺少一侧来源记录', notes);
|
|
163
|
+
if (deps.some(id => payload.modules[id].metrics.amount?.status === 'pending')) return failCross(key, label, '%', '来源金额规则尚未确认', notes, 'pending');
|
|
164
|
+
return ratioMetric(key, label, '%', sum(movements, 'amount'), sum(invoices, 'amount'), { start, end }, notes);
|
|
165
|
+
};
|
|
166
|
+
const openingRatio = () => {
|
|
167
|
+
const key = 'openingMovementRatio', label = '年累计开瓶 / 动销(瓶)', deps = ['opening', 'movement'];
|
|
168
|
+
if (!ruleReady('crossTableMetrics', deps)) return failCross(key, label, '%', '这两个来源版本的跨表关系尚未确认', [], 'pending');
|
|
169
|
+
const end = commonCut(deps, p.end), start = `${f.month.slice(0, 4)}-01-01`;
|
|
170
|
+
const notes = [`同组织;${start} 至 ${end || '未提供共同截止日'};分子与分母都不随产品筛选。`, '仅计单品单位为瓶的扫码数量;盒单位不混入。此值是来源量关系,不解释为消费者渗透率。'];
|
|
171
|
+
const issue = sourceWindowIssue(deps, start, end);
|
|
172
|
+
if (issue) return failCross(key, label, '%', issue, notes);
|
|
173
|
+
const openings = windowRows('opening', f, start, end, true), movements = windowRows('movement', f, start, end, true);
|
|
174
|
+
if (!openings.length || !movements.length) return failCross(key, label, '%', '当前组织缺少一侧来源记录', notes);
|
|
175
|
+
if (movements.some(row => !['瓶', '盒'].includes(row.quantityUnit))) return failCross(key, label, '%', '扫码来源存在未确认单位,无法确认完整瓶数分母', notes);
|
|
176
|
+
if (deps.some(id => payload.modules[id].metrics.bottles?.status === 'pending')) return failCross(key, label, '%', '来源瓶数规则尚未确认', notes, 'pending');
|
|
177
|
+
const bottles = movements.filter(row => row.quantityUnit === '瓶');
|
|
178
|
+
if (!bottles.length) return failCross(key, label, '%', '当前组织没有瓶单位扫码记录', notes);
|
|
179
|
+
return ratioMetric(key, label, '%', sum(openings, 'bottles'), sum(bottles, 'bottles'), { start, end }, notes);
|
|
180
|
+
};
|
|
181
|
+
const inventoryMonths = () => {
|
|
182
|
+
const key = 'inventorySellableMonths', label = '可销月数(来源估算)', deps = ['inventory', 'movement'];
|
|
183
|
+
if (inventoryHistory) return failCross(key, label, '月', '拜访采集表缺少盘点金额和产品编码,无法计算可销月份');
|
|
184
|
+
if (!ruleReady('crossTableMetrics', deps)) return failCross(key, label, '月', '这两个来源版本的跨表关系尚未确认', [], 'pending');
|
|
185
|
+
if (range) return failCross(key, label, '月', '自定义区间不估算可销月数;请切换到按月查看');
|
|
186
|
+
if (payload.coverage.inventory?.end?.slice(0, 7) !== f.month) return failCross(key, label, '月', '只对库存当前导出截止月份估算,不能还原历史月份库存');
|
|
187
|
+
const end = commonCut(deps, p.end), start = `${offsetMonth(f.month, -2)}-01`;
|
|
188
|
+
const partial = end && end < monthEnd(f.month);
|
|
189
|
+
const notes = [`同组织、同产品;盘点金额采用截至 ${end || '未提供共同截止日'} 的当前导出记录。`, `分母为 ${start} 至 ${end || '未提供'} 的扫码净额合计 ÷ 3,窗口包含所选月及前两个月。`, partial ? '窗口含未完月,直接使用已提供的来源值;未折算全月,不作未来外推。' : '使用来源覆盖的三个连续月份;不补缺失月份。', '盘点估值与扫码交易金额属于不同业务量,这只是来源估算,不是库存历史快照或实际周转天数。'];
|
|
190
|
+
const issue = sourceWindowIssue(['movement'], start, end);
|
|
191
|
+
if (issue) return failCross(key, label, '月', issue, notes);
|
|
192
|
+
const inventory = normalized.inventory.filter(row => matchesOrg(row, f) && matchesProduct('inventory', row, f) && row.date && row.date <= end);
|
|
193
|
+
const movement = windowRows('movement', f, start, end);
|
|
194
|
+
if (normalized.inventory.some(row => !row.date)) return failCross(key, label, '月', '盘点来源存在缺失日期', notes);
|
|
195
|
+
if (!inventory.length || !movement.length) return failCross(key, label, '月', '当前组织或产品缺少盘点或扫码来源记录', notes);
|
|
196
|
+
if (payload.modules.inventory.metrics.countAmount?.status === 'pending' || payload.modules.movement.metrics.amount?.status === 'pending') return failCross(key, label, '月', '来源金额规则尚未确认', notes, 'pending');
|
|
197
|
+
const amount = sum(inventory, 'countAmount'), sales = sum(movement, 'amount');
|
|
198
|
+
if (amount !== null && amount < 0) return failCross(key, label, '月', '盘点来源金额为负,无法作可销月数估算', notes);
|
|
199
|
+
return ratioMetric(key, label, '月', amount, sales === null ? null : sales / 3, { start, end }, notes, 1);
|
|
200
|
+
};
|
|
201
|
+
return { movement: [amountRatio(false), amountRatio(true)], opening: [openingRatio()], inventory: [inventoryMonths()] };
|
|
202
|
+
}
|
|
203
|
+
const inventorySelections = new Map();
|
|
204
|
+
const latestInventory = cutoff => {
|
|
205
|
+
if (inventorySelections.has(cutoff)) return inventorySelections.get(cutoff);
|
|
206
|
+
const groups = new Map();
|
|
207
|
+
for (const row of normalized.inventory) {
|
|
208
|
+
if (!row.month || row.date > cutoff) continue;
|
|
209
|
+
const key = row.inventoryGroupKey || JSON.stringify([row.dealerCode, row.productName]);
|
|
210
|
+
const current = groups.get(key), stamp = row.submittedAt || row.date;
|
|
211
|
+
if (!current || stamp > current.stamp) groups.set(key, { stamp, rows: [row] });
|
|
212
|
+
else if (stamp === current.stamp) current.rows.push(row);
|
|
213
|
+
}
|
|
214
|
+
const cutoffDate = inventoryCutoff(cutoff);
|
|
215
|
+
const result = [...groups.values()].flatMap(group => group.rows.map(row => {
|
|
216
|
+
const elapsed = cutoffDate && row.date ? (Date.parse(`${cutoffDate}T00:00:00Z`) - Date.parse(`${row.date}T00:00:00Z`)) / 86400000 : null;
|
|
217
|
+
return { ...row, inventoryConflict: group.rows.length > 1 ? 1 : row.inventoryConflict || 0,
|
|
218
|
+
daysSinceStocktake: Number.isInteger(elapsed) && elapsed >= 0 ? elapsed : null };
|
|
219
|
+
}));
|
|
220
|
+
inventorySelections.set(cutoff, result);
|
|
221
|
+
if (inventorySelections.size > 2) inventorySelections.delete(inventorySelections.keys().next().value);
|
|
222
|
+
return result;
|
|
223
|
+
};
|
|
224
|
+
const shiftDay = (date, days) => new Date(Date.parse(`${date}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
|
|
225
|
+
const isDate = value => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(`${value}T00:00:00Z`)) && new Date(`${value}T00:00:00Z`).toISOString().slice(0, 10) === value;
|
|
226
|
+
// Compares the last day of the selected period with the calendar day before it.
|
|
227
|
+
// Missing days stay unknown; a zero previous day yields a difference but no rate.
|
|
228
|
+
function dayChange(rows, end, name = '当前范围') {
|
|
229
|
+
const source = payload.modules.opening, cover = payload.coverage.opening;
|
|
230
|
+
const base = { label: '较昨日开瓶', unit: '%', name, date: end || null, previousDate: isDate(end) ? shiftDay(end, -1) : null,
|
|
231
|
+
current: null, previous: null, difference: null, amountCurrent: null, amountPrevious: null, amountRate: null, value: null, precision: 1 };
|
|
232
|
+
const fail = (reason, state = 'pending') => ({ ...base, state, reason });
|
|
233
|
+
if (source.state === 'unavailable') return fail(source.reviewReason || '未接入有效来源', source.reviewPending ? 'pending' : 'missing');
|
|
234
|
+
if (!isDate(end)) return fail('所选期间没有可定位的末日');
|
|
235
|
+
if (!isDate(cover?.start) || cover.start > base.previousDate) return fail('昨日不在开瓶来源覆盖期间内', 'missing');
|
|
236
|
+
if (source.metrics?.bottles?.status === 'pending') return fail('开瓶瓶数来源规则或口径待确认');
|
|
237
|
+
if (rows.some(row => !isDate(row.date))) return fail('存在缺失或无效日期,无法定位当日');
|
|
238
|
+
const today = rows.filter(row => row.date === end), yesterday = rows.filter(row => row.date === base.previousDate);
|
|
239
|
+
const current = today.length ? sum(today, 'bottles') : null, previous = yesterday.length ? sum(yesterday, 'bottles') : null;
|
|
240
|
+
const amountCurrent = today.length ? sum(today, 'amount') : null, amountPrevious = yesterday.length ? sum(yesterday, 'amount') : null;
|
|
241
|
+
const known = { ...base, current, previous, amountCurrent, amountPrevious,
|
|
242
|
+
amountRate: finite(amountCurrent) && finite(amountPrevious) && amountPrevious > 0 ? (amountCurrent - amountPrevious) / amountPrevious * 100 : null };
|
|
243
|
+
if (!today.length) return { ...known, state: 'missing', reason: `${end} 无开瓶来源记录,不推定为零` };
|
|
244
|
+
if (!yesterday.length) return { ...known, state: 'missing', reason: `${base.previousDate} 无开瓶来源记录,不计算变化` };
|
|
245
|
+
if (!finite(current) || !finite(previous)) return { ...known, state: 'pending', reason: '当日或昨日存在缺失或不可用瓶数' };
|
|
246
|
+
const difference = current - previous;
|
|
247
|
+
if (previous <= 0) return { ...known, difference, state: 'pending', reason: '昨日开瓶不大于零,不计算变化率' };
|
|
248
|
+
const value = difference / previous * 100;
|
|
249
|
+
return finite(value) ? { ...known, difference, value, state: 'available', reason: null } : { ...known, difference, state: 'pending', reason: '变化率超出可表示范围' };
|
|
250
|
+
}
|
|
251
|
+
// Business targets are matched by region/office/unit names. The most senior
|
|
252
|
+
// filled level at or below the selected scope is used; parents are never split.
|
|
253
|
+
const targetSource = payload.targets?.state === 'ready' ? payload.targets : null;
|
|
254
|
+
const targetRows = (targetSource?.records || []).map(row => {
|
|
255
|
+
const names = [row.region, row.office, row.unit].map(value => String(value ?? '').trim());
|
|
256
|
+
const depth = names.findIndex(value => !value) < 0 ? 3 : names.findIndex(value => !value);
|
|
257
|
+
return { ...row, names, depth, valid: names.slice(depth).every(value => !value) };
|
|
258
|
+
});
|
|
259
|
+
const targetCounts = new Map();
|
|
260
|
+
for (const row of targetRows) { const key = JSON.stringify([row.month, row.metric, row.names]); targetCounts.set(key, (targetCounts.get(key) || 0) + 1); }
|
|
261
|
+
const targetUnit = kind => kind === 'opening' ? '瓶' : '元';
|
|
262
|
+
const targetLevels = ['全战区', '大区', '办事处', '主任单元'];
|
|
263
|
+
function targetValue(kind, filters, segments, label) {
|
|
264
|
+
const months = segments.map(item => item.month);
|
|
265
|
+
const unit = targetUnit(kind), fail = (reason, state = 'pending') => ({ label, unit, value: null, state, reason });
|
|
266
|
+
if (!targetSource) return fail('未上传经营目标', 'missing');
|
|
267
|
+
if (kind !== 'opening' && filters.product !== 'all') return fail('目标不分产品;选择全部产品后显示达成率', 'unavailable');
|
|
268
|
+
if (!months.length || months.some(month => !/^\d{4}-\d{2}$/.test(month))) return fail('所选期间无法对应目标月份');
|
|
269
|
+
const key = filters.unit !== 'all' ? filters.unit : filters.office !== 'all' ? filters.office : filters.region !== 'all' ? filters.region : null;
|
|
270
|
+
let scope = [];
|
|
271
|
+
if (key) { try { scope = JSON.parse(key).slice(3).map(value => String(value ?? '').trim()); } catch { scope = []; } }
|
|
272
|
+
if (key && (!scope.length || scope.some(value => !value))) return fail('当前组织层级名称不完整,无法对应目标', 'unavailable');
|
|
273
|
+
let total = 0; const levels = new Set(); let summed = false;
|
|
274
|
+
for (const { month, weight } of segments) {
|
|
275
|
+
const rows = targetRows.filter(row => row.valid && row.metric === kind && row.month === month);
|
|
276
|
+
// A node uses its own row when filled; otherwise the sum of its filled
|
|
277
|
+
// children. Levels may be mixed: one region filled at region level,
|
|
278
|
+
// another only by some of its offices. Parents are never split down.
|
|
279
|
+
const resolve = prefix => {
|
|
280
|
+
const below = rows.filter(row => row.depth >= prefix.length && prefix.every((name, index) => row.names[index] === name));
|
|
281
|
+
const own = below.filter(row => row.depth === prefix.length);
|
|
282
|
+
if (own.length > 1) return { error: `${month} 目标表同一组织、指标重复,未自动相加` };
|
|
283
|
+
if (own.length === 1) {
|
|
284
|
+
if (!finite(own[0].value)) return { error: `${month} 目标值缺失或无效` };
|
|
285
|
+
levels.add(prefix.length); return { value: own[0].value };
|
|
286
|
+
}
|
|
287
|
+
if (prefix.length >= 3) return null;
|
|
288
|
+
const children = [...new Set(below.map(row => row.names[prefix.length]))];
|
|
289
|
+
let value = 0, found = false;
|
|
290
|
+
for (const child of children) {
|
|
291
|
+
const result = resolve([...prefix, child]);
|
|
292
|
+
if (result?.error) return result;
|
|
293
|
+
if (result) { value += result.value; found = true; }
|
|
294
|
+
}
|
|
295
|
+
if (found && prefix.length === scope.length) summed = true;
|
|
296
|
+
return found ? { value } : null;
|
|
297
|
+
};
|
|
298
|
+
const result = resolve(scope);
|
|
299
|
+
if (result?.error) return fail(result.error);
|
|
300
|
+
if (!result) {
|
|
301
|
+
const parent = rows.find(row => row.depth < scope.length && row.names.slice(0, row.depth).every((name, index) => scope[index] === name));
|
|
302
|
+
return fail(parent ? `${month} 只有${targetLevels[parent.depth]}目标,尚未拆分到当前组织` : `${month} 未填写当前组织的目标`, 'missing');
|
|
303
|
+
}
|
|
304
|
+
total += result.value * weight;
|
|
305
|
+
}
|
|
306
|
+
const prorated = segments.filter(item => item.weight !== 1);
|
|
307
|
+
const note = `${months.length > 1 ? `${months[0]} 至 ${months.at(-1)}` : months[0]} 目标;取 ${[...levels].map(depth => targetLevels[depth]).join('、')} 层级${summed ? '合计(未填目标的下级不计入)' : ''}${prorated.length ? `;${prorated.map(item => `${item.month} 按 ${item.days}/${item.monthDays} 天折算`).join(',')}` : ''}。`;
|
|
308
|
+
return { label, unit, value: total, state: 'available', reason: null, note, months: [...months], precision: unit === '瓶' ? 0 : 2 };
|
|
309
|
+
}
|
|
310
|
+
function attainment(actual, target, label) {
|
|
311
|
+
const fail = (reason, state = 'pending') => ({ label, unit: '%', value: null, state, reason, target, precision: 1 });
|
|
312
|
+
if (target.state !== 'available') return fail(target.reason, target.state);
|
|
313
|
+
if (!actual || actual.state !== 'available' || !finite(actual.value)) return fail(actual?.reason || '实际值缺失或待确认', actual?.state === 'missing' ? 'missing' : 'pending');
|
|
314
|
+
if (target.value <= 0) return fail('目标不大于零,不计算达成率');
|
|
315
|
+
const value = actual.value / target.value * 100;
|
|
316
|
+
return finite(value) ? { label, unit: '%', value, state: 'available', reason: null, target, actual: actual.value, precision: 1, note: `实际 ${format(actual.unit === '元' ? actual.value / 10000 : actual.value, target.unit === '元' ? 2 : 0)} / 目标 ${format(target.unit === '元' ? target.value / 10000 : target.value, target.unit === '元' ? 2 : 0)} ${target.unit === '元' ? '万元' : target.unit}` } : fail('达成率超出可表示范围');
|
|
317
|
+
}
|
|
318
|
+
// Quarter / fiscal-year windows for the selected month (range mode: the range's end month).
|
|
319
|
+
// Fiscal year runs 1 Jul – 30 Jun; quarters are calendar quarters (fiscal Q1 = Jul–Sep).
|
|
320
|
+
const dayCount = (start, end) => Math.round((Date.parse(`${end}T00:00:00Z`) - Date.parse(`${start}T00:00:00Z`)) / 86400000) + 1;
|
|
321
|
+
function cumulativeWindow(kind, f, p) {
|
|
322
|
+
if (p.mode === 'fixed' || !isDate(p.end) || !/^\d{4}-\d{2}$/.test(f.month || '')) return null;
|
|
323
|
+
const year = Number(f.month.slice(0, 4)), month = Number(f.month.slice(5));
|
|
324
|
+
const first = kind === 'quarter' ? `${year}-${String(Math.floor((month - 1) / 3) * 3 + 1).padStart(2, '0')}` : month >= 7 ? `${year}-07` : `${year - 1}-07`;
|
|
325
|
+
const months = Array.from({ length: kind === 'quarter' ? 3 : 12 }, (_, index) => offsetMonth(first, index));
|
|
326
|
+
const fiscal = month >= 7 ? year : year - 1;
|
|
327
|
+
const label = kind === 'quarter' ? `${Number(months[0].slice(5))}–${Number(months[2].slice(5))} 月` : `${String(fiscal).slice(2)}/${String(fiscal + 1).slice(2)} 财年`;
|
|
328
|
+
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
|
+
return { kind, label, detail, start: `${months[0]}-01`, end: p.end, periodEnd: monthEnd(months.at(-1)), months };
|
|
330
|
+
}
|
|
331
|
+
function cumulativeActual(id, module, window, label) {
|
|
332
|
+
const source = payload.modules[id], cover = payload.coverage[id];
|
|
333
|
+
const base = { label, unit: '元', range: { start: window.start, end: window.end } };
|
|
334
|
+
const fail = (reason, state = 'pending') => ({ ...base, value: null, state, reason });
|
|
335
|
+
if (source.state === 'unavailable') return fail(source.reviewReason || '未接入有效来源', source.reviewPending ? 'pending' : 'missing');
|
|
336
|
+
if (!isDate(cover?.start) || !isDate(cover?.end)) return fail('来源覆盖期间缺失或无效');
|
|
337
|
+
if (cover.start > window.start) return fail(`来源从 ${cover.start} 开始,未覆盖 ${window.start} 起的完整累计期间`);
|
|
338
|
+
if (cover.end < window.start) return fail(`来源截至 ${cover.end},尚无本期记录`, 'missing');
|
|
339
|
+
if (module.scopedRows.some(row => !row.date)) return fail('存在缺失日期的记录,无法完整分期');
|
|
340
|
+
const rows = module.scopedRows.filter(row => row.date >= window.start && row.date <= window.end);
|
|
341
|
+
if (!rows.length) return fail('当前范围在累计期间无来源记录;不推定为业务零值', 'missing');
|
|
342
|
+
return { ...metric(rows, 'amount', source, label, '元'), range: { start: window.start, end: [window.end, cover.end].sort()[0] } };
|
|
343
|
+
}
|
|
344
|
+
// Elapsed share of a period, counted to the earlier of the window end and the source cut-off.
|
|
345
|
+
function timeProgress(id, start, periodEnd, windowEnd) {
|
|
346
|
+
const cover = payload.coverage[id], through = [windowEnd, cover?.end].filter(isDate).sort()[0];
|
|
347
|
+
if (!isDate(start) || !isDate(periodEnd) || !isDate(through) || through < start) return null;
|
|
348
|
+
const days = dayCount(start, [through, periodEnd].sort()[0]), totalDays = dayCount(start, periodEnd);
|
|
349
|
+
return { through, days, totalDays, value: days / totalDays * 100 };
|
|
350
|
+
}
|
|
351
|
+
// A custom range uses each overlapping month's target, prorated by calendar days.
|
|
352
|
+
function targetSegments(start, end) {
|
|
353
|
+
const segments = [];
|
|
354
|
+
if (!isDate(start) || !isDate(end) || start > end) return segments;
|
|
355
|
+
for (let month = start.slice(0, 7); month <= end.slice(0, 7); month = offsetMonth(month, 1)) {
|
|
356
|
+
const first = [`${month}-01`, start].sort().at(-1), last = [monthEnd(month), end].sort()[0];
|
|
357
|
+
const days = Math.round((Date.parse(`${last}T00:00:00Z`) - Date.parse(`${first}T00:00:00Z`)) / 86400000) + 1, monthDays = Number(monthEnd(month).slice(8));
|
|
358
|
+
segments.push({ month, weight: days === monthDays ? 1 : days / monthDays, days, monthDays });
|
|
359
|
+
}
|
|
360
|
+
return segments;
|
|
361
|
+
}
|
|
362
|
+
function periodOf(filters = defaults) {
|
|
363
|
+
const f = { ...defaults, ...filters };
|
|
364
|
+
if (f.period === 'range' && isDate(f.start) && isDate(f.end) && f.start <= f.end)
|
|
365
|
+
return { mode: 'range', start: f.start, end: f.end, month: f.end.slice(0, 7), label: `${f.start} 至 ${f.end}`, days: Math.round((Date.parse(`${f.end}T00:00:00Z`) - Date.parse(`${f.start}T00:00:00Z`)) / 86400000) + 1 };
|
|
366
|
+
if (/^\d{4}-\d{2}$/.test(f.month || '')) return { mode: 'month', start: `${f.month}-01`, end: monthEnd(f.month), month: f.month, label: `${Number(f.month.slice(0, 4))} 年 ${Number(f.month.slice(5))} 月`, days: Number(monthEnd(f.month).slice(8)) };
|
|
367
|
+
return { mode: 'fixed', start: null, end: null, month: f.month, label: '来源固定期间', days: null };
|
|
368
|
+
}
|
|
369
|
+
const yearMonths = month => /^\d{4}-\d{2}$/.test(month || '') ? Array.from({ length: Number(month.slice(5)) }, (_, index) => `${month.slice(0, 4)}-${String(index + 1).padStart(2, '0')}`) : [];
|
|
370
|
+
const periodEnd = (id, filters) => {
|
|
371
|
+
const p = periodOf(filters), cover = payload.coverage[id];
|
|
372
|
+
if (p.mode === 'fixed' || !isDate(cover?.end)) return null;
|
|
373
|
+
const end = [p.end, cover.end].sort()[0];
|
|
374
|
+
return end >= p.start ? end : null;
|
|
375
|
+
};
|
|
376
|
+
function select(filters = defaults) {
|
|
377
|
+
const f = { ...defaults, ...filters }, output = { modules: {}, grouped: [] }, p = periodOf(f);
|
|
378
|
+
if (p.mode === 'range') f.month = p.month;
|
|
379
|
+
output.period = p;
|
|
380
|
+
const inWindow = row => p.mode === 'fixed' ? row.month === f.month : Boolean(row.date) && row.date >= p.start && row.date <= p.end;
|
|
381
|
+
const upToEnd = row => p.mode === 'fixed' ? row.month <= f.month : Boolean(row.date) && row.date <= p.end;
|
|
382
|
+
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
|
+
for (const id of ids) {
|
|
384
|
+
const sourceModule = payload.modules[id], sourceRows = id === 'inventory' && inventoryHistory ? latestInventory(p.end || '9999-12-31') : normalized[id];
|
|
385
|
+
const scoped = sourceRows.filter(row => matchesOrg(row, f) && matchesProduct(id, row, f));
|
|
386
|
+
const rows = scoped.filter(row => id === 'banquet' || (row.month && (['inventory', 'terminal'].includes(id) ? upToEnd(row) : inWindow(row))));
|
|
387
|
+
const [baseLabel, unit, field] = definitions[id];
|
|
388
|
+
const label = p.mode === 'range' ? baseLabel.replace('当月', '区间').replace('截至所选月末', `截至 ${p.end}`) : baseLabel;
|
|
389
|
+
const main = metric(rows, field, sourceModule, label, unit);
|
|
390
|
+
const extra = [];
|
|
391
|
+
if (id === 'invoice' || id === 'movement') {
|
|
392
|
+
extra.push(metric(scoped.filter(yearToEnd), 'amount', sourceModule, '当年截至所选月来源金额', '元'));
|
|
393
|
+
extra.push(metric(rows.filter(row => finite(row.amount) && row.amount > 0), 'amount', sourceModule, '正金额合计', '元', main.state !== 'available'));
|
|
394
|
+
extra.push(metric(rows.filter(row => finite(row.amount) && row.amount < 0), 'amount', sourceModule, '负金额合计', '元', main.state !== 'available'));
|
|
395
|
+
}
|
|
396
|
+
if (id === 'movement') {
|
|
397
|
+
extra.push(metric(rows.filter(row => row.quantityUnit === '瓶'), 'bottles', sourceModule, '扫码数量(瓶单位记录)', '瓶'));
|
|
398
|
+
extra.push(metric(rows.filter(row => row.quantityUnit === '盒'), 'boxes', sourceModule, '扫码数量(盒单位记录)', '盒'));
|
|
399
|
+
extra.push(metric(rows, 'cases', sourceModule, '来源扫码件数', '源件数'));
|
|
400
|
+
extra.push({ label: '单位未确认记录数', unit: '条', value: sourceModule.state === 'unavailable' ? null : rows.filter(row => !['瓶', '盒'].includes(row.quantityUnit)).length, state: sourceModule.state === 'unavailable' ? 'missing' : 'available' });
|
|
401
|
+
}
|
|
402
|
+
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
|
+
if (id === 'opening') {
|
|
404
|
+
extra.push(metric(rows, 'amount', sourceModule, '现金红包金额', '元'));
|
|
405
|
+
extra.push(ratio(sum(rows, 'amount'), sum(rows, 'bottles'), '瓶均现金红包', '元/瓶', main.state === 'available' && extra[0].state === 'available'));
|
|
406
|
+
}
|
|
407
|
+
if (id === 'terminal') {
|
|
408
|
+
extra.push(metric(rows, 'agreementCount', sourceModule, '按已确认去重规则保留协议数', '份'));
|
|
409
|
+
}
|
|
410
|
+
if (id === 'inventory') {
|
|
411
|
+
extra.push(metric(rows, 'system', sourceModule, '所选记录系统瓶数合计', '瓶'));
|
|
412
|
+
extra.push(metric(rows, 'countAmount', sourceModule, '所选记录盘点金额合计', '元'));
|
|
413
|
+
extra.push(metric(rows, 'systemAmount', sourceModule, '所选记录系统金额合计', '元'));
|
|
414
|
+
extra.push(metric(rows, 'absoluteVariance', sourceModule, '逐条绝对差异合计', '瓶'));
|
|
415
|
+
extra.push(metric(rows, 'signedVariance', sourceModule, '盘点减系统差异合计', '瓶'));
|
|
416
|
+
extra.push({ label: '源偏差数量缺失记录', unit: '条', value: sourceModule.state === 'unavailable' ? null : rows.filter(row => row.sourceVariance === null).length, state: sourceModule.state === 'unavailable' ? 'missing' : 'available' });
|
|
417
|
+
extra.push({ label: '产品品类未映射记录', unit: '条', value: sourceModule.state === 'unavailable' ? null : rows.filter(row => !row.brand || !row.category).length, state: sourceModule.state === 'unavailable' ? 'missing' : 'available' });
|
|
418
|
+
}
|
|
419
|
+
if (id === 'banquet') {
|
|
420
|
+
extra.push(metric(rows, 'bottles', sourceModule, '固定期间宴席开瓶', '瓶'));
|
|
421
|
+
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
|
+
}
|
|
424
|
+
const hasSourcePeriod = normalized[id].some(row => id === 'banquet' || row.month && (['inventory', 'terminal'].includes(id) ? upToEnd(row) : inWindow(row)));
|
|
425
|
+
if (!hasSourcePeriod && sourceModule.state !== 'unavailable') for (const item of [main, ...extra]) { item.value = null; item.state = 'missing'; item.reason = '该期间无来源记录'; }
|
|
426
|
+
// One pass groups rows by month in their original order (same sums as filtering per month).
|
|
427
|
+
const scopedByMonth = new Map();
|
|
428
|
+
for (const row of scoped) { let list = scopedByMonth.get(row.month); if (!list) { list = []; scopedByMonth.set(row.month, list); } list.push(row); }
|
|
429
|
+
const monthly = months.filter(month => month !== 'fixed').map(month => {
|
|
430
|
+
const monthRows = scopedByMonth.get(month) || [];
|
|
431
|
+
const m = metric(monthRows, id === 'inventory' && inventoryHistory ? 'records' : id === 'terminal' ? 'agreementCount' : field, sourceModule, month, id === 'inventory' && inventoryHistory ? '条' : id === 'terminal' ? '条' : unit);
|
|
432
|
+
if (!monthRows.length) { m.value = null; m.state = 'missing'; m.reason = '该月无来源记录'; }
|
|
433
|
+
return { month, ...m };
|
|
434
|
+
});
|
|
435
|
+
const grouping = f.region === 'all' ? 'region' : f.office === 'all' ? 'office' : 'unit';
|
|
436
|
+
const groupMap = new Map();
|
|
437
|
+
for (const row of rows) { const key = row[grouping]; if (!groupMap.has(key)) groupMap.set(key, []); groupMap.get(key).push(row); }
|
|
438
|
+
const groups = [...groupMap].map(([name, records]) => ({ name, records: records.length, ...metric(records, field, sourceModule, name, unit) })).sort((a, b) => (b.value ?? -Infinity) - (a.value ?? -Infinity));
|
|
439
|
+
const breakdowns = [];
|
|
440
|
+
const distribution = (title, keyFor, labelFor, measure, measureUnit) => {
|
|
441
|
+
const grouped = new Map();
|
|
442
|
+
for (const row of rows) { const key = keyFor(row); if (!grouped.has(key)) grouped.set(key, []); grouped.get(key).push(row); }
|
|
443
|
+
const items = [...grouped.values()].map(items => ({ name: labelFor(items[0]), records: items.length, ...metric(items, measure, sourceModule, labelFor(items[0]), measureUnit) })).sort((a, b) => (b.value ?? -Infinity) - (a.value ?? -Infinity));
|
|
444
|
+
breakdowns.push({ title, unit: measureUnit, items });
|
|
445
|
+
};
|
|
446
|
+
if (['invoice', 'movement', 'inventory'].includes(id) && !(id === 'inventory' && inventoryHistory)) {
|
|
447
|
+
const amountField = id === 'inventory' ? 'countAmount' : 'amount';
|
|
448
|
+
distribution('品牌金额构成', row => row.brand || '', row => row.brand || '未映射品牌', amountField, '元');
|
|
449
|
+
distribution('品类金额构成', row => JSON.stringify([row.brand, row.category]), row => `${row.brand || '未映射品牌'} / ${row.category || '未映射品类'}`, amountField, '元');
|
|
450
|
+
}
|
|
451
|
+
if (id === 'invoice') distribution('经销商编码汇总', row => row.dealerCode || '', row => row.dealerCode ? `${row.dealerCode} · ${row.dealerName || '未提供名称'}` : '未提供经销商编码(不推定身份)', 'amount', '元');
|
|
452
|
+
if (id === 'opening') distribution('开瓶城市分布', row => row.city || '', row => row.city || '未提供城市', 'bottles', '瓶');
|
|
453
|
+
if (id === 'terminal') distribution('协议记录星级分布', row => row.star || '', row => row.star || '未提供星级', 'agreementCount', '条');
|
|
454
|
+
if (id === 'inventory' && !inventoryHistory) distribution('来源安全库存状态', row => row.safety || '', row => row.safety || '未提供状态', 'records', '条');
|
|
455
|
+
const monthUnknown = id !== 'banquet' && scoped.some(row => !row.date);
|
|
456
|
+
const unknownMessage = monthUnknown ? ['存在缺失日期的记录,无法完整分期;月份合计、月度图表和区域金额暂不计算。'] : [];
|
|
457
|
+
if (normalized[id].some(row => partsFor(row).slice(0, 3).some(value => !value))) unknownMessage.push('来源部分上级组织字段未提供;仅完整路径相同才联动,尚未自动补齐或归并。');
|
|
458
|
+
if (id === 'inventory' && !inventoryHistory) {
|
|
459
|
+
const mismatched = rows.filter(row => finite(row.sourceVariance) && finite(row.absoluteVariance) && Math.abs(row.sourceVariance - row.absoluteVariance) > 1e-8).length;
|
|
460
|
+
if (mismatched) unknownMessage.push(`${mismatched} 条记录的源偏差数量与逐条绝对差异不一致;两种值分别保留,不互相覆盖。`);
|
|
461
|
+
}
|
|
462
|
+
if (monthUnknown) for (const item of [main, ...extra, ...monthly, ...groups, ...breakdowns.flatMap(x => x.items)]) { item.value = null; item.state = 'pending'; item.reason = '存在缺失日期,无法完整分期'; }
|
|
463
|
+
if (sourceModule.state === 'unavailable') for (const item of [main, ...extra]) { item.value = null; item.state = sourceModule.reviewPending ? 'pending' : 'missing'; item.reason = sourceModule.reviewReason || '未接入有效来源'; }
|
|
464
|
+
if (sourceModule.reviewPending) unknownMessage.push(sourceModule.reviewReason);
|
|
465
|
+
if (rows.length === 0 && sourceModule.state !== 'unavailable') for (const item of [main, ...extra]) { item.value = null; item.state = 'missing'; item.reason = '当前范围无来源记录;不推定为业务零值'; }
|
|
466
|
+
output.modules[id] = { id, title: titles[id], color: colors[id], main, extra, rows, scopedRows: scoped, recordCount: rows.length, monthly, groups, breakdowns, groupField: grouping,
|
|
467
|
+
state: sourceModule.state, period: period(id, f), pending: [...pending[id], ...unknownMessage], source: payload.sources[id] || null };
|
|
468
|
+
if (id === 'inventory' && inventoryHistory) {
|
|
469
|
+
const uncertain = (sourceModule.uncertaintyGroups || []).filter(group => (group.organizations || []).some(value => {
|
|
470
|
+
const parts = value.orgPath;
|
|
471
|
+
return Array.isArray(parts) && matchesOrg({ region: JSON.stringify(parts.slice(0, 4)), office: JSON.stringify(parts.slice(0, 5)), unit: JSON.stringify(parts) }, f);
|
|
472
|
+
}));
|
|
473
|
+
if (uncertain.length) for (const item of [main, ...extra, ...groups]) {
|
|
474
|
+
item.value = null; item.state = 'unavailable'; item.reason = '当前组织有提交时间无效的盘点,不能保证最新记录选择完整';
|
|
475
|
+
}
|
|
476
|
+
const dates = rows.map(row => row.date).filter(Boolean).sort();
|
|
477
|
+
output.modules[id].inventoryMode = 'visit-history';
|
|
478
|
+
output.modules[id].inventoryStats = { ...(sourceModule.inventoryStats || {}),
|
|
479
|
+
cutoffDate: inventoryCutoff(p.end),
|
|
480
|
+
groupCount: new Set(rows.map(row => row.inventoryGroupKey)).size,
|
|
481
|
+
conflictRows: rows.filter(row => row.inventoryConflict).length,
|
|
482
|
+
uncertainGroups: uncertain.length, latestMinDate: dates[0] || null, latestMaxDate: dates.at(-1) || null,
|
|
483
|
+
oldRecordCount: rows.filter(row => row.date && row.date.slice(0, 4) < f.month.slice(0, 4)).length };
|
|
484
|
+
if (!rows.length && f.region !== 'all') for (const item of [main, ...extra]) {
|
|
485
|
+
if (item.reason === '当前范围无来源记录;不推定为业务零值') item.reason = '当前完整组织路径没有库存记录;新库存与其他来源的组织映射尚未确认,请使用库存来源组织路径';
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
{
|
|
490
|
+
const module = output.modules.opening, end = periodEnd('opening', f), grouping = output.modules.opening.groupField;
|
|
491
|
+
const groups = new Map();
|
|
492
|
+
for (const row of module.scopedRows) { const key = row[grouping]; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(row); }
|
|
493
|
+
module.dayChange = { ...dayChange(module.scopedRows, end), groups: [...groups].map(([key, items]) => ({ key, ...dayChange(items, end, key) }))
|
|
494
|
+
.sort((a, b) => (finite(b.current) ? b.current : -Infinity) - (finite(a.current) ? a.current : -Infinity)) };
|
|
495
|
+
}
|
|
496
|
+
for (const id of ['invoice', 'movement', 'opening']) {
|
|
497
|
+
const module = output.modules[id], range = p.mode === 'range';
|
|
498
|
+
const ytdActual = id === 'opening' ? metric(module.scopedRows.filter(yearToEnd), 'bottles', payload.modules.opening, '当年截至所选月开瓶', '瓶')
|
|
499
|
+
: module.extra.find(item => item.label === '当年截至所选月来源金额');
|
|
500
|
+
const monthTarget = targetValue(id, f, p.mode === 'fixed' ? [] : range ? targetSegments(p.start, p.end) : [{ month: f.month, weight: 1, days: null }], range ? '区间目标' : '当月目标');
|
|
501
|
+
const ytdTarget = targetValue(id, f, p.mode === 'fixed' ? [] : range ? targetSegments(`${f.month.slice(0, 4)}-01-01`, p.end) : yearMonths(f.month).map(month => ({ month, weight: 1, days: null })), '年累计目标');
|
|
502
|
+
module.targets = { available: Boolean(targetSource), month: monthTarget, ytd: ytdTarget,
|
|
503
|
+
attainment: attainment(module.main, monthTarget, range ? '区间目标达成率' : '当月目标达成率'), ytdAttainment: attainment(ytdActual, ytdTarget, '年累计目标达成率') };
|
|
504
|
+
if (id === 'opening') continue;
|
|
505
|
+
// 当月时间进度(按月模式;区间目标已按天折算,不再给进度)。
|
|
506
|
+
module.targets.monthProgress = p.mode === 'month' ? timeProgress(id, p.start, p.end, p.end) : null;
|
|
507
|
+
// 季度(自然季度 = 财年 Q3/Q4/Q1/Q2)与财年(7 月 1 日起):累计实际对全期整月目标。
|
|
508
|
+
for (const kind of ['quarter', 'fiscal']) {
|
|
509
|
+
const window = cumulativeWindow(kind, f, p);
|
|
510
|
+
if (!window) { module.targets[kind] = null; continue; }
|
|
511
|
+
const name = kind === 'quarter' ? '季度' : '财年';
|
|
512
|
+
const actual = cumulativeActual(id, module, window, `${name}累计`);
|
|
513
|
+
const target = targetValue(id, f, window.months.map(month => ({ month, weight: 1, days: null })), `${name}目标`);
|
|
514
|
+
module.targets[kind] = { ...window, actual, target, attainment: attainment(actual, target, `${name}目标达成率`),
|
|
515
|
+
progress: timeProgress(id, window.start, window.periodEnd, window.end) };
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const crossMetrics = crossTableMetrics(f);
|
|
519
|
+
for (const id of ids) output.modules[id].crossMetrics = crossMetrics[id] || [];
|
|
520
|
+
output.groupField = f.region === 'all' ? 'region' : f.office === 'all' ? 'office' : 'unit';
|
|
521
|
+
const structure = terminalBuilder({ terminalRows: normalized.terminal.filter(row => matchesOrg(row, f)),
|
|
522
|
+
// The builder matches exact signed organization paths itself. Retain scans
|
|
523
|
+
// with missing identities so narrowing a filter cannot turn unknowns into 0.
|
|
524
|
+
movementRows: normalized.movement, allTerminalRows: normalized.terminal,
|
|
525
|
+
month: f.month, endDate: p.end, groupField: output.groupField, terminalState: payload.modules.terminal.state,
|
|
526
|
+
movementState: payload.modules.movement.state, identityState: ruleReady('terminalIdentity', ['terminal', 'movement']) ? 'confirmed' : 'pending',
|
|
527
|
+
sourceEnd: payload.coverage.movement?.end || null });
|
|
528
|
+
const terminalModule = output.modules.terminal;
|
|
529
|
+
terminalModule.structure = structure;
|
|
530
|
+
terminalModule.pending = structure.notes;
|
|
531
|
+
const effectiveMetric = (label, value, unit, precision = 0) => ({ label, value, unit, precision,
|
|
532
|
+
state: terminalModule.state === 'unavailable' ? 'missing' : value === null ? 'pending' : 'available',
|
|
533
|
+
reason: value === null ? '来源、日期、品系或件数不足以完整判定' : null });
|
|
534
|
+
terminalModule.extra.push(effectiveMetric('有效终端数', structure.totals.effectiveCount, '家'));
|
|
535
|
+
terminalModule.extra.push(effectiveMetric('有效率', structure.totals.effectiveRate === null ? null : structure.totals.effectiveRate * 100, '%', 1));
|
|
536
|
+
terminalModule.breakdowns = [];
|
|
537
|
+
output.grouped = [...new Set(organizations.filter(row => matchesOrg(row, f)).map(row => row[output.groupField]))].map(name => {
|
|
538
|
+
const groupValue = id => {
|
|
539
|
+
const module = output.modules[id];
|
|
540
|
+
if (module.state === 'unavailable' || module.main.state !== 'available') return null;
|
|
541
|
+
const selected = module.rows.filter(row => row[output.groupField] === name);
|
|
542
|
+
return selected.length ? sum(selected, 'amount') : null;
|
|
543
|
+
};
|
|
544
|
+
return { name, invoice: groupValue('invoice'), movement: groupValue('movement') };
|
|
545
|
+
});
|
|
546
|
+
return output;
|
|
547
|
+
}
|
|
548
|
+
// Distinct complete paths may share a short label. Add the known parent path
|
|
549
|
+
// only for those collisions, without silently joining identities.
|
|
550
|
+
const inventoryOnlyLabels = new Set();
|
|
551
|
+
if (inventoryHistory) {
|
|
552
|
+
const sharedKeys = new Set(ids.filter(id => id !== 'inventory').flatMap(id => normalized[id].flatMap(row => [row.region, row.office, row.unit])));
|
|
553
|
+
for (const row of normalized.inventory) for (const key of [row.region, row.office, row.unit]) if (!sharedKeys.has(key)) inventoryOnlyLabels.add(key);
|
|
554
|
+
// New inventory-only paths must not change labels on the other five boards.
|
|
555
|
+
// Keep their exact filter identities; distinguish their display names here.
|
|
556
|
+
for (const key of inventoryOnlyLabels) labels.set(key, `库存来源 · ${labels.get(key)}`);
|
|
557
|
+
}
|
|
558
|
+
const labelCounts = new Map();
|
|
559
|
+
for (const [id, label] of labels) { const group = labelCounts.get(label) || []; group.push(id); labelCounts.set(label, group); }
|
|
560
|
+
for (const matches of labelCounts.values()) if (matches.length > 1) for (const id of matches) labels.set(id, `${inventoryOnlyLabels.has(id) ? '库存来源 · ' : ''}${fullLabels.get(id)}`);
|
|
561
|
+
const label = id => labels.get(id) || id;
|
|
562
|
+
// Bounds for the custom range control: every dated flow source.
|
|
563
|
+
const flowCoverage = ['invoice', 'movement', 'opening'].map(id => payload.modules[id].state !== 'unavailable' ? payload.coverage[id] : null).filter(cover => isDate(cover?.start) && isDate(cover?.end));
|
|
564
|
+
const dateBounds = flowCoverage.length ? { min: flowCoverage.map(cover => cover.start).sort()[0], max: flowCoverage.map(cover => cover.end).sort().at(-1) } : null;
|
|
565
|
+
return { ids, titles, colors, definitions, targetSource, periodOf, dateBounds, organizations, categories, months, defaults, payload, select, format, formatMetric, period, label,
|
|
566
|
+
scope: filters => label(filters.unit !== 'all' ? filters.unit : filters.office !== 'all' ? filters.office : filters.region !== 'all' ? filters.region : '全战区'),
|
|
567
|
+
previewNotice: '来自本次生成锁定的本机上传版本;未提供来源和待确认指标明确标示,不使用演示值。' };
|
|
568
|
+
}
|