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,260 @@
1
+ import { readFile, writeFile, mkdir, realpath, rm } from 'node:fs/promises';
2
+ import { resolve, sep } from 'node:path';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { gzipSync } from 'node:zlib';
5
+ import { buildSourcePayload } from '../real-data/source-payload.mjs';
6
+ import { applyOrganizationMapping, buildDecisionContract } from '../real-data/organization-mapping.mjs';
7
+ import { packV10Payload, sanitizeV10Payload } from '../real-data/v10-template.mjs';
8
+
9
+ const IDS = ['invoice', 'movement', 'opening', 'terminal', 'inventory', 'banquet'];
10
+ const ORG = ['marketingCompany', 'businessUnit', 'theater', 'region', 'office', 'unit'];
11
+ const sha = value => createHash('sha256').update(value).digest('hex');
12
+ const validSegment = value => typeof value === 'string' && value === value.trim() && value.length > 0 && value.length <= 200
13
+ && !/[\u0000-\u001f]/.test(value) && !['未提供', '未知', '未分配', '组织待确认'].includes(value);
14
+ const fullPath = path => Array.isArray(path) && path.length === 6 && path.every(validSegment);
15
+ const ready = module => module && ['ready', 'partial'].includes(module.state);
16
+ const clone = value => structuredClone(value);
17
+ export const websiteScopeId = path => sha(JSON.stringify(path));
18
+
19
+ function validScope(path) {
20
+ return Array.isArray(path) && [0, 3, 4, 5].includes(path.length)
21
+ && path.every(validSegment);
22
+ }
23
+
24
+ /** Prefixes are compared as path segments, never display labels or text prefixes. */
25
+ export function websiteScopeMatches(path, scope) {
26
+ if (!validScope(scope)) throw new Error('网站授权组织路径格式无效。');
27
+ return !scope.length || fullPath(path) && scope.every((part, index) => path[index] === part);
28
+ }
29
+
30
+ export function websiteScopes(payload) {
31
+ const scopes = new Map([[websiteScopeId([]), []]]);
32
+ for (const id of IDS) for (const row of payload.modules[id].records) {
33
+ if (!fullPath(row.orgPath)) continue;
34
+ for (const length of [3, 4, 5]) {
35
+ const path = row.orgPath.slice(0, length);
36
+ scopes.set(websiteScopeId(path), path);
37
+ }
38
+ }
39
+ return [...scopes].map(([id, path]) => ({ id, path }));
40
+ }
41
+
42
+ /** Keep only the exact authorized rows. Never send raw diagnostics, filenames,
43
+ * global totals, or an unfiltered organization dictionary to the browser.
44
+ * Unknown identity inputs remain a conservative rule gate, not leaked rows.
45
+ */
46
+ export function scopeWebsitePayload(input, scopePath) {
47
+ if (!validScope(scopePath)) throw new Error('网站授权组织路径格式无效。');
48
+ return scopeSanitizedPayload(sanitizeV10Payload(input), scopePath);
49
+ }
50
+
51
+ function scopeSanitizedPayload(input, scopePath) {
52
+ const clean = { ...input, sources: Object.fromEntries(Object.entries(input.sources).map(([id, value]) => [id, { ...value }])),
53
+ modules: { ...input.modules }, ...(input.decisionContract ? { decisionContract: clone(input.decisionContract) } : {}) };
54
+ if (scopePath.length) {
55
+ const allMovement = clean.modules.movement.records;
56
+ const allModules = clean.modules;
57
+ clean.modules = Object.fromEntries(IDS.map(id => [id, {
58
+ ...allModules[id], records: allModules[id].records.filter(row => websiteScopeMatches(row.orgPath, scopePath)),
59
+ }]));
60
+ const terminalCodes = new Set(clean.modules.terminal.records.map(row => row.terminalCode).filter(Boolean));
61
+ // The existing terminal builder treats missing scan identity as unknown.
62
+ // Filtering away that evidence must not make a scoped effective count zero.
63
+ const uncertainIdentity = allMovement.some(row => !row.terminalCode
64
+ || !fullPath(row.orgPath) && terminalCodes.has(row.terminalCode));
65
+ if (uncertainIdentity && clean.decisionContract?.terminalIdentity) {
66
+ clean.decisionContract.terminalIdentity = { status: 'pending', key: 'original-code' };
67
+ }
68
+ // Whole-source missing dates can invalidate common-period calculations.
69
+ // Preserve that gate when its evidence is outside the authorized payload.
70
+ if (['invoice', 'movement', 'opening', 'inventory'].some(id => allModules[id].records.some(row => !row.date))
71
+ && clean.decisionContract?.crossTableMetrics) {
72
+ clean.decisionContract.crossTableMetrics = { status: 'pending' };
73
+ }
74
+ }
75
+ for (const source of Object.values(clean.sources)) source.originalName = '已授权数据来源';
76
+ return clean;
77
+ }
78
+
79
+ // This is the same exact-product-code uniqueness rule used by source-payload.
80
+ // A mixed-version release must resolve inventory classification from its actual
81
+ // selected invoice/movement records rather than the failed candidate's sources.
82
+ function refreshInventoryClassification(payload) {
83
+ const products = new Map();
84
+ for (const id of ['invoice', 'movement']) for (const row of payload.modules[id].records) {
85
+ if (!row.productCode || !row.brand || !row.category) continue;
86
+ const candidates = products.get(row.productCode) ?? new Map();
87
+ candidates.set(JSON.stringify([row.brand, row.category]), { brand: row.brand, category: row.category });
88
+ products.set(row.productCode, candidates);
89
+ }
90
+ for (const row of payload.modules.inventory.records) {
91
+ const candidates = products.get(row.productCode);
92
+ if (candidates?.size === 1) {
93
+ Object.assign(row, [...candidates.values()][0]); row.classificationStatus = 'unique-product-code';
94
+ } else {
95
+ row.brand = null; row.category = null; row.classificationStatus = candidates?.size > 1 ? 'conflict' : 'unmapped';
96
+ }
97
+ }
98
+ }
99
+
100
+ /** Merge only successful candidate modules; all fallback provenance is local.
101
+ * Reapply current source-bound mappings/rules to the resulting combination.
102
+ */
103
+ export function mergeWebsiteModules(candidate, previous, decisions = {}, previousManifest = null) {
104
+ const payload = clone(candidate), modules = {}, localFailures = {};
105
+ payload.mode = 'real';
106
+ for (const id of IDS) {
107
+ const next = payload.modules[id];
108
+ const failed = !ready(next);
109
+ if (failed) {
110
+ localFailures[id] = next?.reason || '该板块没有通过校验和计算。';
111
+ if (ready(previous?.modules?.[id]) && previous.sources?.[id]) {
112
+ payload.modules[id] = clone(previous.modules[id]);
113
+ payload.sources[id] = clone(previous.sources[id]);
114
+ payload.coverage[id] = clone(previous.coverage[id]);
115
+ } else {
116
+ delete payload.sources[id];
117
+ payload.modules[id] = { state: 'unavailable', records: [], metrics: {}, unavailable: [], warnings: [] };
118
+ payload.coverage[id] = { start: null, end: null, semantics: null };
119
+ }
120
+ }
121
+ const source = payload.sources[id];
122
+ const same = source && previous?.sources?.[id]?.sha256 === source.sha256
123
+ && previous.sources[id].uploadId === source.uploadId;
124
+ modules[id] = {
125
+ status: !source || !ready(payload.modules[id]) ? 'unavailable' : failed || same ? 'retained' : 'updated',
126
+ uploadId: source?.uploadId ?? null,
127
+ updatedAt: same || failed && source ? previousManifest?.modules?.[id]?.updatedAt ?? previous?.generatedAt ?? payload.generatedAt : payload.generatedAt,
128
+ ...(failed ? { error: source ? '本次处理未成功,继续展示上次成功数据。' : '暂无有效数据,请在本地后台检查。' } : {}),
129
+ };
130
+ }
131
+ // Remove a previous source-bound mapping before reevaluating the mixed set.
132
+ for (const id of IDS) for (const row of payload.modules[id].records) {
133
+ if (Array.isArray(row.originalOrgPath)) {
134
+ row.orgPath = [...row.originalOrgPath];
135
+ row.org = Object.fromEntries(ORG.map((key, index) => [key, row.orgPath[index]]));
136
+ row.orgKey = JSON.stringify(row.orgPath);
137
+ }
138
+ delete row.organizationMapping;
139
+ }
140
+ const organizationMapping = applyOrganizationMapping(payload, decisions?.organizationMapping);
141
+ payload.decisionContract = buildDecisionContract(payload, decisions, organizationMapping);
142
+ refreshInventoryClassification(payload);
143
+ if (!IDS.some(id => ready(payload.modules[id]) && payload.modules[id].records.length)) {
144
+ throw new Error('没有可供网站展示的有效数据;已保留线上版本。');
145
+ }
146
+ return { payload, modules, localFailures, organizationMapping };
147
+ }
148
+
149
+ async function optionalBytes(file) {
150
+ try { return await readFile(file); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
151
+ }
152
+
153
+ async function previousFrom(value) {
154
+ if (!value) return null;
155
+ const previous = typeof value === 'string' ? JSON.parse(await readFile(value, 'utf8')) : value;
156
+ if (!previous.payload || !previous.manifest) throw new Error('上次网站版本缺少本地回退资料。');
157
+ if (previous.payloadSha256 && sha(JSON.stringify(previous.payload)) !== previous.payloadSha256) throw new Error('上次网站版本的本地回退资料校验失败。');
158
+ return previous;
159
+ }
160
+
161
+ /** Local-only preparation. No network calls and no source-store mutations.
162
+ * outputDir must be new; an interrupted/incomplete directory is never reused.
163
+ * previousRelease is a returned result or the previous local release.json path.
164
+ */
165
+ export async function prepareWebsiteRelease({ dataDir, outputDir, previousRelease = null, baseRevision, uploadAttempts = {}, onStage = () => {} } = {}) {
166
+ if (!dataDir || !outputDir) throw new Error('必须提供本地数据目录和新的网站验收目录。');
167
+ dataDir = await realpath(resolve(dataDir)); outputDir = resolve(outputDir);
168
+ if (outputDir === dataDir || ['uploads', 'generations'].some(name => outputDir === resolve(dataDir, name) || outputDir.startsWith(`${resolve(dataDir, name)}${sep}`))) throw new Error('网站验收目录不能覆盖上传或历史成品目录。');
169
+ const stateFile = resolve(dataDir, 'state.json');
170
+ const stateBefore = await readFile(stateFile);
171
+ const decisionsFile = resolve(dataDir, 'generation-decisions.json');
172
+ const decisionBefore = await optionalBytes(decisionsFile);
173
+ let decisions = {};
174
+ if (decisionBefore) {
175
+ try { decisions = JSON.parse(decisionBefore); if (!decisions || typeof decisions !== 'object' || Array.isArray(decisions)) throw new Error(); }
176
+ catch { throw new Error('本机业务决定文件无效,未创建网站新版本。'); }
177
+ }
178
+ const previous = await previousFrom(previousRelease);
179
+ onStage('正在读取各板块最新上传并独立校验、计算');
180
+ const built = await buildSourcePayload({ dataDir, decisionsFile: decisionBefore ? decisionsFile : undefined });
181
+ if (built.report.activeChangedDuringRead || built.report.decisionError) throw new Error('读取期间来源或业务决定发生变化,请重新准备网站版本。');
182
+ const merged = mergeWebsiteModules(built.payload, previous?.payload, decisions, previous?.manifest);
183
+ // The original upload server records successful installations only. The
184
+ // website controller supplies its latest per-module attempt, so an invalid
185
+ // upload that left active unchanged is still visible as a retained version.
186
+ const sourceState = JSON.parse(stateBefore);
187
+ const uploadFailures = {};
188
+ for (const id of IDS) {
189
+ const attempt = uploadAttempts[id];
190
+ const active = sourceState.uploads.find(item => item.id === sourceState.active[id] && item.moduleId === id);
191
+ if (attempt?.status !== 'failed' || !Number.isFinite(Date.parse(attempt.attemptAt))) continue;
192
+ if (active?.uploadedAt && Date.parse(active.uploadedAt) > Date.parse(attempt.attemptAt)) continue;
193
+ const info = merged.modules[id];
194
+ info.status = info.uploadId ? 'retained' : 'unavailable';
195
+ info.error = info.uploadId ? '本次上传未通过,继续使用上一有效版本。' : '本次上传未通过,暂无有效数据。';
196
+ uploadFailures[id] = { status: 'failed', attemptAt: attempt.attemptAt };
197
+ }
198
+ const generatedAt = new Date().toISOString(), revision = randomUUID();
199
+ merged.payload.generatedAt = generatedAt;
200
+ const snapshot = () => {
201
+ const state = JSON.parse(stateBefore);
202
+ return JSON.stringify({ active: state.active, uploads: state.uploads.map(({ id, moduleId, sha256, validationContract }) => ({ id, moduleId, sha256, validationContract })) });
203
+ };
204
+ const expectedSnapshot = snapshot();
205
+ const verify = async () => {
206
+ const state = JSON.parse(await readFile(stateFile, 'utf8'));
207
+ const current = JSON.stringify({ active: state.active, uploads: state.uploads.map(({ id, moduleId, sha256, validationContract }) => ({ id, moduleId, sha256, validationContract })) });
208
+ if (current !== expectedSnapshot) throw new Error('准备网站版本期间上传资料发生变化,未生成可同步版本。');
209
+ const now = await optionalBytes(decisionsFile);
210
+ if ((now ? sha(now) : null) !== (decisionBefore ? sha(decisionBefore) : null)) throw new Error('准备网站版本期间业务决定发生变化,未生成可同步版本。');
211
+ // Recheck successfully-read new bytes. Cached retained modules have already
212
+ // been verified as a prior accepted local release and need no old-file read.
213
+ for (const id of IDS) if (ready(built.payload.modules[id])) {
214
+ const source = built.payload.sources[id];
215
+ const file = await realpath(resolve(dataDir, 'uploads', source.uploadId, 'source.xlsx'));
216
+ if (!file.startsWith(`${resolve(dataDir, 'uploads')}${sep}`) || sha(await readFile(file)) !== source.sha256) throw new Error('准备网站版本期间来源文件发生变化,未生成可同步版本。');
217
+ }
218
+ };
219
+ await verify();
220
+ await mkdir(outputDir, { mode: 0o700 });
221
+ try {
222
+ await mkdir(resolve(outputDir, 'objects'), { mode: 0o700 });
223
+ const manifest = { revision, baseRevision: baseRevision === undefined ? previous?.manifest?.revision ?? null : baseRevision,
224
+ generatedAt, modules: merged.modules, scopes: [] };
225
+ const objects = [];
226
+ const scopes = websiteScopes(merged.payload);
227
+ if (scopes.length > 2000) throw new Error('授权组织范围超过网站清单上限,请调整范围后再同步。');
228
+ const sanitized = sanitizeV10Payload(merged.payload);
229
+ for (let index = 0; index < scopes.length; index++) {
230
+ const scope = scopes[index];
231
+ onStage(`正在生成授权范围数据 ${index + 1}/${scopes.length}`);
232
+ const scoped = scopeSanitizedPayload(sanitized, scope.path);
233
+ const bytes = gzipSync(Buffer.from(JSON.stringify(packV10Payload(scoped))), { level: 6 });
234
+ if (bytes.length > 64 * 1024 * 1024) throw new Error('单个授权范围数据超过网站同步上限,请缩小数据范围。');
235
+ const info = { ...scope, sha256: sha(bytes), bytes: bytes.length };
236
+ const file = resolve(outputDir, 'objects', `${scope.id}.json.gz`);
237
+ await writeFile(file, bytes, { flag: 'wx', mode: 0o600 });
238
+ manifest.scopes.push(info); objects.push({ ...info, file });
239
+ }
240
+ await verify();
241
+ const report = { ...built.report, localFailures: merged.localFailures, uploadFailures, organizationMapping: merged.organizationMapping,
242
+ decisionContract: merged.payload.decisionContract,
243
+ summary: Object.fromEntries(IDS.map(id => [id, { state: merged.payload.modules[id].state, ...merged.payload.modules[id].metrics }])),
244
+ rejectedOrganizationRows: Object.fromEntries(IDS.map(id => [id, merged.payload.modules[id].records.filter(row => !fullPath(row.orgPath)).length])) };
245
+ const payload = merged.payload;
246
+ const sourceVersions = Object.fromEntries(Object.entries(payload.sources).map(([id, source]) => [id, { uploadId: source.uploadId, sha256: source.sha256 }]));
247
+ const release = { schemaVersion: 1, payload, payloadSha256: sha(JSON.stringify(payload)), sourceVersions, manifest };
248
+ const manifestPath = resolve(outputDir, 'manifest.json'), releasePath = resolve(outputDir, 'release.json');
249
+ await writeFile(manifestPath, JSON.stringify(manifest, null, 2), { flag: 'wx', mode: 0o600 });
250
+ await writeFile(resolve(outputDir, 'diagnostics.json'), JSON.stringify(report, null, 2), { flag: 'wx', mode: 0o600 });
251
+ await writeFile(releasePath, JSON.stringify(release), { flag: 'wx', mode: 0o600 });
252
+ onStage('网站数据已准备完成,等待本地验收后同步');
253
+ return { ...release, report, manifestPath, releasePath, objects };
254
+ } catch (error) {
255
+ // This function created this otherwise-new directory, so cleanup cannot
256
+ // remove a previous release or a user-owned output.
257
+ await rm(outputDir, { recursive: true, force: true });
258
+ throw error;
259
+ }
260
+ }
@@ -0,0 +1,34 @@
1
+ <!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>战区看板 · 本地验收与同步</title><style>
2
+ :root{font-family:system-ui,-apple-system,"PingFang SC",sans-serif;color:#18384b;background:#f3f6f8;font-size:14px}*{box-sizing:border-box}body{margin:0}header{padding:25px 34px;background:#102e42;color:white;display:flex;align-items:center;justify-content:space-between}h1{font-size:22px;margin:0 0 7px}header p{margin:0;color:#a8c0ce}main{max-width:1350px;margin:24px auto;padding:0 24px}nav{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:20px}button,a.button{font:inherit;border:1px solid #ccd9e0;border-radius:8px;padding:10px 16px;background:white;color:#18384b;cursor:pointer;text-decoration:none}button:hover,a.button:hover{border-color:#0c827c}button:disabled{opacity:.5;cursor:wait}.primary{background:#087d77;color:white;border-color:#087d77}.selected{background:#deefef;border-color:#087d77}section{background:white;padding:24px;border:1px solid #dde6eb;border-radius:12px;margin-bottom:20px}h2{font-size:18px;margin:0 0 12px}.muted{color:#627987;line-height:1.7}.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}.module{padding:20px;border:1px solid #dce5e9;border-radius:10px}.module h3{margin:0 0 10px;font-size:16px}.module input{max-width:100%;margin:12px 0}.row{display:flex;align-items:center;gap:12px;flex-wrap:wrap}.status{padding:12px 16px;background:#e8f4f1;border-radius:8px;margin-bottom:18px;white-space:pre-wrap}.error{background:#fff0eb;color:#9b3c21}.badge{font-size:12px;background:#e6f2ef;padding:4px 8px;border-radius:20px}.warning{background:#fff4dc;color:#946417}.field{display:grid;gap:7px;margin:16px 0}.field input{font:inherit;border:1px solid #c8d7e0;border-radius:7px;padding:10px 12px;width:100%;max-width:620px}.hidden{display:none!important}iframe{width:100%;height:820px;border:1px solid #dde6eb;border-radius:10px;background:white}.events{display:grid;gap:12px}.event{border-bottom:1px solid #e5edf1;padding-bottom:12px;line-height:1.7}small{color:#718795}.version{word-break:break-all;font-family:ui-monospace,monospace}footer{margin:24px 0;color:#718795}.step{color:#087d77;font-weight:600}@media(max-width:900px){.grid{grid-template-columns:repeat(2,1fr)}header{padding:20px}.row{align-items:flex-start}}@media(max-width:600px){.grid{grid-template-columns:1fr}main{padding:0 12px}section{padding:18px}header{display:block}iframe{height:680px}}
3
+ </style></head><body><header><div><h1>战区经营看板 · 本地工作台</h1><p>上传资料,在本机验收后同步到网站</p></div><a id="website" class="button hidden" target="_blank" rel="noopener">打开线上看板 ↗</a></header><main><nav><button data-tab="upload" class="selected">1 · 上传数据</button><button data-tab="review">2 · 本地验收</button><button data-tab="history">同步记录</button><button data-tab="settings">网站设置</button></nav><div id="message" class="status hidden" role="status"></div><div id="busy" class="status hidden" role="status"></div>
4
+ <div id="upload" class="tab"><section><h2>六板块资料</h2><p class="muted">每个板块单独上传。校验失败保留上一次有效文件;成功的板块继续使用新数据。原始 Excel 留在本机。</p><p id="uploadCapacity" class="muted"></p><div class="grid" id="modules"></div></section><section class="row"><div><h2>准备本地验收版本</h2><div class="muted">读取各板块有效资料并计算。只有点击“验收通过,立即同步”后,网站数据才会变化。</div></div><button id="prepare" class="primary action">计算并准备预览</button></section></div>
5
+ <div id="review" class="tab hidden"><section><h2>本地验收</h2><div id="candidate" class="muted">尚未准备候选版本。</div><div id="moduleResults" class="grid"></div><div class="row" style="margin-top:18px"><button id="preview" class="action">打开当前预览</button><button id="sync" class="primary action">验收通过,立即同步</button></div><p class="muted">失败板块展示其上一份成功数据;其他成功板块展示最新数据。请核对各板块状态后同步。</p></section><iframe id="previewFrame" class="hidden" title="本地真实数据看板预览"></iframe></div>
6
+ <div id="history" class="tab hidden"><section><h2>操作与同步记录</h2><div id="events" class="events"></div></section></div>
7
+ <div id="settings" class="tab hidden"><section><h2>连接线上网站</h2><p class="muted">网站同步凭据只保存在本机,用于发送验收通过的数据,不是查看者的登录密码。</p><form id="configForm"><label class="field">网站首页地址<input id="siteUrl" type="url" placeholder="https://…chatgpt.site" required></label><label class="field">同步凭据<input id="syncKey" type="password" autocomplete="new-password" placeholder="已配置时留空可保留"></label><button class="primary action" type="submit">保存连接设置</button></form></section><section><h2>首次创建网站管理员</h2><p class="muted">首次使用时设置普通账号和密码。已创建后可在网站“账号管理”中管理其他人员。</p><form id="bootstrapForm"><label class="field">管理员账号<input id="adminName" autocomplete="username" minlength="3" maxlength="64" required></label><label class="field">管理员密码<input id="adminPassword" type="password" autocomplete="new-password" minlength="12" maxlength="128" required></label><button class="action" type="submit">创建管理员</button></form></section></div><footer>本地上传与计算 · 手动验收后同步 · 线上按组织权限查看</footer></main>
8
+ <script>
9
+ let state=null,lastCandidate=null,shownEvents='',uploadBusy=false;const titles={invoice:'发票销售',movement:'终端动销',opening:'消费者开瓶',terminal:'终端签约',inventory:'库存盘点',banquet:'宴席执行'};const $=id=>document.getElementById(id);const time=v=>v?new Date(v).toLocaleString('zh-CN'):'—';
10
+ function message(text,error=false){$('message').textContent=text;$('message').className='status'+(error?' error':'');}
11
+ function tab(name){document.querySelectorAll('.tab').forEach(e=>e.classList.toggle('hidden',e.id!==name));document.querySelectorAll('[data-tab]').forEach(e=>e.classList.toggle('selected',e.dataset.tab===name));}
12
+ document.querySelectorAll('[data-tab]').forEach(e=>e.onclick=()=>tab(e.dataset.tab));
13
+ async function api(path,body){const response=await fetch(path,{method:body===undefined?'GET':'POST',cache:'no-store',headers:body===undefined?{}:{'Content-Type':'application/json','X-Local-Token':state?.token||''},body:body===undefined?undefined:JSON.stringify(body)});const result=await response.json();if(!response.ok)throw new Error(result.error||'请求失败');return result;}
14
+ function line(parent,text,cls){const p=document.createElement('div');p.textContent=text;if(cls)p.className=cls;parent.append(p);return p;}
15
+ function paint(){
16
+ if(state.uploadLimits)$('uploadCapacity').textContent='单文件 ≤ '+state.uploadLimits.fileBytes/1048576+' MB;单表解压 ≤ '+state.uploadLimits.entryBytes/1048576+' MB;整本解压 ≤ '+state.uploadLimits.totalBytes/1048576+' MB。上传整份替换,多次上传不会合并。';
17
+ $('busy').textContent=state.busy?.stage||'';$('busy').classList.toggle('hidden',!state.busy);document.querySelectorAll('.action').forEach(b=>b.disabled=Boolean(state.busy)||uploadBusy);
18
+ $('preview').disabled=!state.candidate||Boolean(state.busy);$('sync').disabled=!state.candidate||!state.settings.configured||Boolean(state.busy);
19
+ if(state.settings.siteUrl){$('website').href=state.settings.siteUrl;$('website').classList.remove('hidden');}if(document.activeElement!==$('siteUrl'))$('siteUrl').value=state.settings.siteUrl;
20
+ if(!$('modules').children.length)for(const m of state.modules){const div=document.createElement('article');div.className='module';div.id='module-'+m.id;const heading=document.createElement('h3');heading.textContent=m.title;div.append(heading);line(div,'','source');line(div,'','attempt');const input=document.createElement('input');input.type='file';input.accept='.xlsx';input.setAttribute('aria-label',m.title+' Excel');const button=document.createElement('button');button.textContent='上传并校验';button.className='action';button.onclick=()=>upload(m.id,input);div.append(input,button);$('modules').append(div);}
21
+ for(const m of state.modules){const box=$('module-'+m.id);box.querySelector('.source').textContent=m.active?'有效资料:'+(m.active.originalName||m.active.filename||'已上传')+' · '+time(m.active.uploadedAt):'尚无有效资料';const attempt=state.uploadAttempts[m.id];box.querySelector('.attempt').textContent=attempt?.status==='failed'?'本次失败,保留上一有效版本:'+attempt.error:'';box.querySelector('.attempt').className='attempt muted';}
22
+ if(lastCandidate!==state.candidate?.revision){lastCandidate=state.candidate?.revision;$('moduleResults').replaceChildren();$('candidate').replaceChildren();if(state.candidate){line($('candidate'),'准备时间:'+time(state.candidate.generatedAt));line($('candidate'),'版本:'+state.candidate.revision,'version');for(const[id,m]of Object.entries(state.candidate.modules)){const box=document.createElement('div');box.className='module';line(box,titles[id]);line(box,({updated:'已更新',retained:'保留上一版本',unavailable:'暂无有效数据'})[m.status]||m.status,'badge '+(m.status!=='updated'?'warning':''));if(m.error)line(box,m.error,'muted');line(box,'数据时间:'+time(m.updatedAt),'muted');$('moduleResults').append(box);}}else $('candidate').textContent='尚未准备候选版本。';}
23
+ const signature=JSON.stringify(state.events);if(signature!==shownEvents){shownEvents=signature;$('events').replaceChildren();for(const e of state.events){const div=document.createElement('div');div.className='event';line(div,(e.ok?'✓ ':'! ')+e.message);line(div,time(e.at)+(e.revision?' · '+e.revision:''),'muted');$('events').append(div);}if(!state.events.length)line($('events'),'尚无操作记录。','muted');}
24
+ }
25
+ async function refresh(){try{const wasBusy=state?.busy;state=await api('/local/state');paint();if(wasBusy&&!state.busy&&state.events[0])message(state.events[0].message,!state.events[0].ok);}catch(e){message(e.message,true);}}
26
+ async function upload(id,input){if(!input.files[0])return message('请先选择该板块的 .xlsx 文件。',true);uploadBusy=true;paint();try{const file=input.files[0];const response=await fetch('/local/upload/'+id,{method:'POST',headers:{'X-Local-Token':state.token,'X-Filename':encodeURIComponent(file.name),'Content-Type':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'},body:file});const result=await response.json();if(!response.ok)throw new Error(result.error);message(titles[id]+'已上传并通过校验。');input.value='';}catch(e){message(e.message,true);}finally{uploadBusy=false;await refresh();}}
27
+ async function act(path,body,success){try{await api(path,body);message(success);await refresh();}catch(e){message(e.message,true);}}
28
+ $('prepare').onclick=()=>act('/local/prepare',{},'正在计算候选数据;完成后可进入本地验收。');
29
+ $('preview').onclick=()=>{$('previewFrame').src='/local/preview?revision='+encodeURIComponent(state.candidate.revision);$('previewFrame').classList.remove('hidden');};
30
+ $('sync').onclick=()=>act('/local/sync',{revision:state.candidate.revision},'已确认本地验收,正在同步;网站将在上传完整后启用新版。');
31
+ $('configForm').onsubmit=async e=>{e.preventDefault();await act('/local/config',{siteUrl:$('siteUrl').value.trim(),syncKey:$('syncKey').value},'网站连接设置已保存。');$('syncKey').value='';};
32
+ $('bootstrapForm').onsubmit=async e=>{e.preventDefault();await act('/local/bootstrap',{username:$('adminName').value.trim(),password:$('adminPassword').value},'网站管理员已创建,可打开线上看板登录。');$('adminPassword').value='';};
33
+ refresh();setInterval(refresh,2000);
34
+ </script></body></html>
@@ -0,0 +1,147 @@
1
+ import http from 'node:http';
2
+ import { createReadStream } from 'node:fs';
3
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { resolve } from 'node:path';
5
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { atomicJson } from '../store.mjs';
8
+ import { uploadLimits, uploadSizeError } from '../recognition/upload-limits.mjs';
9
+ import { moduleDefinitions } from '../modules.mjs';
10
+ import { renderV10Dashboard } from '../real-data/v10-template.mjs';
11
+ import { prepareWebsiteRelease } from './exporter.mjs';
12
+ import { syncWebsiteRelease, websiteOrigin, websiteRequest } from './client.mjs';
13
+
14
+ const PROJECT = fileURLToPath(new URL('../../../', import.meta.url));
15
+ const IDS = new Set(moduleDefinitions.map(item => item.id));
16
+ const jsonRead = async (path, fallback) => { try { return JSON.parse(await readFile(path, 'utf8')); } catch (error) { if (error.code === 'ENOENT') return fallback; throw error; } };
17
+ async function readBody(request, limit = 32_768, limitMessage = () => '上传内容超过允许大小。') {
18
+ if (Number(request.headers['content-length']) > limit) throw new Error(limitMessage(Number(request.headers['content-length'])));
19
+ let size = 0; const chunks = [];
20
+ for await (const chunk of request) { size += chunk.length; if (size > limit) throw new Error(limitMessage(size)); chunks.push(chunk); }
21
+ return Buffer.concat(chunks);
22
+ }
23
+
24
+ export async function createWebsiteSyncServer({ port = 4188, dataDir = resolve(PROJECT, '本机后台数据'), workDir = resolve(PROJECT, '本机后台数据/website-sync'), uploadOrigin = 'http://127.0.0.1:4180', prepare = prepareWebsiteRelease, render = renderV10Dashboard, synchronize = syncWebsiteRelease, fetchImpl = fetch } = {}) {
25
+ dataDir = resolve(dataDir); workDir = resolve(workDir);
26
+ const uploadURL = new URL(uploadOrigin);
27
+ if (!['127.0.0.1', 'localhost'].includes(uploadURL.hostname) || uploadURL.protocol !== 'http:') throw new Error('上传后台必须位于本机。');
28
+ await mkdir(resolve(workDir, 'releases'), { recursive: true, mode: 0o700 });
29
+ const stateFile = resolve(workDir, 'state.json'), configFile = resolve(workDir, 'settings.json');
30
+ let state = await jsonRead(stateFile, { schemaVersion: 1, candidate: null, approvedRelease: null, published: null, uploadAttempts: {}, events: [] });
31
+ if (state.schemaVersion !== 1 || !Array.isArray(state.events)) throw new Error('网站同步记录损坏,已停止以保护原数据。');
32
+ let config = await jsonRead(configFile, {}), busy = null, candidate = null, actualPort, activeTask = null, writing = false, closing = false;
33
+ const token = randomBytes(32).toString('hex');
34
+ const save = () => atomicJson(stateFile, state);
35
+ const event = (kind, ok, message, revision) => { state.events.unshift({ id: randomUUID(), at: new Date().toISOString(), kind, ok, message, ...(revision ? { revision } : {}) }); state.events = state.events.slice(0, 100); };
36
+ const loadCandidate = async () => {
37
+ if (!state.candidate) throw new Error('请先准备数据并完成本地验收。');
38
+ if (!candidate || candidate.manifest.revision !== state.candidate.revision) {
39
+ const local = await jsonRead(state.candidate.releasePath);
40
+ if (!local) throw new Error('候选资料不存在,请重新准备。');
41
+ if (local.manifest?.revision !== state.candidate.revision
42
+ || local.payloadSha256 !== createHash('sha256').update(JSON.stringify(local.payload)).digest('hex')
43
+ || state.candidate.manifestSha256 && state.candidate.manifestSha256 !== createHash('sha256').update(JSON.stringify(local.manifest)).digest('hex')) throw new Error('候选资料校验失败,请重新准备并验收。');
44
+ candidate = { ...local, releasePath: state.candidate.releasePath };
45
+ }
46
+ return candidate;
47
+ };
48
+ const view = async () => {
49
+ const source = await jsonRead(resolve(dataDir, 'state.json'), { active: {}, uploads: [] });
50
+ return { token, busy, uploadLimits, candidate: state.candidate, published: state.published, events: state.events, uploadAttempts: state.uploadAttempts,
51
+ settings: { siteUrl: config.siteUrl || '', configured: Boolean(config.siteUrl && config.syncKey) },
52
+ modules: moduleDefinitions.map(({ id, title }) => ({ id, title, active: (source.uploads || []).find(item => item.id === source.active?.[id]) || null })), uploadOrigin };
53
+ };
54
+ const json = (response, value, status = 200) => { response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }); response.end(JSON.stringify(value)); };
55
+ const guard = (request, write = false) => {
56
+ const origins = [`http://127.0.0.1:${actualPort}`, `http://localhost:${actualPort}`];
57
+ if (!origins.some(value => new URL(value).host === request.headers.host) || request.headers['sec-fetch-site'] === 'cross-site') throw new Error('只允许本机访问。');
58
+ if (request.headers.origin && !origins.includes(request.headers.origin)) throw new Error('不接受其他网站发起的请求。');
59
+ if (write && request.headers['x-local-token'] !== token) throw new Error('页面会话已失效,请刷新后重试。');
60
+ };
61
+ const startTask = (kind, run) => {
62
+ if (busy) throw new Error('当前任务尚未结束,请稍后重试。');
63
+ busy = { kind, stage: '正在准备', startedAt: new Date().toISOString() };
64
+ activeTask = Promise.resolve().then(() => run(stage => { busy.stage = stage; })).catch(async error => {
65
+ event(kind, false, error.message); await save();
66
+ }).catch(error => { event(kind, false, `同步记录保存失败:${error.message}`); }).finally(() => { busy = null; activeTask = null; });
67
+ };
68
+ const server = http.createServer(async (request, response) => {
69
+ let ownsWrite = false;
70
+ try {
71
+ const path = new URL(request.url, 'http://localhost').pathname, write = !['GET', 'HEAD'].includes(request.method);
72
+ guard(request, write);
73
+ if (write) {
74
+ if (closing || busy || writing) return json(response, { error: '当前任务尚未结束,请稍后重试。' }, 409);
75
+ writing = true; ownsWrite = true;
76
+ }
77
+ if (path === '/' && request.method === 'GET') {
78
+ response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'SAMEORIGIN', 'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; frame-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'self'; frame-ancestors 'self'" });
79
+ response.end(await readFile(new URL('./local.html', import.meta.url))); return;
80
+ }
81
+ if (path === '/local/state' && request.method === 'GET') return json(response, await view());
82
+ if (path === '/local/preview' && request.method === 'GET') {
83
+ await loadCandidate();
84
+ const filename = resolve(state.candidate.releasePath, '../preview.html');
85
+ response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'SAMEORIGIN' });
86
+ createReadStream(filename).on('error', () => response.destroy()).pipe(response); return;
87
+ }
88
+ const uploadMatch = /^\/local\/upload\/([^/]+)$/.exec(path);
89
+ if (uploadMatch && request.method === 'POST') {
90
+ const id = uploadMatch[1]; if (!IDS.has(id)) throw new Error('未知板块。');
91
+ busy = { kind: 'upload', stage: '正在上传并校验', startedAt: new Date().toISOString() };
92
+ try {
93
+ const backendResponse = await fetchImpl(`${uploadURL.origin}/api/state`, { signal: AbortSignal.timeout(5000) });
94
+ const backend = await backendResponse.json();
95
+ if (backend.app?.id !== 'theater-command-board-admin' || resolve(backend.app?.dataDir || '') !== dataDir) throw new Error('本机上传后台的数据目录不匹配,请检查启动位置。');
96
+ const bytes = await readBody(request, uploadLimits.fileBytes, uploadSizeError);
97
+ const result = await fetchImpl(`${uploadURL.origin}/api/uploads/${id}`, { method: 'POST', headers: { 'Content-Type': 'application/octet-stream', 'X-Filename': request.headers['x-filename'] || '', 'X-Local-Token': backend.token }, body: bytes, signal: AbortSignal.timeout(180_000) });
98
+ const outcome = await result.json();
99
+ if (!result.ok) throw new Error([...new Set([outcome.error || outcome.message, ...(outcome.validation?.errors || [])].filter(Boolean))].join(';') || '上传校验失败。');
100
+ state.uploadAttempts[id] = { status: 'success', attemptAt: new Date().toISOString() }; event('upload', true, `${id} 上传校验成功`); await save();
101
+ return json(response, { ok: true });
102
+ } catch (error) {
103
+ state.uploadAttempts[id] = { status: 'failed', attemptAt: new Date().toISOString(), error: error.message }; event('upload', false, error.message); await save(); throw error;
104
+ } finally { busy = null; }
105
+ }
106
+ const body = write ? JSON.parse((await readBody(request)).toString() || '{}') : {};
107
+ if (path === '/local/config' && request.method === 'POST') {
108
+ const siteUrl = websiteOrigin(body.siteUrl);
109
+ const syncKey = body.syncKey || config.syncKey;
110
+ if (typeof syncKey !== 'string' || syncKey.length < 32) throw new Error('请填写网站同步凭据。');
111
+ config = { siteUrl, syncKey }; await atomicJson(configFile, config); return json(response, { ok: true });
112
+ }
113
+ if (path === '/local/bootstrap' && request.method === 'POST') {
114
+ await websiteRequest(config, '/api/bootstrap', { method: 'POST', body: { username: body.username, password: body.password }, fetchImpl });
115
+ event('account', true, '网站管理员已初始化'); await save(); return json(response, { ok: true });
116
+ }
117
+ if (path === '/local/prepare' && request.method === 'POST') {
118
+ startTask('prepare', async onStage => {
119
+ const outputDir = resolve(workDir, 'releases', randomUUID());
120
+ const prepared = await prepare({ dataDir, outputDir, previousRelease: state.approvedRelease || undefined, uploadAttempts: state.uploadAttempts, onStage });
121
+ onStage('正在生成本地验收看板');
122
+ const rendered = await render(prepared.payload);
123
+ await writeFile(resolve(outputDir, 'preview.html'), rendered.html, { flag: 'wx', mode: 0o600 });
124
+ candidate = prepared;
125
+ state.candidate = { revision: prepared.manifest.revision, generatedAt: prepared.manifest.generatedAt, modules: prepared.manifest.modules, scopes: prepared.manifest.scopes.length, releasePath: prepared.releasePath,
126
+ manifestSha256: createHash('sha256').update(JSON.stringify(prepared.manifest)).digest('hex') };
127
+ event('prepare', true, '本地候选已准备,可预览验收', prepared.manifest.revision); await save();
128
+ }); return json(response, { started: true }, 202);
129
+ }
130
+ if (path === '/local/sync' && request.method === 'POST') {
131
+ if (!config.siteUrl || !config.syncKey) throw new Error('请先配置网站地址和同步凭据。');
132
+ const release = await loadCandidate();
133
+ if (body.revision !== release.manifest.revision) throw new Error('验收版本已经变化,请重新查看后同步。');
134
+ state.approvedRelease = release.releasePath; await save();
135
+ startTask('sync', async onStage => {
136
+ const result = await synchronize({ release, config, onStage, fetchImpl });
137
+ state.published = result; event('sync', true, '网站已启用本次验收版本', result.revision); await save();
138
+ }); return json(response, { started: true }, 202);
139
+ }
140
+ return json(response, { error: '接口不存在。' }, 404);
141
+ } catch (error) { if (!response.headersSent) json(response, { error: error.message }, /只允许|会话|其他网站/.test(error.message) ? 403 : 400); else response.destroy(); }
142
+ finally { if (ownsWrite) writing = false; }
143
+ });
144
+ await new Promise((accept, reject) => { server.once('error', reject); server.listen(port, '127.0.0.1', accept); });
145
+ actualPort = server.address().port;
146
+ return { url: `http://127.0.0.1:${actualPort}`, close: async () => { closing = true; if (activeTask) await activeTask; await new Promise(resolveClose => server.close(resolveClose)); } };
147
+ }
@@ -0,0 +1,79 @@
1
+ {
2
+ "name": "dsh-data-dashboard",
3
+ "version": "0.1.4",
4
+ "builtAt": "2026-11-25T06:12:45.367Z",
5
+ "sourceCommit": "de16d0bc750c1652a44d80ef3e5978de0e9c235f",
6
+ "sourceDirty": true,
7
+ "files": {
8
+ "README.md": "ae7f24665cd16f9d729d719ef2335c328d14e0c8b791e40c5c39c8a61d8783d6",
9
+ "assets/theater-board.svg": "896b0573d86494e4c31b11bde56cecd517b509bd3bf940a24742ac565f164afc",
10
+ "backend/incremental/flow.mjs": "d4fc15a45380b548cfec74fb46025eaee0373d2faf3b7f4ad2db9d9a4486d100",
11
+ "backend/incremental/jobs.mjs": "3c706c735f5acd357f9578bc014fc4598024ba631c954d51a0f11ff06b8fd780",
12
+ "backend/incremental/xlsx-rows.mjs": "4d840c2401bb0e6157d36f3a0df4e7750bee3209ea6ddb40b70fd9d7cd4e2447",
13
+ "backend/job-worker.mjs": "a9cfa26a77d72926e8485f274a441ae2f919555aee31288776d4e0abc5de9c50",
14
+ "backend/modules.mjs": "0aee556332a186fb7a728858d4643a07da8570e4d155c57204996b01692ffe69",
15
+ "backend/modules/banquet/index.mjs": "66747cfdf75ceb16fc2d00c56b78e629d7b7aebe935e3c9415f1ce955b691fa9",
16
+ "backend/modules/inventory/index.mjs": "621937531da92a607f9a54b622f599aeff36cbd7c7814140f202c0e9cc2727f7",
17
+ "backend/modules/inventory/legacy-fields.mjs": "0de131399a9f5399bf7959ae57af8c52e5c8ab53170910bac3e4bdd21f3be057",
18
+ "backend/modules/invoice/index.mjs": "4d4f0bce05d3a0e385d5a301365d056bd7954427b5038c69393c77724cdd6473",
19
+ "backend/modules/movement/index.mjs": "9179dd5726cd698a521bfaaa6e1a1452912dc1b34ceb3b7395d8e8d75c802abb",
20
+ "backend/modules/opening/index.mjs": "e6f11fc58689848251511ac332cdc3ffc419d7907adcabd3b7440985bcf410fc",
21
+ "backend/modules/target/index.mjs": "d644e882b3b7476c6b8b8985f23aa714b15b0ac902a880137bbf951ac407ee6d",
22
+ "backend/modules/terminal/index.mjs": "cd65735c7dd277e7bc137e9d49c5e15f5b5d99da7c91e93480711351a6f016ea",
23
+ "backend/public/admin.css": "2a43416bed62c0c29b43125fd4151530a9b7370daf9d51187abc2d8f64f614e7",
24
+ "backend/public/admin.js": "acc62dbd69c179702cf925883967de88cbf4220fba3d218e702b72f676bab6e9",
25
+ "backend/public/board.css": "b6dbff8c6d2f21ee70ddb06d90504c8e583722d027567057dc86053ae2b390a4",
26
+ "backend/public/board.html": "b81c90c9d64f67894ca3b0cd295f7710fa08095c32b05e93928be2f77343d684",
27
+ "backend/public/board.js": "e5302d9fcb8784bef3581142314937674ac17778e6fd9b4844445a2db44dd018",
28
+ "backend/public/index.html": "5224461c906395cb7be2a8762c4ec42623fd77ded5bd907daf53686cec80e950",
29
+ "backend/public/review.css": "6fd7366dccd877335f0897577f8cb56a30a2232fe0e779bef84d75757b78b56f",
30
+ "backend/public/review.js": "cd6bd9ad50e458bc13d7a6b41c6c2ad800cf297a05279a7908b02518bc4ae53c",
31
+ "backend/real-data/generate-dashboard.mjs": "6ab0745248f0dddb45237a589c25c2d91459483b06980d79bd1c6c93e2ca7478",
32
+ "backend/real-data/inventory-history.mjs": "863345fc46ef2c66e1f5279823f408a7ee2b78a421574176c7221b79d44d5a50",
33
+ "backend/real-data/organization-mapping.mjs": "963414c4ee317e41a29064dc66a5b8a8241dbe6246d8ae76d930da8c2cbfd867",
34
+ "backend/real-data/source-payload.mjs": "f2f04697dac7ee7d62f5bb1f3304b552118ff8854c8dae7fb4e0575d4fdb3679",
35
+ "backend/real-data/terminal-components.mjs": "e7c7399e9459964d25cee0c0f7d72834e6480603d6c64b9f41c581319db9c12a",
36
+ "backend/real-data/terminal-structure.css": "17ca1107abff93b48e5d129a3943b01b2f6ff7113eeede589f51634861069e26",
37
+ "backend/real-data/terminal-structure.mjs": "a06b4f0eb91e0c2aea6c8f75ff898017787a4269d4e1630866fb31796ead462e",
38
+ "backend/real-data/v10-components.mjs": "a2ec25b59a6f2a7ada61081ac3de4dc63e09693d9c12eaa82bce1efed1cc65e0",
39
+ "backend/real-data/v10-details.css": "a0c12a87ea7fd2974051f0e7b6c00a6057fe8e60515abd6c53aa52b93e8cf924",
40
+ "backend/real-data/v10-details.mjs": "740c3246fbf5fbbd8ae806dc3e042f4a8d5ce9cea31553fe45a1ea77a6514195",
41
+ "backend/real-data/v10-layout.css": "2efc29f10d984a8629ef87aae1c72cbdc09658a3553407732c2359931a66cdbd",
42
+ "backend/real-data/v10-model.mjs": "19ce10b2a8d520bbcf14a496681a0f42b2bd38eb53f88634404e3fc26a8b2699",
43
+ "backend/real-data/v10-overview-data.mjs": "da365789e08cd089d7b10bb1236d2891ccf5d0bc4f9b9e91187e233264ec03f0",
44
+ "backend/real-data/v10-overview.css": "6c906cb737fd86be5278febd6449b97fbb02892dc2b0314dd1200930b4b341a7",
45
+ "backend/real-data/v10-overview.mjs": "b7dcad8691f7264fd76d6e6e193016c41bdf31c5d7cbd1fe434e1358a59c189b",
46
+ "backend/real-data/v10-presentation.mjs": "aadeffbb27499f6353eb52533d1eb2f87493d617da80ab8afeb851e97bdffe09",
47
+ "backend/real-data/v10-shell.html": "d5118e6e2ec447cc22992c348e18ae719bfbda959a2b694352843c120522a5f1",
48
+ "backend/real-data/v10-template.mjs": "62802e21574312eb27f0f7e1631170b5457dbf4f32b1e3e3e6b4fe9dc73f0fd0",
49
+ "backend/recognition/fingerprint.mjs": "652340bf7b1f1617c03d53e5c5724154ffabc262c0a522e498ba015671420528",
50
+ "backend/recognition/headers.mjs": "1cadc4fb39b8a1d7decddae666c827b00903b7f14cfd9e7f4974f2042f07fc02",
51
+ "backend/recognition/module-definition.mjs": "2aaea663fcc2a52c193637135ad762c7c2af35da96aa12d89742ab6606ed7801",
52
+ "backend/recognition/result.mjs": "4afe8df9046258424091e556de8337bf283837bd07a1c8c14f765bd11eaa98b5",
53
+ "backend/recognition/upload-limits.mjs": "8fde2d6c62ab7f0bfa1a945d34efc462087b895fd25e92cf5d5c34c97d738ace",
54
+ "backend/review-engine.mjs": "9c13e5684b4697f09b5bda808266095ae3acd40474124d4dd021ff067b547e1d",
55
+ "backend/review-service.mjs": "c9d4526b952e07c7c9a5d9c5ef9ccaf6bd108527057dd605e24107312d1bb02f",
56
+ "backend/server.mjs": "f9a1a61c69fa7658ca687f7f1b1d0d40cc639bc169131edf3b9d3c8bc621ac41",
57
+ "backend/store.mjs": "1e74edc99a577fa9a72a43722a35b6cee7c0c5582b49a5786bbc676412602f0b",
58
+ "backend/target-template.mjs": "fa33f13b8ee56da7a2bc44c1c474d879817e270bddad03350799143f7fe78b43",
59
+ "backend/validate-workbook.mjs": "2f86c034e4af578b7971486e81e86912f69a086c877c516223350b52931cc377",
60
+ "backend/web-sync/README.md": "100d23f98a118593072498ac5004cb393536d8e63e3ac2fa0aacb3d406822423",
61
+ "backend/web-sync/client.mjs": "08b8411d0594f20011c57789c56d61d0486ebd1a9d5db6e77087bfe67e4f22b3",
62
+ "backend/web-sync/exporter.mjs": "b74a1bef8f072242b12d8a683f6cf42744da925c478558c2c7306fd2ab282130",
63
+ "backend/web-sync/local.html": "baa1606eac3438fcbab366fd0336a210126ff0a924e5c369b529784a6ade2609",
64
+ "backend/web-sync/server.mjs": "2b0dd216db6cccf1f641e372394109654fea018780825a6a7bd52d126636043e",
65
+ "client.js": "3a3222a2b6573efdf1c6d472d3ece340fddf5db4c279c508ea24d82bb2b42511",
66
+ "cordis.patch.yml": "9c21f648e3a89752d07d2db65b1236330b8489b584ddfc63f98be9d9e3116133",
67
+ "index.js": "b851c33fb87bc02aa3c95d9c236a21865501fcda0576ffa568ae2eabdb73954e",
68
+ "lib/dist-manifest.mjs": "92ea95c04d108b62e9c513eb7330914a24fbc46b5a4a0869ee0fca1cfb7418fe",
69
+ "lib/market-index.mjs": "c016b827c730bdd8717a643ae1e8a1b32d845ac7b9f4f80914571acf34fbe21a",
70
+ "lib/package-audit.mjs": "fcddbf4e8a6eec68bf1c2cbd01a6569fcd6301b50677f367a08fc0476f44561b",
71
+ "lib/settings.mjs": "b05040be7d56020b33b1c7e4e8208830360a0935e191960d8e13038fce6f16e0",
72
+ "lib/tool-definitions.mjs": "a3fa67c261627e140025d200f624885510f8857bf77c3f219efc53cbc4ea1300",
73
+ "lib/tools.mjs": "78cf680319cc2e5868b01c76c55a369ee034e9a5be2dc6a3865462dd1ed2c172",
74
+ "locale/en.json": "e7a5b39324d6162e7d29957fbc7a0f4bde9c588de2000c874f058df5520f472c",
75
+ "locale/zh.json": "dd29dcecb35aa6e95a295af228fd39f833c1f492cc5ca41567bb6945ab134510",
76
+ "package-lock.json": "7ff8aebb33a076262532e4ab48e9b755b0efb2893d56f70d2f9d5b94659030c5",
77
+ "package.json": "95c4df01ce5aab9ea0c4d4ffa1168c9d27dad2f77076c46f5dd3b828e24d6a00"
78
+ }
79
+ }
package/client.js ADDED
@@ -0,0 +1,24 @@
1
+ // Browser face of the DSH plugin. Hand-written in the closure-factory format the
2
+ // DSH client module loader expects (window.__ModuleLoader__.load), so the
3
+ // package ships without a build step. Only React from the shared module table
4
+ // is used.
5
+ window.__ModuleLoader__.load({id:`dsh-data-dashboard`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});
6
+ const React=require("react");const h=React.createElement;
7
+ const PANEL_ID='dsh-data-dashboard.board';
8
+ const DEFAULT_PORT=4181;
9
+ const LOOPBACK=['127.0.0.1','localhost'];
10
+ function BoardIcon({size}){const s=size||20;return h('svg',{width:s,height:s,viewBox:'0 0 24 24',fill:'none',stroke:'currentColor',strokeWidth:1.8,strokeLinejoin:'round','aria-hidden':true},h('rect',{x:3.5,y:3.5,width:7,height:9,rx:1.5}),h('rect',{x:13.5,y:3.5,width:7,height:5,rx:1.5}),h('rect',{x:13.5,y:11.5,width:7,height:9,rx:1.5}),h('rect',{x:3.5,y:15.5,width:7,height:5,rx:1.5}))}
11
+ // DSH Web on loopback keeps its own hostname (same-site with the backend);
12
+ // the DSH desktop window (dsh-app://app) uses 127.0.0.1.
13
+ function boardUrl(port,where){const loc=where||location;if(LOOPBACK.includes(loc.hostname)&&(loc.protocol==='http:'||loc.protocol==='https:'))return`http://${loc.hostname}:${port}/`;if(loc.protocol==='dsh-app:'&&loc.hostname==='app')return`http://127.0.0.1:${port}/`;return null}
14
+ function makePage(readPort){return function TheaterBoardPage(){
15
+ const port=readPort();const src=boardUrl(port);
16
+ if(!src)return h('div',{style:{padding:32,lineHeight:1.7}},'战区看板只能在本机的 DeepSeek Harness 中使用(桌面版,或地址为 127.0.0.1 / localhost 的网页版)。');
17
+ return h('iframe',{src,title:'战区经营看板',style:{display:'block',width:'100%',height:'100%',border:0,background:'#fff'}})}}
18
+ const inject=['slots'];
19
+ function apply(ctx,config){
20
+ const readPort=()=>{try{const v=config&&config.port&&config.port.get();return Number.isInteger(v)?v:DEFAULT_PORT}catch{return DEFAULT_PORT}};
21
+ ctx.slots.inject('main',()=>ctx.slots.register({name:'main',key:PANEL_ID},makePage(readPort)));
22
+ ctx.slots.inject('sidebar.panellist',()=>ctx.slots.register({name:'sidebar.panellist',id:PANEL_ID,order:50,label:'战区看板'},BoardIcon));
23
+ }
24
+ exports.apply=apply;exports.inject=inject;exports.boardUrl=boardUrl;return module.exports}});
@@ -0,0 +1,3 @@
1
+ - insert:
2
+ - id: theater-board
3
+ name: dsh-data-dashboard