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.
Files changed (71) hide show
  1. package/README.md +35 -2
  2. package/assets/theater-board.svg +1 -0
  3. package/backend/incremental/flow.mjs +492 -0
  4. package/backend/incremental/jobs.mjs +58 -0
  5. package/backend/incremental/xlsx-rows.mjs +145 -0
  6. package/backend/job-worker.mjs +22 -0
  7. package/backend/modules/banquet/index.mjs +46 -0
  8. package/backend/modules/inventory/index.mjs +45 -0
  9. package/backend/modules/inventory/legacy-fields.mjs +83 -0
  10. package/backend/modules/invoice/index.mjs +72 -0
  11. package/backend/modules/movement/index.mjs +68 -0
  12. package/backend/modules/opening/index.mjs +48 -0
  13. package/backend/modules/target/index.mjs +45 -0
  14. package/backend/modules/terminal/index.mjs +114 -0
  15. package/backend/modules.mjs +12 -0
  16. package/backend/public/admin.css +220 -0
  17. package/backend/public/admin.js +772 -0
  18. package/backend/public/board.css +70 -0
  19. package/backend/public/board.html +50 -0
  20. package/backend/public/board.js +153 -0
  21. package/backend/public/index.html +113 -0
  22. package/backend/public/org-mapping.js +49 -0
  23. package/backend/public/review.css +5 -0
  24. package/backend/public/review.js +452 -0
  25. package/backend/real-data/generate-dashboard.mjs +137 -0
  26. package/backend/real-data/inventory-history.mjs +316 -0
  27. package/backend/real-data/organization-mapping.mjs +166 -0
  28. package/backend/real-data/source-payload.mjs +459 -0
  29. package/backend/real-data/terminal-components.mjs +280 -0
  30. package/backend/real-data/terminal-structure.css +105 -0
  31. package/backend/real-data/terminal-structure.mjs +276 -0
  32. package/backend/real-data/v10-components.mjs +112 -0
  33. package/backend/real-data/v10-details.css +18 -0
  34. package/backend/real-data/v10-details.mjs +251 -0
  35. package/backend/real-data/v10-layout.css +27 -0
  36. package/backend/real-data/v10-model.mjs +568 -0
  37. package/backend/real-data/v10-overview-data.mjs +253 -0
  38. package/backend/real-data/v10-overview.css +370 -0
  39. package/backend/real-data/v10-overview.mjs +340 -0
  40. package/backend/real-data/v10-presentation.mjs +354 -0
  41. package/backend/real-data/v10-shell.html +1097 -0
  42. package/backend/real-data/v10-template.mjs +353 -0
  43. package/backend/recognition/fingerprint.mjs +32 -0
  44. package/backend/recognition/headers.mjs +2 -0
  45. package/backend/recognition/module-definition.mjs +4 -0
  46. package/backend/recognition/result.mjs +29 -0
  47. package/backend/recognition/upload-limits.mjs +14 -0
  48. package/backend/review-engine.mjs +364 -0
  49. package/backend/review-service.mjs +182 -0
  50. package/backend/server.mjs +569 -0
  51. package/backend/store.mjs +68 -0
  52. package/backend/target-template.mjs +47 -0
  53. package/backend/validate-workbook.mjs +251 -0
  54. package/backend/web-sync/README.md +37 -0
  55. package/backend/web-sync/client.mjs +63 -0
  56. package/backend/web-sync/exporter.mjs +260 -0
  57. package/backend/web-sync/local.html +34 -0
  58. package/backend/web-sync/server.mjs +147 -0
  59. package/build-manifest.json +80 -0
  60. package/client.js +54 -0
  61. package/cordis.patch.yml +3 -0
  62. package/index.js +117 -0
  63. package/lib/dist-manifest.mjs +19 -0
  64. package/lib/market-index.mjs +56 -0
  65. package/lib/package-audit.mjs +34 -0
  66. package/lib/settings.mjs +71 -0
  67. package/lib/tool-definitions.mjs +56 -0
  68. package/lib/tools.mjs +255 -0
  69. package/locale/en.json +6 -0
  70. package/locale/zh.json +6 -0
  71. package/package.json +71 -4
@@ -0,0 +1,452 @@
1
+ 'use strict';
2
+
3
+ // All workbook text is rendered with textContent. Draft choices stay in memory
4
+ // across polling; only an explicit save creates a persisted business decision.
5
+ window.ReviewUI = (() => {
6
+ const pathLabels = ['营销公司', '事业部', '战区', '大区', '办事处', '单元'];
7
+ const stateLabels = {missing: '待上传', unchecked: '尚未检查', ready: '可以使用', pending: '待确认', error: '需要核对'};
8
+ const drafts = new Map();
9
+ const organizationDrafts = new Map();
10
+ let bridge;
11
+ let review = null;
12
+ let requestInFlight = null;
13
+ let stateSignature = '';
14
+ let renderSignature = '';
15
+ let actionBusy = false;
16
+ let fileBackup = null;
17
+
18
+ function node(tag, className, text) {
19
+ const result = document.createElement(tag);
20
+ if (className) result.className = className;
21
+ if (text !== undefined) result.textContent = text;
22
+ return result;
23
+ }
24
+ const $ = selector => document.querySelector(selector);
25
+ const readablePath = path => (path || []).map((part, index) => part || `未提供${pathLabels[index]}`).join(' / ');
26
+ const pretty = value => value === null || value === undefined || value === '' ? '—' : typeof value === 'object' ? JSON.stringify(value) : String(value);
27
+ const amount = value => Number(value).toLocaleString('zh-CN', {maximumFractionDigits: 2});
28
+ const time = value => value ? new Date(value).toLocaleString('zh-CN', {hour12: false}) : '—';
29
+
30
+ function notice(message, error = false) {
31
+ const target = $('#review-notice');
32
+ target.textContent = message;
33
+ target.hidden = !message;
34
+ target.className = `notice${error ? ' error' : ''}`;
35
+ }
36
+
37
+ function button(label, handler, className = 'button button-secondary') {
38
+ const result = node('button', className, label);
39
+ result.type = 'button';
40
+ result.addEventListener('click', handler);
41
+ result.dataset.reviewAction = 'true';
42
+ return result;
43
+ }
44
+
45
+ function labelInput(label, input) {
46
+ const result = node('label', 'review-label');
47
+ // A select's option text must not become part of its accessible name.
48
+ input.setAttribute('aria-label', label);
49
+ result.append(node('span', '', label), input);
50
+ return result;
51
+ }
52
+
53
+ function option(value, label) {
54
+ const result = node('option', '', label);
55
+ result.value = value;
56
+ return result;
57
+ }
58
+
59
+ function field(type = 'text') {
60
+ const input = node('input', 'review-input');
61
+ input.type = type;
62
+ return input;
63
+ }
64
+
65
+ function checkbox(text, checked, onChange) {
66
+ const label = node('label', 'review-check');
67
+ const input = field('checkbox');
68
+ input.checked = checked;
69
+ input.addEventListener('change', () => onChange(input.checked));
70
+ label.append(input, node('span', '', text));
71
+ return {label, input};
72
+ }
73
+
74
+ function download(name, data, type = 'application/json') {
75
+ const url = URL.createObjectURL(new Blob([data], {type}));
76
+ const link = node('a');
77
+ link.href = url; link.download = name;
78
+ document.body.append(link); link.click(); link.remove();
79
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
80
+ }
81
+
82
+ async function refresh(force = false) {
83
+ if (requestInFlight) { await requestInFlight; return; }
84
+ if (!bridge?.getState()?.token) return;
85
+ requestInFlight = (async () => {
86
+ try {
87
+ const next = await bridge.request('/api/review');
88
+ apply(next, force);
89
+ } catch (error) {
90
+ notice(`检查结果暂时无法读取:${error.message}`, true);
91
+ } finally { requestInFlight = null; }
92
+ })();
93
+ await requestInFlight;
94
+ }
95
+
96
+ function controls() {
97
+ const disabled = actionBusy || Boolean(bridge?.isBusy());
98
+ document.querySelectorAll('[data-review-action]').forEach(item => { item.disabled = disabled; });
99
+ $('#review-restore-confirm').disabled = disabled || !fileBackup;
100
+ $('#generate-pending-button').disabled = disabled || !review?.modules?.some(module => module.uploadId);
101
+ $('#review-check-button').disabled = disabled || !bridge?.getState()?.token;
102
+ }
103
+
104
+ async function mutate(path, payload, success) {
105
+ if (actionBusy || bridge.isBusy() || !review) return false;
106
+ actionBusy = true;
107
+ controls();
108
+ bridge.setWorking({kind: 'review', stage: '正在保存检查与处理结果'});
109
+ notice('');
110
+ try {
111
+ const result = await bridge.request(path, {
112
+ method: 'POST',
113
+ headers: {'Content-Type': 'application/json', 'X-Local-Token': bridge.getState().token},
114
+ body: JSON.stringify({revision: review.revision, ...payload}),
115
+ });
116
+ if (result.review) apply(result.review, true);
117
+ if (result.state) bridge.applyState(result.state);
118
+ if (!result.review) await refresh(true);
119
+ notice(success);
120
+ return true;
121
+ } catch (error) {
122
+ notice(error.message, true);
123
+ if (error.data?.review) apply(error.data.review, true);
124
+ else await refresh(true);
125
+ return false;
126
+ } finally {
127
+ actionBusy = false;
128
+ bridge.setWorking(null);
129
+ controls();
130
+ }
131
+ }
132
+
133
+ function apply(next, force = false) {
134
+ if (!next || !Array.isArray(next.modules)) return;
135
+ review = next;
136
+ const signature = JSON.stringify(next);
137
+ if (force || signature !== renderSignature) {
138
+ renderSignature = signature;
139
+ render();
140
+ }
141
+ controls();
142
+ }
143
+
144
+ function rememberDraft(module, group) {
145
+ const key = `${module.uploadId}:${group.key}`;
146
+ if (!drafts.has(key)) drafts.set(key, {
147
+ keep: new Set(group.status === 'resolved' ? group.keepKeys || [] : []),
148
+ remember: false,
149
+ dirty: false,
150
+ });
151
+ // Read-only resolved groups always reflect the persisted decision, including
152
+ // a change made by another open page or by restoring a settings backup.
153
+ if (group.status === 'resolved') {
154
+ drafts.get(key).keep = new Set(group.keepKeys || []);
155
+ drafts.get(key).dirty = false;
156
+ }
157
+ return drafts.get(key);
158
+ }
159
+
160
+ function candidateGroup(module, group, index) {
161
+ const box = node('details', `review-group ${group.status === 'resolved' ? 'resolved' : 'pending'}`);
162
+ box.dataset.openKey = `group:${module.uploadId}:${group.key}`;
163
+ box.open = group.status !== 'resolved';
164
+ const summary = node('summary');
165
+ summary.append(node('strong', '', `第 ${index + 1} 组 · ${group.rows.length} 条候选`), node('span', `status ${group.status === 'resolved' ? 'ready' : 'running'}`, group.status === 'resolved' ? group.reused ? '已复用决定' : '已处理' : '待确认'));
166
+ box.append(summary);
167
+ const content = node('div', 'review-group-body');
168
+ content.append(node('p', 'review-help', group.reason || '请核对这些记录是否都应计入。'));
169
+ if (group.status === 'resolved') content.append(node('p', 'review-help', `已保存:计入 ${group.keepKeys?.length ?? 0} 条。修改时请先撤销原决定,再重新选择。`));
170
+ if (group.conflict || group.conflicts?.length) content.append(node('p', 'review-error', '保存的处理决定存在冲突。请在“处理记录”撤销冲突决定后重新确认。'));
171
+ const draft = rememberDraft(module, group);
172
+ const identity = module.id === 'invoice' ? ['业务日期', '单据类型', '单据编码', '单据行号', '发票金额', '计价数量', '计价单位'] : ['协议编号', '网点编号', '网点名称', '协议名称', '签约日期', '星级'];
173
+ const columns = [...new Set([...identity, ...(group.differentFields || []), ...(module.id === 'invoice' ? ['销售大区', '办事处', '客户主任单元'] : ['大区', '办事处', '主任单元'])])].filter(key => group.rows.some(row => Object.hasOwn(row.values || {}, key)));
174
+ const tableWrap = node('div', 'review-table-wrap');
175
+ const table = node('table', 'review-table');
176
+ const caption = node('caption', 'sr-only', `${module.title}第 ${index + 1} 组重复候选`);
177
+ table.append(caption);
178
+ const head = node('thead'); const header = node('tr');
179
+ for (const title of ['计入', 'Excel 行号', ...columns]) { const th = node('th', '', title); th.scope = 'col'; header.append(th); }
180
+ head.append(header); table.append(head);
181
+ const body = node('tbody'); const checks = [];
182
+ const preview = node('p', 'review-impact'); preview.setAttribute('aria-live', 'polite');
183
+ const save = button('确认计入选中记录', async () => {
184
+ if (!draft.keep.size) { notice('请至少选择一条应计入的记录;拿不准可以稍后处理。', true); return; }
185
+ const ok = await mutate('/api/review/decisions', {uploadId: module.uploadId, groupKey: group.key, keepKeys: [...draft.keep], remember: draft.remember}, '这组处理已保存,原始 Excel 没有改动。');
186
+ if (ok) drafts.delete(`${module.uploadId}:${group.key}`);
187
+ }, 'button button-primary');
188
+ function updateImpact() {
189
+ const selected = group.rows.filter(row => draft.keep.has(row.key));
190
+ let text = `本组 ${group.rows.length} 条,已选择 ${selected.length} 条计入,${group.rows.length - selected.length} 条不计入。`;
191
+ if (!selected.length) text = '尚未选择。本组仍为待确认,不会把未选记录自动当作应排除。';
192
+ else if (module.id === 'invoice') {
193
+ const values = group.rows.map(row => row.amount ?? row.values?.发票金额);
194
+ if (values.every(value => value !== null && value !== '' && Number.isFinite(Number(value)))) {
195
+ const sum = selected.reduce((total, row) => total + Number(row.amount ?? row.values?.发票金额), 0);
196
+ const all = values.reduce((total, value) => total + Number(value), 0);
197
+ text += ` 本组计入 ${amount(sum)} 元;相比全部计入,金额变化 ${sum - all > 0 ? '+' : ''}${amount(sum - all)} 元。`;
198
+ } else text += ' 金额含缺失或无法识别的值,不能预览完整金额。';
199
+ } else text += ' 协议数按保留记录计算;终端家数仍按终端身份去重,有效率重新计算。';
200
+ preview.textContent = text;
201
+ save.dataset.emptySelection = selected.length ? '' : 'true';
202
+ }
203
+ for (const row of group.rows) {
204
+ const tr = node('tr'); const choiceCell = node('td');
205
+ const choice = field('checkbox'); choice.checked = draft.keep.has(row.key);
206
+ choice.setAttribute('aria-label', `计入 Excel 第 ${row.row} 行`);
207
+ choice.disabled = group.status === 'resolved';
208
+ choice.addEventListener('change', () => { if (choice.checked) draft.keep.add(row.key); else draft.keep.delete(row.key); draft.dirty = true; updateImpact(); });
209
+ checks.push([choice, row]); choiceCell.append(choice); tr.append(choiceCell, node('td', '', row.row));
210
+ for (const column of columns) tr.append(node('td', group.differentFields?.includes(column) ? 'review-difference' : '', pretty(row.values?.[column])));
211
+ body.append(tr);
212
+ }
213
+ table.append(body); tableWrap.append(table); content.append(tableWrap);
214
+ const allFields = node('details', 'review-all-fields'); allFields.dataset.openKey = `fields:${module.uploadId}:${group.key}`;
215
+ allFields.append(node('summary', '', '查看全部字段'));
216
+ for (const row of group.rows) {
217
+ const details = node('dl', 'review-fields');
218
+ details.append(node('dt', '', 'Excel 行号'), node('dd', '', row.row));
219
+ for (const [name, value] of Object.entries(row.values || {})) details.append(node('dt', '', name), node('dd', '', pretty(value)));
220
+ allFields.append(details);
221
+ }
222
+ content.append(allFields, preview);
223
+ if (group.status !== 'resolved') {
224
+ const scope = checkbox('记住这一组决定,下次内容完全对应时继续使用', draft.remember, checked => { draft.remember = checked; draft.dirty = true; });
225
+ const actions = node('div', 'review-actions');
226
+ actions.append(button('全部计入', () => { for (const [choice, row] of checks) { choice.checked = true; draft.keep.add(row.key); } draft.dirty = true; updateImpact(); }), button('清空选择', () => { for (const [choice] of checks) choice.checked = false; draft.keep.clear(); draft.dirty = true; updateImpact(); }), save, button('暂不处理', () => { box.open = false; notice('这组仍为待确认。已确认的处理结果保存在本机,可从本次数据检查继续。'); }));
227
+ content.append(scope.label, node('p', 'review-help', '不勾选时仅本次来源使用。保存前请核对上方影响;不会将本组决定扩大到其他业务。'), actions);
228
+ } else if (group.decisionId) {
229
+ content.append(button('撤销这组决定', () => revoke(group.decisionId)));
230
+ } else content.append(node('p', 'review-help', '沿用此前与本文件绑定的已确认处理。可在处理记录中查看来源。'));
231
+ updateImpact();
232
+ box.append(content);
233
+ return box;
234
+ }
235
+
236
+ function organizationEditor(module) {
237
+ const section = node('details', 'review-organizations');
238
+ section.dataset.openKey = `org:${module.uploadId}`;
239
+ section.append(node('summary', '', `组织对应 · ${module.inspection.organizations?.length || 0} 条来源路径`));
240
+ const content = node('div', 'review-group-body');
241
+ content.append(node('p', 'review-help', '默认按原表完整路径统计。新增组织可以直接展示;只有改名、调区或合并需要统一统计时,才保存对应关系。同名不代表同一组织。'));
242
+ const paths = module.inspection.organizations || [];
243
+ if (!paths.length) { content.append(node('p', 'review-help', '当前来源没有可供确认的组织路径。')); section.append(content); return section; }
244
+ const draftKey = module.uploadId;
245
+ if (!organizationDrafts.has(draftKey)) organizationDrafts.set(draftKey, {fromIndex: '0', kind: 'alias', to: ['', '', '', '', '', ''], start: '', end: '', remember: false, period: 'all'});
246
+ const draft = organizationDrafts.get(draftKey);
247
+ const form = node('form', 'review-org-form');
248
+ const from = node('select', 'review-input');
249
+ paths.forEach((item, index) => from.append(option(String(index), `${readablePath(item.path)}(${item.count} 行)`)));
250
+ from.value = draft.fromIndex; if (!from.value) from.value = '0';
251
+ const kind = node('select', 'review-input');
252
+ [['alias', '同一组织改名 / 名称对应'], ['transfer', '调整上级归属'], ['merge', '归入合并后的组织'], ['keep', '保持原表归属']].forEach(([value, label]) => kind.append(option(value, label)));
253
+ kind.value = draft.kind;
254
+ const target = node('select', 'review-input');
255
+ target.append(option('', '选择已有完整路径,或在下方填写新路径'));
256
+ const available = new Map();
257
+ for (const source of review.modules) for (const org of source.inspection?.organizations || []) if (org.path?.length === 6 && org.path.every(Boolean)) available.set(JSON.stringify(org.path), org.path);
258
+ for (const rule of review.organizationRules || []) if (!rule.revokedAt && rule.to?.every(Boolean)) available.set(JSON.stringify(rule.to), rule.to);
259
+ for (const [key, path] of available) target.append(option(key, readablePath(path)));
260
+ const targetFields = node('div', 'review-org-fields');
261
+ const inputs = pathLabels.map((label, index) => {
262
+ const input = field(); input.value = draft.to[index]; input.maxLength = 1000;
263
+ input.addEventListener('input', () => { draft.to[index] = input.value; target.value = ''; preview(); });
264
+ targetFields.append(labelInput(label, input)); return input;
265
+ });
266
+ const period = node('select', 'review-input');
267
+ period.append(option('all', '本来源中符合原路径的记录'), option('range', '仅指定业务期间'));
268
+ const canDate = ['invoice', 'movement', 'opening'].includes(module.id);
269
+ period.disabled = !canDate; period.value = canDate ? draft.period : 'all';
270
+ const start = field('date'); start.value = draft.start;
271
+ const end = field('date'); end.value = draft.end;
272
+ const dateFields = node('div', 'review-date-fields'); dateFields.append(labelInput('开始日期(含)', start), labelInput('结束日期(含)', end));
273
+ const impact = node('p', 'review-impact'); impact.setAttribute('aria-live', 'polite');
274
+ const remember = checkbox('记住这条对应关系,今后来源类型、原路径及期间仍匹配时使用', draft.remember, checked => { draft.remember = checked; preview(); });
275
+ function preview() {
276
+ const source = paths[Number(from.value)];
277
+ const keep = kind.value === 'keep';
278
+ target.disabled = keep;
279
+ inputs.forEach(input => { input.disabled = keep; input.required = !keep; });
280
+ dateFields.hidden = period.value !== 'range';
281
+ start.required = end.required = period.value === 'range';
282
+ let message = keep ? '保存后这条路径保持原表归属。' : `将“${readablePath(source.path)}”归入“${readablePath(inputs.map(input => input.value.trim()))}”。`;
283
+ message += ` 仅作用于${module.title},原路径共 ${source.count} 行。`;
284
+ message += period.value === 'range' ? ` 仅 ${start.value || '未选开始日期'} 至 ${end.value || '未选结束日期'} 的记录参与对应;具体受影响行数以保存后的检查结果为准。` : ' 适用于本来源所有匹配该完整路径的记录。';
285
+ message += ' 不删除记录,也不修改已经生成的历史看板。';
286
+ impact.textContent = message;
287
+ }
288
+ from.addEventListener('change', () => { draft.fromIndex = from.value; preview(); });
289
+ kind.addEventListener('change', () => { draft.kind = kind.value; preview(); });
290
+ target.addEventListener('change', () => {
291
+ if (target.value) { draft.to = JSON.parse(target.value); inputs.forEach((input, index) => { input.value = draft.to[index]; }); }
292
+ preview();
293
+ });
294
+ period.addEventListener('change', () => { draft.period = period.value; preview(); });
295
+ start.addEventListener('input', () => { draft.start = start.value; preview(); });
296
+ end.addEventListener('input', () => { draft.end = end.value; preview(); });
297
+ form.append(labelInput('原表中的完整组织路径', from), labelInput('这次要做什么', kind), labelInput('对应到哪个完整组织', target), targetFields, labelInput('适用范围', period), dateFields);
298
+ if (!canDate) form.append(node('p', 'review-help', '这类来源不能仅凭签约或盘点日期推断历史归属,因此只支持明确的来源路径对应,不按日期自动调区。'));
299
+ form.append(remember.label, impact);
300
+ const save = button('确认并保存组织对应', () => form.requestSubmit(), 'button button-primary');
301
+ form.append(save);
302
+ form.addEventListener('submit', async event => {
303
+ event.preventDefault();
304
+ if (!form.reportValidity()) return;
305
+ const source = paths[Number(from.value)];
306
+ if (period.value === 'range' && start.value > end.value) { notice('开始日期不能晚于结束日期。', true); return; }
307
+ await mutate('/api/review/organizations', {uploadId: module.uploadId, from: source.path, to: kind.value === 'keep' ? source.path : inputs.map(input => input.value.trim()), start: period.value === 'range' ? start.value : null, end: period.value === 'range' ? end.value : null, kind: kind.value, remember: draft.remember}, '组织对应已保存。仅应用于所选来源和适用期间,历史成品保持原内容。');
308
+ });
309
+ content.append(form, node('p', 'review-help', '组织拆分需要客户或终端归属依据;此处不提供按名称猜测或平均分配。若没有依据,请继续按原表统计。'));
310
+ preview(); section.append(content); return section;
311
+ }
312
+
313
+ function sourceSelection(module) {
314
+ const uploads = (bridge.getState()?.uploads || []).filter(item => item.moduleId === module.id);
315
+ if (uploads.length < 2) return null;
316
+ const holder = node('div', 'review-source-selection');
317
+ const select = node('select', 'review-input');
318
+ uploads.forEach(upload => select.append(option(upload.id, `${upload.filename} · ${time(upload.uploadedAt)}${upload.id === module.activeUploadId ? ' · 原有效版本' : ''}${upload.id === module.uploadId ? ' · 本次检查' : ''}`)));
319
+ select.value = module.uploadId;
320
+ holder.append(labelInput('本次使用的来源', select), button('选择这份来源', () => mutate('/api/review/select', {moduleId: module.id, uploadId: select.value}, '已选择来源,检查结果已更新。生成时将使用页面列出的版本。')));
321
+ return holder;
322
+ }
323
+
324
+ function reviewModule(module) {
325
+ const card = node('details', `review-module review-${module.status}`);
326
+ card.dataset.openKey = `module:${module.id}`;
327
+ card.open = ['pending', 'error'].includes(module.status);
328
+ const summary = node('summary');
329
+ summary.append(node('strong', '', module.title), node('span', `status ${module.status === 'ready' ? 'ready' : module.status === 'error' ? 'error' : 'running'}`, stateLabels[module.status] || module.status));
330
+ const pending = module.inspection?.pendingCount ?? 0;
331
+ if (pending) summary.append(node('span', 'review-count', `${pending} 组待确认`));
332
+ card.append(summary);
333
+ const content = node('div', 'review-module-body');
334
+ content.append(node('p', 'review-source-name', module.filename || '尚未选择来源'));
335
+ if (module.uploadId && module.activeUploadId && module.uploadId !== module.activeUploadId) content.append(node('p', 'review-help', '本次检查的是新来源;原有效来源仍保留。可在下方明确选择旧版本。'));
336
+ const choose = sourceSelection(module); if (choose) content.append(choose);
337
+ const inspection = module.inspection;
338
+ if (!inspection) content.append(node('p', 'review-help', module.status === 'missing' ? '上传对应表格后会自动检查。' : '此来源尚未完成本轮检查,请点击“检查全部当前来源”。'));
339
+ else {
340
+ const coverage = inspection.coverage;
341
+ content.append(node('p', 'review-help', `${inspection.sheet || '工作表未确认'} · ${Number(inspection.rowCount || 0).toLocaleString('zh-CN')} 行 · ${coverage?.start && coverage?.end ? `${coverage.start} 至 ${coverage.end}` : '期间待确认'} · 已处理 ${inspection.resolvedCount || 0} 组,待处理 ${pending} 组`));
342
+ for (const error of inspection.errors || []) content.append(node('p', 'review-error', typeof error === 'string' ? error : error.message || pretty(error)));
343
+ const groups = inspection.groups || [];
344
+ if (!groups.length) content.append(node('p', 'review-help', '本轮未发现需要选择的重复候选。缺失指标与其他业务限制仍按原口径显示。'));
345
+ groups.forEach((group, index) => content.append(candidateGroup(module, group, index)));
346
+ content.append(organizationEditor(module));
347
+ }
348
+ card.append(content); return card;
349
+ }
350
+
351
+ async function revoke(id) {
352
+ const affected = [];
353
+ for (const module of review.modules) for (const group of module.inspection?.groups || []) {
354
+ if (group.decisionId === id) affected.push(`${module.uploadId}:${group.key}`);
355
+ }
356
+ if (await mutate('/api/review/revoke', {id}, '已撤销。受影响来源已重新检查,历史成品与原始 Excel 保留。')) {
357
+ // Revocation must return this group to an explicit choice, without
358
+ // preselecting the old decision or discarding drafts for other groups.
359
+ for (const key of affected) drafts.delete(key);
360
+ apply(review, true);
361
+ }
362
+ }
363
+
364
+ function renderRecords() {
365
+ const host = $('#review-records'); host.replaceChildren();
366
+ const decisions = review.decisions || [];
367
+ const rules = review.organizationRules || [];
368
+ if (!decisions.length && !rules.length) host.append(node('p', 'review-help', '尚未保存新的处理决定。每次确认和撤销都会在这里留记录。'));
369
+ const title = moduleId => review.modules.find(module => module.id === moduleId)?.title || moduleId;
370
+ for (const record of [...decisions.map(item => ({...item, type: 'duplicate'})), ...rules.map(item => ({...item, type: 'organization'}))].sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))) {
371
+ const row = node('article', `review-record${record.revokedAt ? ' revoked' : ''}`);
372
+ row.append(node('strong', '', `${title(record.moduleId)} · ${record.type === 'duplicate' ? '重复记录处理' : '组织对应'}`));
373
+ row.append(node('p', 'review-help', record.type === 'duplicate' ? `计入 ${record.keepKeys?.length || 0} 条 · ${record.remember ? '同一组内容匹配时复用' : '仅本次来源'}` : `${readablePath(record.from)} → ${readablePath(record.to)};${record.start || record.end ? `${record.start || '不限开始'} 至 ${record.end || '不限结束'}` : '不按日期限制'};${record.remember ? '符合条件时复用' : '仅本次来源'}`));
374
+ row.append(node('p', 'review-help', `${time(record.createdAt)}${record.revokedAt ? ` · 已于 ${time(record.revokedAt)} 撤销` : ''}`));
375
+ if (!record.revokedAt) row.append(button('撤销此决定', () => revoke(record.id)));
376
+ host.append(row);
377
+ }
378
+ if (review.history?.length) {
379
+ const history = node('details', 'review-all-fields'); history.dataset.openKey = 'history-events';
380
+ history.append(node('summary', '', `操作记录 · ${review.history.length} 条`));
381
+ const list = node('ol', 'review-event-list');
382
+ const names = {decision: '保存重复处理', organization: '保存组织对应', revoke: '撤销决定', restore: '恢复处理设置', check: '检查来源', select: '选择来源'};
383
+ for (const event of [...review.history].reverse().slice(0, 100)) list.append(node('li', '', `${time(event.at || event.createdAt)} · ${event.message || names[event.type || event.action] || '更新处理记录'}`));
384
+ history.append(list); host.append(history);
385
+ }
386
+ }
387
+
388
+ function render() {
389
+ const opened = new Map([...document.querySelectorAll('#review [data-open-key]')].map(item => [item.dataset.openKey, item.open]));
390
+ const pending = review.modules.reduce((sum, module) => sum + (module.inspection?.pendingCount || 0), 0);
391
+ const unchecked = review.modules.filter(module => module.status === 'unchecked').length;
392
+ const errors = review.modules.filter(module => module.status === 'error').length;
393
+ const resolved = review.modules.reduce((sum, module) => sum + (module.inspection?.resolvedCount || 0), 0);
394
+ $('#review-summary').textContent = `${pending} 组待确认 · ${resolved} 组已处理${unchecked ? ` · ${unchecked} 类尚未检查` : ''}${errors ? ` · ${errors} 类需核对` : ''}`;
395
+ const resume = $('#review-resume');
396
+ resume.hidden = !pending && !unchecked && !errors;
397
+ resume.textContent = `继续处理${pending ? ` ${pending} 组` : ''}${unchecked ? ' · 有来源尚未检查' : ''}${errors ? ' · 有来源需核对' : ''}`;
398
+ $('#review-modules').replaceChildren(...review.modules.filter(module => module.uploadId || module.status !== 'missing').map(reviewModule));
399
+ if (!review.modules.some(module => module.uploadId)) $('#review-modules').append(node('p', 'review-help', '先上传至少一类 Excel。软件会在上传后检查,并把待处理项集中列在这里。'));
400
+ renderRecords();
401
+ for (const item of document.querySelectorAll('#review [data-open-key]')) if (opened.has(item.dataset.openKey)) item.open = opened.get(item.dataset.openKey);
402
+ controls();
403
+ }
404
+
405
+ function exportChecklist() {
406
+ if (!review) return;
407
+ const rows = [['板块', '来源文件', '候选组', '状态', 'Excel行号', '字段', '值']];
408
+ for (const module of review.modules) for (const group of module.inspection?.groups || []) for (const row of group.rows || []) for (const [key, value] of Object.entries(row.values || {})) rows.push([module.title, module.filename, group.id, group.status === 'resolved' ? '已处理' : '待确认', row.row, key, pretty(value)]);
409
+ // Prefix formula-leading source strings for safe opening in spreadsheet apps.
410
+ const quote = value => `"${String(value ?? '').replace(/^[=+@-]/, "'$&").replaceAll('"', '""')}"`;
411
+ download('待核对清单.csv', '\uFEFF' + rows.map(row => row.map(quote).join(',')).join('\r\n'), 'text/csv;charset=utf-8');
412
+ }
413
+
414
+ function init(adapter) {
415
+ bridge = adapter;
416
+ $('#review-check-button').addEventListener('click', () => mutate('/api/review/check', {}, '所有当前来源已完成检查,可在下方集中处理。'));
417
+ $('#review-later').addEventListener('click', () => {
418
+ notice('已经确认的结果保存在本机。尚未确认的勾选不会执行,回来后可从“继续处理”接着确认。');
419
+ $('#sources').scrollIntoView({behavior: 'smooth'});
420
+ });
421
+ $('#review-export').addEventListener('click', exportChecklist);
422
+ $('#review-backup').addEventListener('click', async () => {
423
+ try { download('战区看板处理设置备份.json', JSON.stringify(await bridge.request('/api/review/backup'), null, 2)); notice('处理设置备份已下载。它不包含原始 Excel 和历史 HTML;完整资料仍需另行备份本机数据目录。'); }
424
+ catch (error) { notice(error.message, true); }
425
+ });
426
+ $('#review-restore-file').addEventListener('change', async event => {
427
+ const file = event.target.files?.[0]; fileBackup = null;
428
+ $('#review-restore-name').textContent = '';
429
+ try {
430
+ if (!file) return;
431
+ if (file.size > 32 * 1048576) throw new Error('处理设置备份超过 32 MB,请核对所选文件。');
432
+ fileBackup = JSON.parse(await file.text());
433
+ $('#review-restore-name').textContent = `已选择:${file.name}。恢复前请确认下方说明。`;
434
+ } catch (error) { notice(`无法读取备份:${error.message}`, true); }
435
+ finally { controls(); }
436
+ });
437
+ $('#review-restore-confirm').addEventListener('click', async () => {
438
+ if (!fileBackup) return;
439
+ if (await mutate('/api/review/restore', {backup: fileBackup}, '处理设置已恢复,当前来源已重新核对。请检查恢复后的处理记录。')) { fileBackup = null; $('#review-restore-file').value = ''; $('#review-restore-name').textContent = ''; controls(); }
440
+ });
441
+ $('#generate-pending-button').addEventListener('click', () => bridge.generate(true));
442
+ controls();
443
+ }
444
+
445
+ function setState(state) {
446
+ if (!bridge) return;
447
+ const signature = JSON.stringify([state.reviewRevision, state.modules?.map(module => [module.id, module.activeUpload?.id, module.candidateUpload?.id, module.reviewStatus])]);
448
+ if (signature !== stateSignature) { stateSignature = signature; refresh(); }
449
+ controls();
450
+ }
451
+ return {init, setState, refresh, apply, controls};
452
+ })();
@@ -0,0 +1,137 @@
1
+ import { readFile, writeFile, readdir, realpath } from 'node:fs/promises';
2
+ import { resolve, relative, sep } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { buildSourcePayload } from './source-payload.mjs';
5
+ import { summarizeOrganizationMapping } from './organization-mapping.mjs';
6
+ import { moduleDefinitions } from '../modules.mjs';
7
+
8
+ const sha = value => createHash('sha256').update(value).digest('hex');
9
+ const ids = moduleDefinitions.map(module => module.id);
10
+ const titles = Object.fromEntries(moduleDefinitions.map(module => [module.id, module.title]));
11
+
12
+ export function captureSourceSnapshot(state, { includeCandidates = false } = {}) {
13
+ if (!state?.active || Array.isArray(state.active) || !Array.isArray(state.uploads)) throw new Error('后台上传版本记录格式无效。');
14
+ if (Object.keys(state.active).some(id => !ids.includes(id))) throw new Error('后台存在未知板块的有效版本记录。');
15
+ const selected = includeCandidates ? { ...state.active, ...state.candidates } : state.active;
16
+ return Object.fromEntries(ids.filter(id => selected[id]).map(id => {
17
+ const uploadId = selected[id];
18
+ const source = state.uploads.find(item => item.id === uploadId && item.moduleId === id);
19
+ if (typeof uploadId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(uploadId) || !source || !/^[a-f0-9]{64}$/i.test(source.sha256 ?? '')) throw new Error(`${titles[id]}的有效上传版本记录不完整,请重新上传。`);
20
+ return [id, { uploadId, sha256: source.sha256.toLowerCase(), validationContract: source.validationContract ?? null }];
21
+ }));
22
+ }
23
+
24
+ export async function verifySourceSnapshot(dataDir, snapshot, { verifyFiles = true, selection = 'active' } = {}) {
25
+ const checkState = async () => {
26
+ const state = JSON.parse(await readFile(resolve(dataDir, 'state.json'), 'utf8'));
27
+ if (JSON.stringify(captureSourceSnapshot(state, { includeCandidates: selection === 'review' })) !== JSON.stringify(snapshot)) throw new Error('生成期间有效上传版本发生变化,请重新生成;未发布混合版本成品。');
28
+ };
29
+ await checkState();
30
+ if (verifyFiles) {
31
+ const uploads = await realpath(resolve(dataDir, 'uploads'));
32
+ for (const [id, source] of Object.entries(snapshot)) {
33
+ const file = await realpath(resolve(uploads, source.uploadId, 'source.xlsx'));
34
+ if (!file.startsWith(`${uploads}${sep}`) || sha(await readFile(file)) !== source.sha256) throw new Error(`${titles[id]}的上传文件与锁定来源不一致,请重新上传后生成。`);
35
+ }
36
+ }
37
+ await checkState();
38
+ }
39
+
40
+ async function fingerprint(project) {
41
+ const files = ['package.json', 'package-lock.json'];
42
+ async function walk(dir) {
43
+ for (const entry of await readdir(resolve(project, dir), { withFileTypes: true })) {
44
+ const name = `${dir}/${entry.name}`;
45
+ if (entry.isDirectory()) await walk(name);
46
+ else if (entry.isFile()) files.push(name);
47
+ }
48
+ }
49
+ await walk('backend');
50
+ const hash = createHash('sha256');
51
+ for (const file of files.sort()) {
52
+ let bytes;
53
+ // npm packages (DSH plugin tarball) never carry package-lock.json; the hash is unchanged when it exists.
54
+ try { bytes = await readFile(resolve(project, file)); }
55
+ catch (error) { if (error.code === 'ENOENT' && file === 'package-lock.json') continue; throw error; }
56
+ hash.update(relative(project, resolve(project, file))).update('\0').update(bytes).update('\0');
57
+ }
58
+ return hash.digest('hex');
59
+ }
60
+
61
+ async function decisionBytes(file) {
62
+ try { return await readFile(file); }
63
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
64
+ }
65
+
66
+ export async function verifyGenerationSnapshot({ project, dataDir, sourceVersions, selection = 'active', codeSha256, decisionsSha256, reviewSha256 }) {
67
+ await verifySourceSnapshot(dataDir, sourceVersions, { selection });
68
+ const current = await decisionBytes(resolve(dataDir, 'generation-decisions.json'));
69
+ if ((current ? sha(current) : null) !== decisionsSha256) throw new Error('生成期间业务决定文件发生变化,请重新生成。');
70
+ if (reviewSha256 !== undefined) {
71
+ const state = JSON.parse(await readFile(resolve(dataDir, 'state.json'), 'utf8'));
72
+ if (sha(JSON.stringify(state.review ?? null)) !== reviewSha256) throw new Error('生成期间检查处理设置发生变化,请重新生成。');
73
+ }
74
+ if (await fingerprint(project) !== codeSha256) throw new Error('生成期间源码发生变化,请等待修改完成后重试。');
75
+ }
76
+
77
+ /** Build a source-bound artifact in the server's private staging directory.
78
+ * The server publishes this directory atomically only after all checks pass.
79
+ */
80
+ export async function generateDashboard({ project, dataDir, sourceVersions, outputDir, selection = 'active', allowPending = false, onStage = () => {} }, dependencies = {}) {
81
+ const codeSha256 = await fingerprint(project);
82
+ const decisionsFile = resolve(dataDir, 'generation-decisions.json');
83
+ const decisionBefore = await decisionBytes(decisionsFile);
84
+ if (decisionBefore) {
85
+ try { const parsed = JSON.parse(decisionBefore); if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') throw new Error(); }
86
+ catch { throw new Error('本机业务决定文件格式无效,请修复后重新生成。'); }
87
+ }
88
+ const decisionsSha256 = decisionBefore ? sha(decisionBefore) : null;
89
+ const initialState = JSON.parse(await readFile(resolve(dataDir, 'state.json'), 'utf8'));
90
+ const reviewSha256 = sha(JSON.stringify(initialState.review ?? null));
91
+ const verifyInputs = () => verifyGenerationSnapshot({ project, dataDir, sourceVersions, selection, codeSha256, decisionsSha256, reviewSha256 });
92
+ if (!Object.keys(sourceVersions).length) throw new Error('请先上传并校验至少一个板块的真实资料。');
93
+ await verifyInputs();
94
+ onStage('正在读取最新有效上传并计算真实数据');
95
+ const build = dependencies.buildSourcePayload ?? buildSourcePayload;
96
+ const { payload, report } = await build({ dataDir, decisionsFile: decisionBefore ? decisionsFile : undefined, sourceVersions, allowPending, rowCache: true });
97
+ if (!payload?.sources || !payload?.modules || report?.activeChangedDuringRead) throw new Error('有效上传版本读取不完整或已发生变化,请重新生成。');
98
+ if (report.decisionError) throw new Error(report.decisionError);
99
+ for (const [id, expected] of Object.entries(sourceVersions)) {
100
+ const source = payload.sources[id], module = payload.modules[id];
101
+ if (!source || source.uploadId !== expected.uploadId || source.sha256 !== expected.sha256) throw new Error(`${titles[id]}未使用锁定的有效上传版本:${module?.reason || '请重新上传并检查来源。'}`);
102
+ if (!['ready', 'partial'].includes(module?.state) && !(allowPending && report.modules?.[id]?.reviewPending)) throw new Error(`${titles[id]}无法计算:${module?.reason || '请核对该板块资料及已确认规则。'}`);
103
+ }
104
+ if (Object.keys(payload.sources).some(id => !sourceVersions[id])) throw new Error('计算结果出现未锁定来源,已停止生成。');
105
+ const pendingModules = Object.keys(sourceVersions).filter(id => report.modules?.[id]?.reviewPending);
106
+ if (!Object.entries(payload.modules).some(([id, module]) => sourceVersions[id] && module.records?.length) && !(allowPending && pendingModules.length)) throw new Error('没有可呈现的真实记录,请检查已上传资料。');
107
+ payload.mode = 'real';
108
+ onStage('正在生成 v10 真实数据离线看板');
109
+ const render = dependencies.renderV10Dashboard ?? (await import('./v10-template.mjs')).renderV10Dashboard;
110
+ const rendered = await render(payload);
111
+ if (typeof rendered?.html !== 'string' || !rendered.html.includes('</html>')) throw new Error('未生成有效的离线 HTML。');
112
+ const reviewSummary = { pendingCount: pendingModules.reduce((count, id) => count + (report.modules[id].review?.pendingCount || 1), 0), modules: pendingModules,
113
+ sources: Object.entries(sourceVersions).map(([id]) => ({ moduleId: id, filename: payload.sources[id].originalName, sha256: payload.sources[id].sha256, groups: report.modules[id].review?.groups ?? [], reason: payload.modules[id].reason ?? null })), organizations: report.reviewOrganizations ?? null };
114
+ if (initialState.review) {
115
+ const escape = value => String(value ?? '').replace(/[&<>"']/g, character => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[character]);
116
+ const label = pendingModules.length ? `待确认版本 · ${pendingModules.length} 个板块尚未处理` : '本次来源与处理记录';
117
+ const entries = reviewSummary.sources.map(source => `<li><strong>${escape(titles[source.moduleId])}</strong>:${escape(source.filename)}${source.reason ? ` · ${escape(source.reason)}` : ''}${source.groups.map(group => `<p>${group.status === 'resolved' ? `计入原表第 ${escape(group.keptRows.join('、'))} 行;不计入 ${escape(group.excludedRows.join('、') || '无')}。` : '重复候选待确认。'}</p>`).join('')}</li>`).join('');
118
+ const notes = `<details class="import-review"${pendingModules.length ? ' open' : ''}><summary>${escape(label)}</summary><div><p>本文件保留生成时的处理结果。调整决定需返回本机应用重新生成;受影响汇总和依赖指标保持不可用。</p><ul>${entries}</ul><p>组织对应已应用 ${report.reviewOrganizations?.appliedRows ?? 0} 行。原始 Excel 和历史看板未改写。</p></div></details>`;
119
+ rendered.html = rendered.html.replace('</head>', '<style>.import-review{position:fixed;right:12px;bottom:12px;z-index:99999;max-width:min(540px,90vw);font:13px/1.6 sans-serif;background:#fffaf0;color:#45351d;border:1px solid #b89349;border-radius:8px;box-shadow:0 3px 16px #0002}.import-review summary{padding:8px 14px;cursor:pointer;font-weight:600}.import-review>div{padding:0 16px 12px;max-height:42vh;overflow:auto}.import-review p{margin:6px 0}</style></head>').replace('</body>', `${notes}</body>`);
120
+ if (pendingModules.length) rendered.html = rendered.html.replace('<title>', '<title>待确认 · ');
121
+ }
122
+ await verifyInputs();
123
+ onStage('正在保存成品并核对来源版本');
124
+ await writeFile(resolve(outputDir, 'dashboard.html'), rendered.html, { flag: 'wx', mode: 0o600 });
125
+ await writeFile(resolve(outputDir, 'diagnostics.json'), JSON.stringify(report), { flag: 'wx', mode: 0o600 });
126
+ await verifyInputs();
127
+ return {
128
+ bytes: Buffer.byteLength(rendered.html), sha256: sha(rendered.html), templateSha256: rendered.templateSha256,
129
+ codeSha256, decisionsSha256, reviewSha256, needsReview: pendingModules.length > 0, reviewSummary, payloadSha256: rendered.payloadSha256,
130
+ processingVersion: payload.processingVersion, payloadVersion: payload.schemaVersion, rendererVersion: rendered.rendererVersion,
131
+ sources: payload.sources, moduleStates: rendered.moduleStates,
132
+ processors: Object.fromEntries(ids.map(id => [id, { version: payload.processingVersion, state: payload.modules[id].state }])),
133
+ moduleSummaries: Object.fromEntries(ids.map(id => [id, { state: payload.modules[id].state, records: payload.modules[id].records.length, metrics: payload.modules[id].metrics, warnings: payload.modules[id].warnings || [], unavailable: payload.modules[id].unavailable || [] }])),
134
+ pendingDecisions: payload.pendingDecisions,
135
+ organizationMapping: summarizeOrganizationMapping(report.organizationMapping),
136
+ };
137
+ }