dsh-data-dashboard 0.0.0-stage → 0.1.4

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 (70) 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 +192 -0
  17. package/backend/public/admin.js +713 -0
  18. package/backend/public/board.css +43 -0
  19. package/backend/public/board.html +47 -0
  20. package/backend/public/board.js +96 -0
  21. package/backend/public/index.html +110 -0
  22. package/backend/public/review.css +5 -0
  23. package/backend/public/review.js +452 -0
  24. package/backend/real-data/generate-dashboard.mjs +135 -0
  25. package/backend/real-data/inventory-history.mjs +316 -0
  26. package/backend/real-data/organization-mapping.mjs +102 -0
  27. package/backend/real-data/source-payload.mjs +459 -0
  28. package/backend/real-data/terminal-components.mjs +280 -0
  29. package/backend/real-data/terminal-structure.css +105 -0
  30. package/backend/real-data/terminal-structure.mjs +276 -0
  31. package/backend/real-data/v10-components.mjs +112 -0
  32. package/backend/real-data/v10-details.css +18 -0
  33. package/backend/real-data/v10-details.mjs +251 -0
  34. package/backend/real-data/v10-layout.css +27 -0
  35. package/backend/real-data/v10-model.mjs +521 -0
  36. package/backend/real-data/v10-overview-data.mjs +248 -0
  37. package/backend/real-data/v10-overview.css +264 -0
  38. package/backend/real-data/v10-overview.mjs +263 -0
  39. package/backend/real-data/v10-presentation.mjs +342 -0
  40. package/backend/real-data/v10-shell.html +1097 -0
  41. package/backend/real-data/v10-template.mjs +351 -0
  42. package/backend/recognition/fingerprint.mjs +32 -0
  43. package/backend/recognition/headers.mjs +2 -0
  44. package/backend/recognition/module-definition.mjs +4 -0
  45. package/backend/recognition/result.mjs +29 -0
  46. package/backend/recognition/upload-limits.mjs +14 -0
  47. package/backend/review-engine.mjs +364 -0
  48. package/backend/review-service.mjs +182 -0
  49. package/backend/server.mjs +545 -0
  50. package/backend/store.mjs +68 -0
  51. package/backend/target-template.mjs +47 -0
  52. package/backend/validate-workbook.mjs +251 -0
  53. package/backend/web-sync/README.md +37 -0
  54. package/backend/web-sync/client.mjs +63 -0
  55. package/backend/web-sync/exporter.mjs +260 -0
  56. package/backend/web-sync/local.html +34 -0
  57. package/backend/web-sync/server.mjs +147 -0
  58. package/build-manifest.json +79 -0
  59. package/client.js +24 -0
  60. package/cordis.patch.yml +3 -0
  61. package/index.js +117 -0
  62. package/lib/dist-manifest.mjs +19 -0
  63. package/lib/market-index.mjs +56 -0
  64. package/lib/package-audit.mjs +34 -0
  65. package/lib/settings.mjs +71 -0
  66. package/lib/tool-definitions.mjs +56 -0
  67. package/lib/tools.mjs +255 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +71 -4
@@ -0,0 +1,713 @@
1
+ 'use strict';
2
+
3
+ if (new URLSearchParams(location.search).has('embed')) document.documentElement.classList.add('embedded');
4
+
5
+ const $ = selector => document.querySelector(selector);
6
+ const rows = new Map();
7
+ const preferredOrder = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet', 'target'];
8
+ let state = null;
9
+ let working = null;
10
+ let connected = false;
11
+ let polling = false;
12
+ let historySignature = '';
13
+ let trackedGeneration = null;
14
+ // A running pre-upgrade server may serve the new page before it is restarted.
15
+ const currentUploadLimits = () => state?.uploadLimits ?? { fileBytes: 50 * 1048576, entryBytes: 128 * 1048576, totalBytes: 256 * 1048576 };
16
+
17
+ const iconPaths = {
18
+ invoice: '<path d="M4 3h16v18l-3-2-3 2-3-2-3 2-4-2zM8 8h8m-8 4h8"/>',
19
+ movement: '<path d="M4 3v17h17M7 15l4-5 4 2 5-7m-5 0h5v5"/>',
20
+ opening: '<path d="M12 2S5 9 5 15a7 7 0 0 0 14 0c0-6-7-13-7-13zm4 13a4 4 0 0 1-4 4"/>',
21
+ terminal: '<path d="m3 10 4-6 5 2 5-2 4 6-4 3-4-4-4 4-3-1M3 10l-2 4 4 3 3-5m0 3 6 5 7-6-2-3m-8 5 3 3m0-6 3 3"/>',
22
+ inventory: '<path d="m12 2 9 5v10l-9 5-9-5V7zm-9 5 9 5 9-5M12 12v10M7 4.8l10 5.5v6"/>',
23
+ banquet: '<path d="m3 21 4-14 10 10zm4-14 10 10M13 3l1 4m4-2 2-2m-2 7 4 1m-1 5 2 1M8 13l3 3"/>',
24
+ target: '<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1"/>',
25
+ };
26
+
27
+ function element(tag, className, text) {
28
+ const node = document.createElement(tag);
29
+ if (className) node.className = className;
30
+ if (text !== undefined) node.textContent = text;
31
+ return node;
32
+ }
33
+
34
+ function icon(id) {
35
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
36
+ svg.setAttribute('viewBox', '0 0 24 24');
37
+ svg.setAttribute('aria-hidden', 'true');
38
+ svg.innerHTML = iconPaths[id] || iconPaths.invoice;
39
+ return svg;
40
+ }
41
+
42
+ function readableSize(bytes) {
43
+ if (!Number.isFinite(bytes)) return '—';
44
+ return bytes >= 1048576 ? `${(bytes / 1048576).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`;
45
+ }
46
+
47
+ function readableTime(value) {
48
+ if (!value) return '—';
49
+ const date = new Date(value);
50
+ if (Number.isNaN(date.valueOf())) return '—';
51
+ return new Intl.DateTimeFormat('zh-CN', {month:'2-digit', day:'2-digit', hour:'2-digit', minute:'2-digit', second:'2-digit', hour12:false}).format(date);
52
+ }
53
+
54
+ const cycleLabels = [['daily', '每日'], ['weekly', '每周'], ['monthly', '每月'], ['irregular', '不定期']];
55
+ const cycleDays = { daily: 1, weekly: 7, monthly: 31, irregular: Infinity };
56
+ const localDay = value => { const date = new Date(value); return Number.isNaN(date.valueOf()) ? null : new Date(date.getFullYear(), date.getMonth(), date.getDate()); };
57
+ const pad2 = value => String(value).padStart(2, '0');
58
+ function sourceAge(uploadedAt, cycle) {
59
+ const day = uploadedAt ? localDay(uploadedAt) : null;
60
+ if (!day) return { text: '—', today: false, overdue: false };
61
+ const days = Math.round((localDay(Date.now()) - day) / 86400000);
62
+ const date = `${pad2(day.getMonth() + 1)}/${pad2(day.getDate())}`;
63
+ return { text: days <= 0 ? '今日' : date, today: days <= 0, overdue: days >= (cycleDays[cycle] ?? Infinity), days };
64
+ }
65
+ async function saveCycle(moduleId, cycle) {
66
+ if (!state?.token) return;
67
+ try { const result = await request('/api/settings/cycle', { method:'POST', headers:{'Content-Type':'application/json', 'X-Local-Token':state.token}, body:JSON.stringify({ moduleId, cycle }) }); applyState(result.state); }
68
+ catch (error) { setNotice(`提醒周期未保存:${error.message}`, true); }
69
+ }
70
+
71
+ function setNotice(message, error = false) {
72
+ const notice = $('#notice');
73
+ notice.textContent = message;
74
+ notice.className = `notice${error ? ' error' : ''}`;
75
+ notice.hidden = !message;
76
+ }
77
+
78
+ function fileErrorMessage(data) {
79
+ const messages = [data.error];
80
+ if (data.validation?.errors?.length) messages.push(...data.validation.errors);
81
+ if (data.validation?.missingHeaders?.length && !data.validation.errors?.some(message => data.validation.missingHeaders.every(header => message.includes(header)))) messages.push(`缺少表头:${data.validation.missingHeaders.join('、')}`);
82
+ return [...new Set(messages.filter(Boolean))].join('\n') || '操作未完成,请重试。';
83
+ }
84
+
85
+ async function request(path, options = {}) {
86
+ const response = await fetch(path, {cache:'no-store', credentials:'same-origin', ...options});
87
+ let data;
88
+ try { data = await response.json(); }
89
+ catch { throw new Error('后台返回了无法识别的结果,请刷新状态后重试。'); }
90
+ if (!response.ok) {
91
+ const error = new Error(fileErrorMessage(data));
92
+ error.data = data;
93
+ throw error;
94
+ }
95
+ return data;
96
+ }
97
+
98
+ function connectionStatus(online) {
99
+ connected = online;
100
+ const connection = $('#connection');
101
+ connection.className = `connection ${online ? 'online' : 'offline'}`;
102
+ connection.replaceChildren(element('i'), document.createTextNode(online ? '本机运行中' : '后台连接中断'));
103
+ }
104
+
105
+ function currentBusy() { return state?.busy || working; }
106
+
107
+ function busyLabel(busy) {
108
+ if (!busy) return '等待手动生成';
109
+ if (busy.stage) return busy.stage;
110
+ return busy.kind === 'upload' ? '正在更新资料' : '正在生成真实数据看板';
111
+ }
112
+
113
+ function renderControls() {
114
+ const busy = currentBusy();
115
+ const realMode = state?.app?.mode === 'real';
116
+ const hasSources = state?.modules?.some(module => module.activeUpload || module.candidateUpload);
117
+ $('#generate-button').disabled = !connected || Boolean(busy) || !realMode || !hasSources;
118
+ $('#generate-button').firstChild.textContent = busy?.kind === 'generate' ? '正在生成,请稍候' : '生成真实数据看板';
119
+ $('#task-status').textContent = !connected ? '后台未连接' : busy ? busyLabel(busy) : '空闲';
120
+ $('#generation-progress').textContent = !connected ? '连接后台后可生成' : busy ? busyLabel(busy) : !realMode ? '当前后台尚未启用真实数据生成,请刷新状态' : !hasSources ? '请先在上方更新至少一类资料' : '使用本次选择的来源 · 每次保存为新文件';
121
+ for (const row of rows.values()) row.cycle.disabled = !connected;
122
+ if (typeof renderBatch === 'function') renderBatch();
123
+ window.ReviewUI?.controls();
124
+ }
125
+
126
+ // ---- 当前使用的资料: read-only status table (design ⑩) ----
127
+ const shortDay = value => value ? `${String(value).slice(5, 7)}/${String(value).slice(8, 10)}` : '—';
128
+ const dayRange = (a, b) => !a ? '—' : !b || a === b ? shortDay(a) : `${shortDay(a)} ~ ${shortDay(b)}`;
129
+ const selectedUpload = module => module?.candidateUpload || module?.activeUpload || null;
130
+
131
+ function rangeText(module, upload) {
132
+ if (!upload) return '尚未上传';
133
+ const count = `${Number(upload.validation?.rowCount || 0).toLocaleString('zh-CN')} 行`;
134
+ if (module.id === 'banquet') return `无日期列 · ${count}`;
135
+ if (module.id === 'target') return count;
136
+ if (!upload.coverage) return '正在计算数据起止日…';
137
+ if (!upload.coverage.start) return '—';
138
+ const prefix = { terminal: '签约日期 ', inventory: '提交时间 ' }[module.id] || '';
139
+ return `${prefix}${upload.coverage.start} ~ ${upload.coverage.end}`;
140
+ }
141
+ function versionText(upload) {
142
+ if (!upload) return '—';
143
+ const composition = upload.composition;
144
+ return composition?.step ? `基线 + ${composition.step} 次更新` : composition?.partId ? '新基线' : '基线';
145
+ }
146
+ function operationText(upload) {
147
+ if (!upload) return '—';
148
+ const composition = upload.composition, when = sourceAge(upload.uploadedAt, 'irregular').text;
149
+ const op = composition?.mode === 'range' ? `范围 ${dayRange(composition.start, composition.end)}` : composition?.mode === 'incremental' ? `增量 ${dayRange(composition.start, composition.end)}` : '整份替换';
150
+ return `${when} ${op}`;
151
+ }
152
+ function statusOf(module, upload, cycle) {
153
+ if (!upload) return { text: '未上传', tone: 'muted' };
154
+ const review = module.reviewStatus?.status || module.reviewStatus;
155
+ if (module.candidateUpload || review === 'pending') return { text: '待确认', tone: 'warn' };
156
+ if (review === 'error') return { text: '需要核对', tone: 'bad' };
157
+ if (sourceAge(upload.uploadedAt, cycle).overdue) return { text: '待更新', tone: 'warn' };
158
+ if (review === 'unchecked') return { text: '尚未检查', tone: 'muted' };
159
+ return { text: '可使用', tone: 'ok' };
160
+ }
161
+
162
+ function createStatusRow(module) {
163
+ const root = element('div', 'status-row');
164
+ root.setAttribute('role', 'row');
165
+ root.dataset.module = module.id;
166
+ const name = element('span', 'status-name'); name.setAttribute('role', 'cell');
167
+ const symbol = element('span', 'module-icon'); symbol.append(icon(module.id));
168
+ const title = element('b', '', module.title); title.title = module.description || '';
169
+ name.append(symbol, title);
170
+ if (module.id === 'target') {
171
+ const template = element('a', 'text-link target-template', '下载模板 ↓');
172
+ template.href = '/api/target-template'; template.setAttribute('download', '经营目标模板.xlsx');
173
+ template.title = '预填当前已上传来源中的组织名称;目标值需自行填写';
174
+ name.append(template);
175
+ }
176
+ const cells = ['range', 'version', 'last'].map(() => { const cell = element('span', 'status-cell'); cell.setAttribute('role', 'cell'); return cell; });
177
+ const cycleCell = element('span', 'status-cell'); cycleCell.setAttribute('role', 'cell');
178
+ const cycle = element('select', 'source-cycle');
179
+ cycle.setAttribute('aria-label', `${module.title}提醒周期`);
180
+ for (const [value, label] of cycleLabels) { const option = element('option', '', label); option.value = value; cycle.append(option); }
181
+ cycle.addEventListener('change', () => saveCycle(module.id, cycle.value));
182
+ cycleCell.append(cycle);
183
+ const status = element('span', 'status-state'); status.setAttribute('role', 'cell');
184
+ root.append(name, ...cells, cycleCell, status);
185
+ const row = { root, range: cells[0], version: cells[1], last: cells[2], cycle, status };
186
+ rows.set(module.id, row);
187
+ return row;
188
+ }
189
+ function updateStatusRow(module) {
190
+ const row = rows.get(module.id), upload = selectedUpload(module);
191
+ row.range.textContent = rangeText(module, upload);
192
+ row.range.title = upload?.filename ? `当前文件:${upload.filename}` : '';
193
+ row.version.textContent = versionText(upload);
194
+ row.version.title = upload?.composition?.partFilename && upload.composition.step ? `最近一次由“${upload.composition.partFilename}”生成;收到的原文件保存在本机` : '';
195
+ row.last.textContent = operationText(upload);
196
+ const cycleValue = state?.settings?.cycles?.[module.id] || 'irregular';
197
+ if (document.activeElement !== row.cycle) row.cycle.value = cycleValue;
198
+ const status = statusOf(module, upload, cycleValue);
199
+ row.status.textContent = status.text;
200
+ row.status.className = `status-state is-${status.tone}`;
201
+ row.root.classList.toggle('is-today', sourceAge(upload?.uploadedAt, cycleValue).today);
202
+ }
203
+
204
+ function localLink(href, label, download = false) {
205
+ if (typeof href !== 'string') return null;
206
+ let url;
207
+ try { url = new URL(href, location.origin); } catch { return null; }
208
+ if (url.origin !== location.origin || !['http:', 'https:'].includes(url.protocol)) return null;
209
+ const link = element('a', '', label); link.href = url.pathname + url.search;
210
+ if (!download) { link.target = '_blank'; link.rel = 'noopener'; }
211
+ else link.setAttribute('download', '');
212
+ return link;
213
+ }
214
+
215
+ function renderHistory() {
216
+ const generations = [...(state?.generations || [])].sort((a,b) => String(b.createdAt).localeCompare(String(a.createdAt)));
217
+ $('#history-count').textContent = `${generations.length} 条记录`;
218
+ $('#generation-count').textContent = generations.filter(item => item.status === 'completed').length;
219
+ const latest = generations.find(item => item.status === 'completed' && !item.needsReview && !item.reviewPending && localLink(item.viewUrl, ''));
220
+ const latestLink = $('#latest-output'); latestLink.hidden = !latest;
221
+ if (latest) {
222
+ latestLink.href = localLink(latest.viewUrl, '').href;
223
+ latestLink.textContent = latest.mode === 'real' ? '打开最新生成的真实数据看板 ↗' : latest.mode === 'demo' ? '打开最近的历史演示看板 ↗' : '打开最近生成的看板 ↗';
224
+ }
225
+ const signature = JSON.stringify(generations);
226
+ if (signature === historySignature) return;
227
+ historySignature = signature;
228
+ const host = $('#generation-history'); host.replaceChildren();
229
+ if (!generations.length) {
230
+ const empty = element('div', 'empty-state');
231
+ empty.append(element('strong', '', '还没有生成记录'), element('p', '', '更新资料并通过检查后,点击上方按钮生成真实数据看板。'));
232
+ host.append(empty);
233
+ return;
234
+ }
235
+ const wrapper = element('div', 'history-table-wrap');
236
+ const table = element('table', 'history-table');
237
+ const thead = element('thead'); const tr = element('tr');
238
+ for (const label of ['成品 / 任务', '生成时间', '状态', '操作']) { const th = element('th','',label); th.scope = 'col'; tr.append(th); }
239
+ thead.append(tr); const tbody = element('tbody');
240
+ for (const generation of generations) {
241
+ const row = element('tr');
242
+ const name = element('td');
243
+ const real = generation.mode === 'real';
244
+ const demo = generation.mode === 'demo';
245
+ name.append(element('span', 'history-name', generation.filename || (real ? 'v10 真实数据看板' : demo ? 'v5 演示看板' : '历史看板')));
246
+ const sources = generation.sourceIds ? Object.values(generation.sourceIds).filter(Boolean).length : 0;
247
+ const sourceLabel = real ? `${generation.needsReview ? '待确认版本 · ' : ''}真实上传数据 · ${sources} 类来源版本` : demo ? `历史合成演示数据 · 记录 ${sources} 类资料版本` : `历史生成记录 · ${sources} 类资料版本`;
248
+ name.append(element('span', 'history-sub', `${sourceLabel}${generation.bytes ? ` · ${readableSize(generation.bytes)}` : ''}`));
249
+ if (real && generation.status === 'completed' && generation.moduleStates) {
250
+ const moduleTitle = id => state.modules.find(module => module.id === id)?.title || id;
251
+ const unavailable = Object.entries(generation.moduleStates).filter(([, value]) => ['unavailable', 'missing_source'].includes(value)).map(([id]) => moduleTitle(id));
252
+ const partial = Object.entries(generation.moduleStates).filter(([, value]) => value === 'partial').map(([id]) => moduleTitle(id));
253
+ const notes = [unavailable.length ? `无可用来源:${unavailable.join('、')}` : '', partial.length ? `部分指标可用:${partial.join('、')}` : ''].filter(Boolean);
254
+ if (notes.length) name.append(element('span', 'history-sub', notes.join(';')));
255
+ }
256
+ const created = element('td', '', readableTime(generation.createdAt));
257
+ const statusCell = element('td');
258
+ const statusNames = {completed:'已完成', failed:'生成失败', running:'生成中'};
259
+ statusCell.append(element('span', `status ${generation.status === 'completed' ? 'ready' : generation.status === 'failed' ? 'error' : 'running'}`, generation.status === 'completed' && generation.needsReview ? '待确认版本' : statusNames[generation.status] || generation.status));
260
+ const actions = element('td');
261
+ if (generation.status === 'completed') {
262
+ const links = element('div', 'history-links');
263
+ const view = localLink(generation.viewUrl, '查看 ↗'); const download = localLink(generation.downloadUrl, '下载 HTML', true);
264
+ if (view) links.append(view); if (download) links.append(download);
265
+ actions.append(links);
266
+ } else if (generation.status === 'failed') actions.append(element('span', 'history-sub history-error', generation.error || '生成未完成,请重试。'));
267
+ else actions.append(element('span', 'history-sub', generation.stage || '正在准备成品…'));
268
+ row.append(name, created, statusCell, actions); tbody.append(row);
269
+ }
270
+ table.append(thead, tbody); wrapper.append(table); host.append(wrapper);
271
+ }
272
+
273
+ function applyState(next) {
274
+ state = next;
275
+ const limits = currentUploadLimits();
276
+ $('#upload-limit-hint').textContent = `单文件 ≤ ${limits.fileBytes / 1048576} MB · 原文件保留`;
277
+ $('#upload-capacity-description').textContent = `单表解压 ≤ ${limits.entryBytes / 1048576} MB,整本解压 ≤ ${limits.totalBytes / 1048576} MB。解压大小不同于文件大小。`;
278
+ connectionStatus(true);
279
+ const modules = [...(state.modules || [])].sort((a,b) => preferredOrder.indexOf(a.id) - preferredOrder.indexOf(b.id));
280
+ const grid = $('#module-grid');
281
+ if (!rows.size) grid.replaceChildren();
282
+ for (const module of modules) {
283
+ if (!rows.has(module.id)) grid.append(createStatusRow(module).root);
284
+ updateStatusRow(module);
285
+ }
286
+ $('#ready-count').textContent = modules.filter(module => module.activeUpload).length;
287
+ $('#ready-total').textContent = ` / ${modules.length} 类`;
288
+ const today = modules.filter(module => sourceAge(selectedUpload(module)?.uploadedAt, 'daily').today);
289
+ $('#today-count').textContent = today.length;
290
+ $('#today-total').textContent = ` / ${modules.length} 类`;
291
+ const fresh = today.map(module => module.title), kept = modules.filter(module => module.activeUpload && !today.includes(module)).map(module => module.title);
292
+ const missing = modules.filter(module => !module.activeUpload && !module.candidateUpload).map(module => module.title);
293
+ $('#generate-sources').textContent = [fresh.length ? `今日更新:${fresh.join('、')}` : '今日还没有更新任何板块', kept.length ? `沿用上次:${kept.join('、')}` : '', missing.length ? `未上传:${missing.join('、')}` : ''].filter(Boolean).join(';') + '。';
294
+ $('#data-directory').textContent = state.app?.dataDir || '本机资料目录';
295
+ const realMode = state.app?.mode === 'real';
296
+ $('#mode-title').textContent = realMode ? '当前生成:v10 真实数据看板' : '当前后台尚未启用真实数据生成';
297
+ $('#mode-description').textContent = realMode ? '检查并处理本次来源后,按已确认口径生成。无法决定的问题可保留在待确认版本中;受影响指标不会显示为完整结果。' : '请等待后台升级完成并刷新状态。已有生成记录仍可查看或下载。';
298
+ $('#mode-tag').textContent = realMode ? '真实上传数据' : '等待后台就绪';
299
+ $('#version-label').textContent = `${realMode ? 'v10 真实数据生成' : '等待真实数据生成启用'}${state.app?.version ? ` · 后台 ${state.app.version}` : ''}`;
300
+ renderHistory();
301
+ renderControls();
302
+ window.ReviewUI?.setState(state);
303
+ if (trackedGeneration) {
304
+ const current = (state.generations || []).find(item => item.id === trackedGeneration);
305
+ if (lastReceipt?.generating && ['completed', 'failed'].includes(current?.status)) {
306
+ lastReceipt.generating = false;
307
+ lastReceipt.foot = current.status === 'failed' ? `看板生成失败:${current.error || '请稍后重试'}。资料已更新,可直接重新生成。` : current.needsReview ? '已生成待确认版本,当前看板未替换。收到的原文件都保存在本机。'
308
+ : document.documentElement.classList.contains('embedded') ? '看板已生成并切到「看板」页。收到的原文件都保存在本机。' : '看板已生成,可在下方“生成记录”查看。收到的原文件都保存在本机。';
309
+ renderReceipt();
310
+ }
311
+ if (current?.status === 'completed') {
312
+ setNotice(current.needsReview ? '待确认版本已生成。相关汇总及关联指标保持待确认,请在生成记录中查看;最近正常版本入口未被替换。' : current.mode === 'real' ? '真实数据看板已生成,使用本次开始生成时锁定的来源。可在“生成记录”中查看或下载 HTML;缺失来源和待确认指标已明确标注。' : '历史演示看板已生成。请查看生成记录中的模式说明。');
313
+ trackedGeneration = null;
314
+ } else if (current?.status === 'failed') {
315
+ setNotice(`生成失败:${current.error || '请检查后台状态后重试。'}`, true);
316
+ trackedGeneration = null;
317
+ }
318
+ }
319
+ }
320
+
321
+ async function refresh(silent = false) {
322
+ if (polling) return;
323
+ polling = true;
324
+ try { applyState(await request('/api/state')); }
325
+ catch (error) {
326
+ connectionStatus(false);
327
+ renderControls();
328
+ if (!silent) setNotice(`无法连接本机后台。${error.message}`, true);
329
+ } finally { polling = false; }
330
+ }
331
+
332
+ // ---- 更新数据: every board from one entry (design ⑨) ----
333
+ // Files are identified by sheet name. Dated boards (invoice, movement, opening,
334
+ // inventory) and whole-replacement boards (terminal, banquet) are analysed by
335
+ // the backend, which suggests the mode and checks the export scope; the target
336
+ // workbook keeps its original whole upload.
337
+ const batchItems = [];
338
+ let batchRunning = false;
339
+ let generateAfterBatch = false;
340
+ let lastReceipt = null;
341
+ const moduleOf = id => state?.modules?.find(module => module.id === id) || null;
342
+ const moduleTitle = id => moduleOf(id)?.title || '';
343
+ const SHORT = { invoice: '发票', movement: '动销', opening: '开瓶', inventory: '库存', terminal: '签约', banquet: '宴席', target: '目标' };
344
+ const shortTitle = id => SHORT[id] || moduleTitle(id);
345
+ const isUpdatable = id => Boolean(moduleOf(id)?.updatable);
346
+ const modesOf = id => moduleOf(id)?.modes || [];
347
+ const MODE_LABELS = { incremental: '增量', range: '范围更新', full: '整份替换' };
348
+ const countText = value => value === null || value === undefined ? '—' : Number(value).toLocaleString('zh-CN', { maximumFractionDigits: 2 });
349
+ const wanText = value => value === null || value === undefined ? '—' : (Number(value) / 10000).toLocaleString('zh-CN', { maximumFractionDigits: 1, minimumFractionDigits: 1 });
350
+ const figureValue = (figure, value) => figure.unit === 'wan' ? wanText(value) : countText(value);
351
+ function figureDelta(figure) {
352
+ if (figure.before === null || figure.after === null || figure.before === undefined || figure.after === undefined) return { text: '—', tone: '' };
353
+ const delta = Number(figure.after) - Number(figure.before);
354
+ if (!delta) return { text: '0', tone: '' };
355
+ const text = figure.unit === 'wan' ? wanText(Math.abs(delta)) : countText(Math.abs(delta));
356
+ return { text: `${delta > 0 ? '+' : '−'}${text}`, tone: delta > 0 ? 'pos' : 'neg' };
357
+ }
358
+ function batchConflicts() {
359
+ const counts = new Map();
360
+ for (const item of batchItems) if (item.moduleId && ['ready', 'analyzing', 'uploading'].includes(item.status)) counts.set(item.moduleId, (counts.get(item.moduleId) || 0) + 1);
361
+ return counts;
362
+ }
363
+ // What the card says about this file: ok, confirm (needs a tick), adjust (fixable), scope (re-export).
364
+ function itemState(item) {
365
+ if (!['ready', 'uploading'].includes(item.status) || !item.moduleId) return item.status;
366
+ if (!isUpdatable(item.moduleId)) return 'ok';
367
+ const r = item.receipt;
368
+ if (!r) return 'adjust';
369
+ if (r.scope && !r.scope.ok) return 'scope';
370
+ if (r.blocked?.length) return 'adjust';
371
+ if (r.requiresConfirmation && !item.confirmMissing) return 'confirm';
372
+ return 'ok';
373
+ }
374
+ async function discardStaged(item) {
375
+ if (!item.staged) return;
376
+ const stagedId = item.staged.stagedId; item.staged = null;
377
+ try { await request('/api/updates/discard', { method:'POST', headers:{'Content-Type':'application/json', 'X-Local-Token':state?.token || ''}, body:JSON.stringify({ stagedId }) }); } catch {}
378
+ }
379
+ async function analyzeItem(item) {
380
+ await discardStaged(item);
381
+ item.status = 'analyzing'; item.confirmMissing = false; item.needConfirm = false; item.error = ''; item.receipt = null; renderBatch();
382
+ while (currentBusy()) { await new Promise(resolve => setTimeout(resolve, 400)); await refresh(true); }
383
+ try {
384
+ const result = await request('/api/updates/analyze', { method:'POST', headers:{'Content-Type':'application/octet-stream', 'X-Filename':encodeURIComponent(item.file.name), 'X-Module-Id':item.moduleId, 'X-Local-Token':state?.token || ''}, body:item.file });
385
+ if (result.duplicate) { item.status = 'duplicate'; item.message = result.message; }
386
+ else Object.assign(item, { staged: result, mode: result.suggestion.mode, start: result.suggestion.start, end: result.suggestion.end, modeAuto: true, receipt: result.receipt, status: 'ready' });
387
+ } catch (error) { item.status = 'failed'; item.message = error.message; }
388
+ renderBatch();
389
+ }
390
+ let previewTimer = null;
391
+ function schedulePreview(item) {
392
+ clearTimeout(previewTimer);
393
+ previewTimer = setTimeout(async () => {
394
+ if (!item.staged) return;
395
+ try {
396
+ const result = await request('/api/updates/preview', { method:'POST', headers:{'Content-Type':'application/json', 'X-Local-Token':state?.token || ''}, body:JSON.stringify({ stagedId:item.staged.stagedId, mode:item.mode, start:item.start, end:item.end }) });
397
+ item.receipt = result.receipt; item.error = '';
398
+ } catch (error) { item.error = error.message; if (error.data?.receipt) item.receipt = error.data.receipt; }
399
+ renderBatch();
400
+ }, 250);
401
+ }
402
+
403
+ const STATUS_TEXT = { ok: ['✓ 可以提交', 'is-ok'], confirm: ['! 需确认', 'is-warn'], adjust: ['✕ 需要调整', 'is-bad'], scope: ['✕ 需要重新导出', 'is-bad'],
404
+ identifying: ['正在识别…', ''], analyzing: ['正在核对…', ''], uploading: ['正在更新…', ''], unknown: ['请选择板块', 'is-warn'], failed: ['✕ 未通过', 'is-bad'], duplicate: ['已处理过', 'is-ok'] };
405
+ function scopeLine(item) {
406
+ const scope = item.receipt?.scope;
407
+ if (!scope) return '';
408
+ const parts = [], sentences = [];
409
+ if (scope.checked.zone) parts.push(`战区 ${scope.counts.zones} 个`);
410
+ if (scope.checked.region) parts.push(`大区 ${scope.counts.regions} 个`);
411
+ const product = scope.checked.product ? `${scope.productLabel} ${countText(scope.counts.products)} 个` : '';
412
+ if (parts.length) sentences.push(`范围检查通过:${parts.join('、')},与当前一致${product ? `;${product}` : ''}`);
413
+ else if (product) sentences.push(`范围检查通过:${product}`);
414
+ for (const note of scope.notes || []) sentences.push(note.replace(/。$/, ''));
415
+ if (item.mode === 'range') sentences.push('区间外数据保持不变');
416
+ if (item.mode === 'incremental') sentences.push(`${item.receipt.identity?.existing ? '' : '全部是新记录,直接追加;'}${item.moduleId === 'inventory' ? '历史盘点保留,「较上次变化」自动接上之前的记录' : '已有日期保持不变'}`);
417
+ return sentences.length ? `${sentences.join('。')}。` : '';
418
+ }
419
+ function figuresTable(item) {
420
+ const r = item.receipt;
421
+ const whole = !moduleOf(item.moduleId)?.flow;
422
+ const table = element('div', 'check-table');
423
+ table.setAttribute('role', 'table');
424
+ const [beforeLabel, afterLabel] = whole ? ['当前', '新文件'] : item.mode === 'incremental' ? ['现有', '追加后'] : item.mode === 'range' ? ['替换前', '替换后'] : ['当前', '整份替换后'];
425
+ const label = whole ? '' : item.mode === 'range' ? `替换 ${dayRange(r.start, r.end)}` : item.mode === 'incremental' ? `追加 ${dayRange(r.file.start, r.file.end)}` : '整份替换';
426
+ const head = [label, beforeLabel, afterLabel, '变化'].map(text => element('span', 'check-col', text));
427
+ head.forEach(cell => cell.setAttribute('role', 'columnheader'));
428
+ table.append(...head);
429
+ for (const figure of r.figures || []) {
430
+ const delta = figureDelta(figure);
431
+ const cells = [element('span', 'check-label', figure.label), element('span', '', figureValue(figure, figure.before)), element('span', '', figureValue(figure, figure.after)), element('span', `check-delta ${delta.tone}`, delta.text)];
432
+ cells.forEach(cell => cell.setAttribute('role', 'cell'));
433
+ table.append(...cells);
434
+ }
435
+ return table;
436
+ }
437
+ function checkCard(item, counts) {
438
+ const st = itemState(item), conflict = item.moduleId && counts.get(item.moduleId) > 1;
439
+ const [statusText, statusTone] = conflict ? ['同一板块只能选一个文件', 'is-bad'] : STATUS_TEXT[st] || ['', ''];
440
+ const card = element('div', `check-card is-${conflict ? 'conflict' : st}`);
441
+ const head = element('div', 'check-head');
442
+ const locked = batchRunning || ['uploading', 'analyzing', 'identifying'].includes(item.status);
443
+ if (!item.moduleId || item.status === 'unknown') {
444
+ const select = element('select', 'check-board-select');
445
+ select.setAttribute('aria-label', `${item.file.name} 对应的板块`);
446
+ const empty = element('option', '', '选择板块'); empty.value = ''; select.append(empty);
447
+ for (const module of [...(state?.modules || [])].sort((a,b) => preferredOrder.indexOf(a.id) - preferredOrder.indexOf(b.id))) { const option = element('option', '', module.title); option.value = module.id; select.append(option); }
448
+ select.value = item.moduleId || ''; select.disabled = locked;
449
+ select.addEventListener('change', async () => {
450
+ item.moduleId = select.value || null;
451
+ if (!item.moduleId) { item.status = 'unknown'; renderBatch(); return; }
452
+ if (isUpdatable(item.moduleId)) return analyzeItem(item);
453
+ item.status = 'ready'; renderBatch();
454
+ });
455
+ head.append(select);
456
+ } else head.append(element('b', 'check-board', moduleTitle(item.moduleId)));
457
+ const r = item.receipt;
458
+ const dateLabel = { terminal: '签约日期', inventory: '提交时间' }[item.moduleId] || '文件日期';
459
+ const fileInfo = r?.file?.start ? `${item.file.name} · ${dateLabel} ${dayRange(r.file.start, r.file.end)}` : item.moduleId === 'banquet' && r ? `${item.file.name} · ${countText(r.file.rows)} 行` : item.file.name;
460
+ const file = element('span', 'check-file', fileInfo); file.title = item.file.name;
461
+ head.append(file);
462
+ if (item.status === 'ready' || item.status === 'uploading') {
463
+ const modes = modesOf(item.moduleId);
464
+ if (modes.length > 1) {
465
+ const label = element('label', 'check-mode', '更新方式 ');
466
+ const select = element('select');
467
+ for (const mode of modes) { const option = element('option', '', MODE_LABELS[mode]); option.value = mode; select.append(option); }
468
+ select.value = item.mode; select.disabled = locked || st === 'scope';
469
+ select.addEventListener('change', () => { item.mode = select.value; item.modeAuto = item.mode === item.staged.suggestion.mode; item.confirmMissing = false; if (item.mode === 'range' && !item.start) { item.start = item.staged.suggestion.start; item.end = item.staged.suggestion.end; } schedulePreview(item); renderBatch(); });
470
+ label.append(select); head.append(label);
471
+ if (st !== 'scope') {
472
+ const tag = element('span', item.modeAuto ? 'check-tag' : 'check-tag manual', item.modeAuto ? '系统建议' : '手动');
473
+ tag.title = item.modeAuto ? item.staged.suggestion.reason : `系统建议:${MODE_LABELS[item.staged.suggestion.mode]}(${item.staged.suggestion.reason})`;
474
+ head.append(tag);
475
+ }
476
+ } else head.append(element('span', 'check-only', isUpdatable(item.moduleId) ? `整份替换(${shortTitle(item.moduleId)}只支持整份)` : '整份替换'));
477
+ }
478
+ head.append(element('span', `check-status ${statusTone}`, statusText));
479
+ const remove = element('button', 'text-button', '移除'); remove.type = 'button'; remove.disabled = locked;
480
+ remove.addEventListener('click', async () => { batchItems.splice(batchItems.indexOf(item), 1); await discardStaged(item); renderBatch(); });
481
+ head.append(remove);
482
+ card.append(head);
483
+
484
+ if (['failed', 'duplicate'].includes(item.status)) { card.append(element('p', item.status === 'failed' ? 'check-error' : 'check-note', item.message || '')); return card; }
485
+ if (!isUpdatable(item.moduleId) && item.status === 'ready') { card.append(element('p', 'check-note', '经营目标按原方式整份上传,提交时校验结构。')); return card; }
486
+ if (!r || !['ready', 'uploading'].includes(item.status)) return card;
487
+
488
+ if (st === 'scope') {
489
+ const box = element('div', 'check-scope');
490
+ box.append(element('b', '', '导出范围和当前数据不一致,未提交。'));
491
+ for (const message of r.scope.blocked) box.append(element('p', '', `· ${message}`));
492
+ if (r.scope.advice) box.append(element('p', '', r.scope.advice));
493
+ card.append(box);
494
+ return card;
495
+ }
496
+ if (item.mode === 'range' && modesOf(item.moduleId).length > 1) {
497
+ const range = element('div', 'check-range');
498
+ range.append(element('span', '', '替换区间'));
499
+ for (const key of ['start', 'end']) {
500
+ const input = element('input'); input.type = 'date'; input.value = item[key] || ''; input.disabled = locked;
501
+ input.setAttribute('aria-label', key === 'start' ? '替换开始日期' : '替换结束日期');
502
+ input.addEventListener('change', () => { item[key] = input.value; item.modeAuto = false; item.confirmMissing = false; schedulePreview(item); });
503
+ range.append(input);
504
+ if (key === 'start') range.append(element('span', '', '~'));
505
+ }
506
+ card.append(range);
507
+ }
508
+ const compact = item.moduleId === 'banquet' && !r.blocked.length && !r.requiresConfirmation;
509
+ if (compact) {
510
+ const [events, bottles] = r.figures;
511
+ card.append(element('p', 'check-note', `执行场次 ${countText(events.before)} → ${countText(events.after)} · 开瓶 ${countText(bottles.before)} → ${countText(bottles.after)} 瓶。${(r.notes || []).join('')}`));
512
+ } else card.append(figuresTable(item));
513
+ const notes = element('div', 'check-notes');
514
+ if (r.identity?.existing) notes.append(element('p', 'check-note', `按${r.identity.label}:已存在 ${countText(r.identity.existing)} 行 · 新增 ${countText(r.identity.added)} 行。${item.moduleId === 'invoice' ? '合并后仍做重复候选检查。' : '不自动去重。'}`));
515
+ if (r.disappearingDates?.length) notes.append(element('p', 'check-warn', `区间内 ${r.disappearingDates.length} 天在新文件里没有记录,替换后这些天的原有数据会移除:${r.disappearingDates.slice(0, 8).map(shortDay).join('、')}${r.disappearingDates.length > 8 ? ' 等' : ''}。`));
516
+ for (const warning of r.warnings || []) notes.append(element('p', 'check-warn', warning));
517
+ for (const message of r.blocked || []) notes.append(element('p', 'check-error', message));
518
+ if (!compact) for (const note of r.notes || []) notes.append(element('p', 'check-note', note));
519
+ if (r.confirmation) {
520
+ const label = element('label', `check-confirm${item.needConfirm ? ' is-required' : ''}`);
521
+ const box = element('input'); box.type = 'checkbox'; box.checked = !!item.confirmMissing; box.disabled = locked;
522
+ box.addEventListener('change', () => { item.confirmMissing = box.checked; item.needConfirm = false; renderBatch(); });
523
+ label.append(box, document.createTextNode(` ${r.confirmation.message} ${r.confirmation.label}`));
524
+ notes.append(label);
525
+ }
526
+ if (item.error) notes.append(element('p', 'check-error', item.error));
527
+ const line = scopeLine(item);
528
+ if (line && !r.blocked.length) notes.append(element('p', 'check-note', line));
529
+ card.append(notes);
530
+ return card;
531
+ }
532
+ function effectiveText(moduleId) {
533
+ const upload = selectedUpload(moduleOf(moduleId));
534
+ if (!upload) return '尚未上传';
535
+ return upload.coverage?.end ? `截至 ${shortDay(upload.coverage.end)}` : '上一版';
536
+ }
537
+ let batchSignature = '';
538
+ function renderBatch() {
539
+ const list = $('#batch-list'), counts = batchConflicts();
540
+ // The status poll calls this every two seconds; rebuild the cards only when
541
+ // something on them changed so an open dropdown or date field is not reset.
542
+ const signature = JSON.stringify([batchRunning, batchItems.map(item => [item.file.name, item.status, item.moduleId, item.mode, item.start, item.end, item.modeAuto, item.confirmMissing, item.needConfirm, item.error, item.message, item.receipt])]);
543
+ if (signature !== batchSignature) {
544
+ batchSignature = signature;
545
+ list.replaceChildren();
546
+ for (const item of batchItems) list.append(checkCard(item, counts));
547
+ }
548
+ const has = batchItems.length > 0;
549
+ $('#batch-drop').hidden = has;
550
+ $('#batch-add').hidden = !has;
551
+ $('#batch-actions').hidden = !has;
552
+ const states = batchItems.map(item => ({ item, st: item.moduleId && counts.get(item.moduleId) > 1 ? 'conflict' : itemState(item) }));
553
+ const submittable = states.filter(({ st }) => ['ok', 'confirm'].includes(st));
554
+ const reexport = states.filter(({ st }) => ['scope', 'adjust', 'failed', 'conflict'].includes(st));
555
+ const waiting = states.some(({ st }) => ['identifying', 'analyzing', 'unknown'].includes(st));
556
+ const disabled = batchRunning || !connected || Boolean(currentBusy()) || !submittable.length || waiting;
557
+ $('#batch-upload').disabled = disabled;
558
+ $('#batch-upload').textContent = batchRunning && !generateAfterBatch ? '正在更新…' : '只更新数据';
559
+ $('#batch-generate').disabled = disabled || state?.app?.mode !== 'real';
560
+ $('#batch-generate').textContent = batchRunning && generateAfterBatch ? '正在更新…' : '确认更新并生成看板 →';
561
+ const skipped = states.filter(({ st }) => ['scope', 'adjust', 'conflict'].includes(st)).map(({ item }) => item.moduleId).filter(Boolean);
562
+ const confirmLater = states.filter(({ st }) => st === 'confirm').map(({ item }) => shortTitle(item.moduleId));
563
+ const hints = [];
564
+ for (const id of [...new Set(skipped)]) hints.push(`${shortTitle(id)}不提交,看板沿用${shortTitle(id)}上一版(${effectiveText(id)})`);
565
+ if (confirmLater.length) hints.push(`${confirmLater.join('、')}勾选确认后一并提交`);
566
+ if (waiting) hints.push(states.some(({ st }) => st === 'unknown') ? '有文件需要选择板块' : '正在核对文件…');
567
+ $('#batch-hint').textContent = hints.join(';') + (hints.length ? '。' : '');
568
+ const touched = new Set(submittable.map(({ item }) => item.moduleId));
569
+ const ready = states.filter(({ st }) => st === 'ok').length, confirm = confirmLater.length;
570
+ $('#batch-summary').textContent = !has ? '六个板块都从这里更新:拖入或选择一个或多个 Excel,按工作表名识别板块。没选的板块沿用当前版本。'
571
+ : `已选 ${batchItems.length} 个文件:${[ready ? `${ready} 个可以提交` : '', confirm ? `${confirm} 个需确认` : '', reexport.length ? `${reexport.length} 个需要重新导出或调整` : ''].filter(Boolean).join(',') || '正在核对'}。${touched.has('target') ? '没选的板块' : '没选的板块和经营目标'}沿用当前版本。`;
572
+ $('#batch-clear').hidden = !has || batchRunning;
573
+ }
574
+ async function addBatchFiles(files) {
575
+ $('#receipt').hidden = true;
576
+ for (const file of files) {
577
+ if (!/\.xlsx$/i.test(file.name)) { batchItems.push({ file, moduleId:null, status:'failed', message:'不是 .xlsx 文件;旧版 .xls 请先另存为 .xlsx。' }); continue; }
578
+ if (file.size > currentUploadLimits().fileBytes) { batchItems.push({ file, moduleId:null, status:'failed', message:`超过 ${currentUploadLimits().fileBytes / 1048576} MB 上限。` }); continue; }
579
+ batchItems.push({ file, moduleId:null, status:'identifying' });
580
+ }
581
+ renderBatch();
582
+ for (const item of batchItems.filter(item => item.status === 'identifying')) {
583
+ try {
584
+ const result = await request('/api/identify', { method:'POST', headers:{'Content-Type':'application/octet-stream', 'X-Local-Token':state?.token || ''}, body:item.file });
585
+ item.moduleId = result.moduleId; item.reason = result.reason; item.status = result.moduleId ? 'ready' : 'unknown';
586
+ } catch (error) { item.status = 'unknown'; item.reason = `识别失败:${error.message}`; }
587
+ if (item.status === 'ready' && isUpdatable(item.moduleId)) await analyzeItem(item);
588
+ renderBatch();
589
+ }
590
+ }
591
+ async function uploadTarget(item) {
592
+ const result = await request(`/api/uploads/${encodeURIComponent(item.moduleId)}`, {
593
+ method:'POST', headers:{'Content-Type':'application/octet-stream', 'X-Filename':encodeURIComponent(item.file.name), 'X-Local-Token':state.token}, body:item.file,
594
+ });
595
+ return { result, receipt: null };
596
+ }
597
+ async function applyItem(item) {
598
+ working = {kind:'upload', moduleId:item.moduleId, stage:item.mode === 'full' ? '正在核对并更新资料' : '正在合并为新版本'}; renderControls();
599
+ try {
600
+ const { result } = isUpdatable(item.moduleId) ? { result: await request('/api/updates/apply', { method:'POST', headers:{'Content-Type':'application/json', 'X-Local-Token':state.token}, body:JSON.stringify({ stagedId:item.staged.stagedId, mode:item.mode, start:item.start, end:item.end, confirmMissing:!!item.confirmMissing }) }) } : await uploadTarget(item);
601
+ item.staged = null;
602
+ if (result.receipt) item.receipt = result.receipt;
603
+ if (result.warnings?.length) item.warnings = result.warnings;
604
+ if (result.state) applyState(result.state);
605
+ const module = result.state?.modules?.find(entry => entry.id === item.moduleId);
606
+ return { ok:true, duplicate:!!result.duplicate, pending:!!module?.candidateUpload, upload:result.upload };
607
+ } catch (error) {
608
+ if (error.data?.receipt) item.receipt = error.data.receipt;
609
+ return { ok:false, message:error.message };
610
+ } finally { working = null; await refresh(true); renderControls(); }
611
+ }
612
+ function changeText(item) {
613
+ const r = item.receipt;
614
+ if (!r) return '整份替换';
615
+ const figure = key => r.figures?.find(entry => entry.key === key);
616
+ const delta = (key, unit) => { const value = figure(key); if (!value) return ''; const d = figureDelta(value); return `${d.text === '0' ? '±0' : d.text}${unit}`; };
617
+ const arrow = key => { const value = figure(key); return value ? `${countText(value.before)} → ${countText(value.after)}` : ''; };
618
+ const auto = isUpdatable(item.moduleId) && modesOf(item.moduleId).length > 1 ? `(${item.modeAuto ? '系统建议' : '手动'})` : '';
619
+ const what = item.mode === 'range' ? `范围更新 ${dayRange(r.start, r.end)}${auto}` : item.mode === 'incremental' ? `增量追加 ${dayRange(r.file.start, r.file.end)}${auto}` : `整份替换${auto}`;
620
+ const core = { invoice: `净额 ${delta('amount', ' 万元')}`, movement: `扫码金额 ${delta('amount', ' 万元')}`, opening: `开瓶 ${delta('bottles', ' 瓶')}`, inventory: `${delta('rows', '')} 条盘点`,
621
+ terminal: `协议 ${arrow('agreements')}${r.disappearingAgreements ? `(已确认 ${countText(r.disappearingAgreements)} 份消失)` : ''}`, banquet: `场次 ${arrow('events')}` }[item.moduleId] || '';
622
+ return [what, core].filter(Boolean).join(',');
623
+ }
624
+ function renderReceipt() {
625
+ const section = $('#receipt');
626
+ if (!lastReceipt) { section.hidden = true; return; }
627
+ section.hidden = false;
628
+ $('#receipt-title').textContent = `本次更新回执 · ${lastReceipt.time}`;
629
+ const grid = $('#receipt-grid'); grid.replaceChildren();
630
+ for (const label of ['板块', '做了什么', '现在生效']) grid.append(element('span', 'receipt-col', label));
631
+ for (const line of lastReceipt.lines) grid.append(element('span', `receipt-board${line.ok ? '' : ' is-bad'}`, line.title), element('span', line.ok ? '' : 'is-bad', line.what), element('span', `receipt-now ${line.ok ? 'is-ok' : 'is-warn'}`, line.now));
632
+ $('#receipt-foot').textContent = lastReceipt.foot;
633
+ }
634
+ function nowText(moduleId) {
635
+ const module = moduleOf(moduleId), upload = selectedUpload(module);
636
+ if (!upload) return '—';
637
+ const step = upload.composition?.step;
638
+ const end = upload.coverage?.end ? shortDay(upload.coverage.end) : '';
639
+ const pending = module.candidateUpload ? '(检查项待处理,生成仍用上一版)' : '';
640
+ if (step) return `截至 ${end || '—'} · 第 ${step} 次更新${pending}`;
641
+ return `新基线${end ? ` · ${end}` : ''}${pending}`;
642
+ }
643
+ async function uploadBatch(andGenerate = false) {
644
+ const counts = batchConflicts();
645
+ const states = batchItems.map(item => ({ item, st: item.moduleId && counts.get(item.moduleId) > 1 ? 'conflict' : itemState(item) }));
646
+ const queue = states.filter(({ st }) => ['ok', 'confirm'].includes(st)).map(({ item }) => item);
647
+ if (!queue.length || batchRunning) return;
648
+ // Ticks are settled before anything changes; files that must be re-exported are skipped.
649
+ const unconfirmed = queue.filter(item => itemState(item) === 'confirm');
650
+ if (unconfirmed.length) { for (const item of unconfirmed) item.needConfirm = true; renderBatch(); setNotice('有文件需要先核对并勾选确认,本次还没有更新任何板块。', true); return; }
651
+ const skipped = states.filter(({ st }) => ['scope', 'adjust', 'conflict', 'failed', 'duplicate'].includes(st)).map(({ item }) => item);
652
+ batchRunning = true; generateAfterBatch = andGenerate; setNotice(''); renderBatch();
653
+ const lines = [];
654
+ for (const item of queue) {
655
+ item.status = 'uploading'; renderBatch();
656
+ while (currentBusy()) { await new Promise(resolve => setTimeout(resolve, 500)); await refresh(true); }
657
+ const result = await applyItem(item);
658
+ item.status = result.ok ? result.duplicate ? 'duplicate' : 'done' : 'failed';
659
+ item.pending = result.pending;
660
+ if (result.ok) lines.push({ title: moduleTitle(item.moduleId), ok: true, what: result.duplicate ? '与当前版本相同,未新增版本' : changeText(item), now: nowText(item.moduleId), moduleId: item.moduleId });
661
+ else lines.push({ title: moduleTitle(item.moduleId), ok: false, what: `未提交:${result.message}`, now: `沿用 · ${effectiveText(item.moduleId)}`, moduleId: item.moduleId });
662
+ renderBatch();
663
+ }
664
+ for (const item of skipped) {
665
+ if (!item.moduleId) continue;
666
+ const st = itemState(item);
667
+ const reason = item.status === 'duplicate' ? '这份文件已经处理过,未重复计入' : st === 'scope' ? '未提交:导出范围不一致,请重新导出' : item.status === 'failed' ? `未提交:${item.message || '文件未通过检查'}` : '未提交:需要先调整更新方式或区间';
668
+ lines.push({ title: moduleTitle(item.moduleId), ok: item.status === 'duplicate', what: reason, now: `沿用 · ${effectiveText(item.moduleId)}`, moduleId: item.moduleId });
669
+ }
670
+ lines.sort((a, b) => preferredOrder.indexOf(a.moduleId) - preferredOrder.indexOf(b.moduleId));
671
+ const failed = queue.filter(item => item.status === 'failed').length, pending = queue.some(item => item.pending);
672
+ const now = new Date();
673
+ const willGenerate = andGenerate && !failed && !pending && lines.some(line => line.ok);
674
+ lastReceipt = { time: `${pad2(now.getMonth() + 1)}/${pad2(now.getDate())} ${pad2(now.getHours())}:${pad2(now.getMinutes())}`, lines, generating: willGenerate,
675
+ foot: willGenerate ? '正在生成看板,完成后切到「看板」页。收到的原文件都保存在本机。'
676
+ : pending ? '有重复候选或组织对应待处理,请在下方“本次数据检查”确认后再生成。收到的原文件都保存在本机。'
677
+ : failed && andGenerate ? '有板块未通过,本次没有生成看板。收到的原文件都保存在本机。' : '收到的原文件都保存在本机。可直接生成看板。' };
678
+ for (const item of batchItems.splice(0, batchItems.length)) await discardStaged(item);
679
+ batchRunning = false; generateAfterBatch = false;
680
+ renderBatch(); renderReceipt(); renderControls();
681
+ $('#receipt').scrollIntoView({ behavior: 'smooth', block: 'start' });
682
+ if (willGenerate) await generate(false);
683
+ }
684
+ $('#batch-input').addEventListener('change', event => { const files = [...event.target.files]; event.target.value = ''; addBatchFiles(files); });
685
+ $('#batch-more').addEventListener('change', event => { const files = [...event.target.files]; event.target.value = ''; addBatchFiles(files); });
686
+ $('#batch-upload').addEventListener('click', () => uploadBatch(false));
687
+ $('#batch-generate').addEventListener('click', () => uploadBatch(true));
688
+ $('#batch-clear').addEventListener('click', async () => { const items = batchItems.splice(0, batchItems.length); renderBatch(); for (const item of items) await discardStaged(item); });
689
+ $('#receipt-close').addEventListener('click', () => { lastReceipt = null; renderReceipt(); });
690
+ const panel = $('#update-panel'), drop = $('#batch-drop');
691
+ for (const name of ['dragenter', 'dragover']) panel.addEventListener(name, event => { event.preventDefault(); drop.classList.add('is-dragging'); panel.classList.add('is-dragging'); });
692
+ for (const name of ['dragleave', 'drop']) panel.addEventListener(name, event => { event.preventDefault(); drop.classList.remove('is-dragging'); panel.classList.remove('is-dragging'); });
693
+ panel.addEventListener('drop', event => addBatchFiles([...event.dataTransfer.files]));
694
+
695
+ async function generate(allowPending = false) {
696
+ if (currentBusy() || !state?.token || state.app?.mode !== 'real' || !state.modules?.some(module => module.activeUpload || module.candidateUpload)) return;
697
+ working = {kind:'generate', stage:'正在创建生成任务'}; setNotice(''); renderControls();
698
+ try {
699
+ const result = await request('/api/generations', {method:'POST', headers:{'Content-Type':'application/json', 'X-Local-Token':state.token}, body:JSON.stringify({allowPending})});
700
+ trackedGeneration = result.generation.id;
701
+ } catch (error) { setNotice(`无法开始生成:${error.message}`, true); }
702
+ finally { working = null; await refresh(); renderControls(); }
703
+ }
704
+
705
+ $('#refresh').addEventListener('click', async () => { setNotice(''); await refresh(); });
706
+ $('#generate-button').addEventListener('click', () => generate(false));
707
+ document.querySelectorAll('.rail-item').forEach(link => link.addEventListener('click', () => {
708
+ document.querySelectorAll('.rail-item').forEach(item => item.classList.toggle('active', item === link));
709
+ }));
710
+ window.ReviewUI?.init({request, getState: () => state, applyState, isBusy: () => Boolean(currentBusy()) || !connected, setWorking: value => { working = value; renderControls(); }, generate});
711
+ refresh();
712
+ setInterval(() => { if (document.visibilityState === 'visible' || currentBusy()) refresh(true); }, 2000);
713
+ document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') refresh(true); });