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.
- package/README.md +35 -2
- package/assets/theater-board.svg +1 -0
- package/backend/incremental/flow.mjs +492 -0
- package/backend/incremental/jobs.mjs +58 -0
- package/backend/incremental/xlsx-rows.mjs +145 -0
- package/backend/job-worker.mjs +22 -0
- package/backend/modules/banquet/index.mjs +46 -0
- package/backend/modules/inventory/index.mjs +45 -0
- package/backend/modules/inventory/legacy-fields.mjs +83 -0
- package/backend/modules/invoice/index.mjs +72 -0
- package/backend/modules/movement/index.mjs +68 -0
- package/backend/modules/opening/index.mjs +48 -0
- package/backend/modules/target/index.mjs +45 -0
- package/backend/modules/terminal/index.mjs +114 -0
- package/backend/modules.mjs +12 -0
- package/backend/public/admin.css +192 -0
- package/backend/public/admin.js +713 -0
- package/backend/public/board.css +43 -0
- package/backend/public/board.html +47 -0
- package/backend/public/board.js +96 -0
- package/backend/public/index.html +110 -0
- package/backend/public/review.css +5 -0
- package/backend/public/review.js +452 -0
- package/backend/real-data/generate-dashboard.mjs +135 -0
- package/backend/real-data/inventory-history.mjs +316 -0
- package/backend/real-data/organization-mapping.mjs +102 -0
- package/backend/real-data/source-payload.mjs +459 -0
- package/backend/real-data/terminal-components.mjs +280 -0
- package/backend/real-data/terminal-structure.css +105 -0
- package/backend/real-data/terminal-structure.mjs +276 -0
- package/backend/real-data/v10-components.mjs +112 -0
- package/backend/real-data/v10-details.css +18 -0
- package/backend/real-data/v10-details.mjs +251 -0
- package/backend/real-data/v10-layout.css +27 -0
- package/backend/real-data/v10-model.mjs +521 -0
- package/backend/real-data/v10-overview-data.mjs +248 -0
- package/backend/real-data/v10-overview.css +264 -0
- package/backend/real-data/v10-overview.mjs +263 -0
- package/backend/real-data/v10-presentation.mjs +342 -0
- package/backend/real-data/v10-shell.html +1097 -0
- package/backend/real-data/v10-template.mjs +351 -0
- package/backend/recognition/fingerprint.mjs +32 -0
- package/backend/recognition/headers.mjs +2 -0
- package/backend/recognition/module-definition.mjs +4 -0
- package/backend/recognition/result.mjs +29 -0
- package/backend/recognition/upload-limits.mjs +14 -0
- package/backend/review-engine.mjs +364 -0
- package/backend/review-service.mjs +182 -0
- package/backend/server.mjs +545 -0
- package/backend/store.mjs +68 -0
- package/backend/target-template.mjs +47 -0
- package/backend/validate-workbook.mjs +251 -0
- package/backend/web-sync/README.md +37 -0
- package/backend/web-sync/client.mjs +63 -0
- package/backend/web-sync/exporter.mjs +260 -0
- package/backend/web-sync/local.html +34 -0
- package/backend/web-sync/server.mjs +147 -0
- package/build-manifest.json +79 -0
- package/client.js +24 -0
- package/cordis.patch.yml +3 -0
- package/index.js +117 -0
- package/lib/dist-manifest.mjs +19 -0
- package/lib/market-index.mjs +56 -0
- package/lib/package-audit.mjs +34 -0
- package/lib/settings.mjs +71 -0
- package/lib/tool-definitions.mjs +56 -0
- package/lib/tools.mjs +255 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +71 -4
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { createReadStream, createWriteStream } from 'node:fs';
|
|
3
|
+
import { mkdir, readFile, readdir, rename, rm, stat, appendFile, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
|
+
import { Transform } from 'node:stream';
|
|
6
|
+
import { createHash, randomUUID, randomBytes } from 'node:crypto';
|
|
7
|
+
import { dirname, resolve } from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { Worker } from 'node:worker_threads';
|
|
10
|
+
import { moduleDefinitions } from './modules.mjs';
|
|
11
|
+
import { identifyWorkbook } from './validate-workbook.mjs';
|
|
12
|
+
import { validationFingerprint } from './recognition/fingerprint.mjs';
|
|
13
|
+
import { uploadLimits, uploadSizeError } from './recognition/upload-limits.mjs';
|
|
14
|
+
import { openStore, atomicJson } from './store.mjs';
|
|
15
|
+
import { captureSourceSnapshot, verifyGenerationSnapshot } from './real-data/generate-dashboard.mjs';
|
|
16
|
+
import { createReviewService, emptyReview } from './review-service.mjs';
|
|
17
|
+
import { buildTargetTemplate, targetOrganizations } from './target-template.mjs';
|
|
18
|
+
import { AGGREGATE_VERSION, isFlowModule, isUpdatable, isWholeModule, lineageShas, modesFor, receipt as flowReceipt, suggestMode } from './incremental/flow.mjs';
|
|
19
|
+
|
|
20
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
21
|
+
const project = resolve(here, '..');
|
|
22
|
+
export const DEFAULT_DATA_DIR = resolve(project, '../本机后台数据');
|
|
23
|
+
export const APP_ID = 'theater-command-board-admin';
|
|
24
|
+
const MAX_BYTES = uploadLimits.fileBytes;
|
|
25
|
+
const knownModules = new Set(moduleDefinitions.map(m => m.id));
|
|
26
|
+
// How often each board is expected to be refreshed. Only used for reminders.
|
|
27
|
+
const CYCLES = ['daily', 'weekly', 'monthly', 'irregular'];
|
|
28
|
+
export const DEFAULT_CYCLES = { invoice: 'daily', movement: 'daily', opening: 'daily', terminal: 'weekly', inventory: 'monthly', banquet: 'irregular', target: 'monthly' };
|
|
29
|
+
const publicFiles = new Map([['/', ['board.html', 'text/html; charset=utf-8']], ['/board', ['board.html', 'text/html; charset=utf-8']], ['/admin', ['index.html', 'text/html; charset=utf-8']], ['/board.js', ['board.js', 'text/javascript; charset=utf-8']], ['/board.css', ['board.css', 'text/css; charset=utf-8']], ['/admin.js', ['admin.js', 'text/javascript; charset=utf-8']], ['/admin.css', ['admin.css', 'text/css; charset=utf-8']]]);
|
|
30
|
+
for (const [file, type] of [['review.js', 'text/javascript'], ['review.css', 'text/css']]) publicFiles.set(`/${file}`, [file, `${type}; charset=utf-8`]);
|
|
31
|
+
|
|
32
|
+
class RequestError extends Error {
|
|
33
|
+
constructor(status, message, extra = {}) { super(message); this.status = status; this.extra = extra; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function workerJob(data, onStage, log) {
|
|
37
|
+
return new Promise((resolveJob, reject) => {
|
|
38
|
+
const worker = new Worker(new URL('./job-worker.mjs', import.meta.url), { workerData: data, resourceLimits: { maxOldGenerationSizeMb: data.kind === 'upload' ? 512 : 1536 } });
|
|
39
|
+
let done = false;
|
|
40
|
+
const finish = (error, result) => {
|
|
41
|
+
if (done) return;
|
|
42
|
+
done = true;
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
worker.terminate().catch(() => {});
|
|
45
|
+
if (error) reject(error); else resolveJob(result);
|
|
46
|
+
};
|
|
47
|
+
const timeout = ['generate', 'compose', 'analyze', 'aggregate', 'coverage'].includes(data.kind) ? 300_000 : 120_000;
|
|
48
|
+
const timer = setTimeout(() => finish(new Error(`处理超过${timeout === 300_000 ? '五' : '两'}分钟,请检查文件大小或内容后重试。`)), timeout);
|
|
49
|
+
worker.on('message', message => {
|
|
50
|
+
if (message.stage) onStage(message.stage);
|
|
51
|
+
else if (message.error) { log(message.detail); finish(new Error(message.error)); }
|
|
52
|
+
else if ('result' in message) finish(null, message.result);
|
|
53
|
+
});
|
|
54
|
+
worker.on('error', error => { log(error.stack); finish(new Error('处理进程未能完成,请检查文件是否过大或损坏。')); });
|
|
55
|
+
worker.on('exit', () => { if (!done) finish(new Error('处理进程意外退出,请重试。')); });
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function filenameFrom(request) {
|
|
60
|
+
let name;
|
|
61
|
+
try { name = decodeURIComponent(request.headers['x-filename'] || ''); }
|
|
62
|
+
catch { throw new RequestError(400, '文件名编码无效。'); }
|
|
63
|
+
if (!name || name.length > 200 || /[\x00-\x1f\x7f/\\]/.test(name) || !/\.xlsx$/i.test(name)) throw new RequestError(400, '请选择名称有效的 .xlsx 文件。暂不支持 .xls、宏或加密工作簿。');
|
|
64
|
+
return name;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function receiveFile(request, file) {
|
|
68
|
+
if (Number(request.headers['content-length']) > MAX_BYTES) throw new RequestError(413, uploadSizeError(Number(request.headers['content-length'])));
|
|
69
|
+
let bytes = 0;
|
|
70
|
+
const hash = createHash('sha256');
|
|
71
|
+
const counter = new Transform({ transform(chunk, encoding, callback) {
|
|
72
|
+
bytes += chunk.length;
|
|
73
|
+
if (bytes > MAX_BYTES) callback(new RequestError(413, uploadSizeError(bytes)));
|
|
74
|
+
else { hash.update(chunk); callback(null, chunk); }
|
|
75
|
+
} });
|
|
76
|
+
await pipeline(request, counter, createWriteStream(file, { flags: 'wx', mode: 0o600 }));
|
|
77
|
+
if (!bytes) throw new RequestError(400, '文件为空,请重新选择。');
|
|
78
|
+
return { bytes, sha256: hash.digest('hex') };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function readJson(request, maxBytes = 8 * 1048576) {
|
|
82
|
+
const chunks = []; let size = 0;
|
|
83
|
+
for await (const chunk of request) {
|
|
84
|
+
size += chunk.length;
|
|
85
|
+
if (size > maxBytes) throw new RequestError(413, '请求内容过大。');
|
|
86
|
+
chunks.push(chunk);
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
const value = size ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {};
|
|
90
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error();
|
|
91
|
+
return value;
|
|
92
|
+
} catch { throw new RequestError(400, '请求必须是有效的 JSON 对象。'); }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Extra page origins allowed to embed this backend (DSH plugin mode only):
|
|
97
|
+
* loopback http(s) origins (DSH Web) and exactly `dsh-app://app` (the DSH
|
|
98
|
+
* desktop window). The default (none) keeps same-origin framing for source and
|
|
99
|
+
* desktop launches.
|
|
100
|
+
*/
|
|
101
|
+
const LOOPBACK_ORIGIN = /^https?:\/\/(127\.0\.0\.1|localhost)(:\d{1,5})?$/;
|
|
102
|
+
export const DSH_DESKTOP_ORIGIN = 'dsh-app://app';
|
|
103
|
+
const embedOrigin = origin => typeof origin === 'string' && (LOOPBACK_ORIGIN.test(origin) || origin === DSH_DESKTOP_ORIGIN);
|
|
104
|
+
export function frameAncestorList(extra = []) {
|
|
105
|
+
const origins = typeof extra === 'function' ? extra() : extra;
|
|
106
|
+
return ["'self'", ...new Set((origins || []).filter(embedOrigin))];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function createAdminServer({ port = 4180, dataDir = DEFAULT_DATA_DIR, frameAncestors = [] } = {}) {
|
|
110
|
+
dataDir = resolve(dataDir);
|
|
111
|
+
const embedded = typeof frameAncestors === 'function' || frameAncestors.length > 0;
|
|
112
|
+
for (const origin of typeof frameAncestors === 'function' ? [] : frameAncestors) if (!embedOrigin(origin)) throw new Error(`嵌入来源只能是本机回环地址或 ${DSH_DESKTOP_ORIGIN}:${origin}`);
|
|
113
|
+
const ancestors = () => frameAncestorList(frameAncestors).join(' ');
|
|
114
|
+
const store = await openStore(dataDir);
|
|
115
|
+
const token = randomBytes(32).toString('hex');
|
|
116
|
+
let busy = null;
|
|
117
|
+
let closing = false;
|
|
118
|
+
const pending = new Set();
|
|
119
|
+
let actualPort;
|
|
120
|
+
const log = detail => { appendFile(resolve(dataDir, 'logs/backend.log'), `${new Date().toISOString()} ${detail}\n`, { mode: 0o600 }).catch(() => {}); };
|
|
121
|
+
const track = promise => { pending.add(promise); promise.finally(() => pending.delete(promise)).catch(() => {}); return promise; };
|
|
122
|
+
// Files received for review but never submitted do not survive a restart.
|
|
123
|
+
for (const entry of await readdir(resolve(dataDir, 'temp')).catch(() => [])) if (/^(staged-|composed-)/.test(entry)) await rm(resolve(dataDir, 'temp', entry), { recursive: true, force: true }).catch(() => {});
|
|
124
|
+
const review = createReviewService({ store, dataDir, scan: data => workerJob({ kind: 'inspect', ...data }, () => {}, log) });
|
|
125
|
+
// Data start/end for uploads saved before coverage was recorded (§11.5). Cached
|
|
126
|
+
// beside each upload; the upload records in state.json are not rewritten.
|
|
127
|
+
const coverageCache = new Map();
|
|
128
|
+
const COVERAGE_MODULES = new Set(['invoice', 'movement', 'opening', 'terminal', 'inventory']);
|
|
129
|
+
const withCoverage = upload => !upload || upload.coverage?.start || !coverageCache.has(upload.id) ? upload : { ...upload, coverage: coverageCache.get(upload.id), coverageComputed: true };
|
|
130
|
+
let coverageRun = null;
|
|
131
|
+
async function fillCoverage() {
|
|
132
|
+
const ids = new Set([...Object.values(store.state.active || {}), ...Object.values(store.state.candidates || {})]);
|
|
133
|
+
for (const upload of store.state.uploads) {
|
|
134
|
+
if (closing) return;
|
|
135
|
+
if (!ids.has(upload.id) || upload.coverage?.start || coverageCache.has(upload.id) || !COVERAGE_MODULES.has(upload.moduleId)) continue;
|
|
136
|
+
const directory = resolve(dataDir, 'uploads', upload.id);
|
|
137
|
+
try {
|
|
138
|
+
const cached = JSON.parse(await readFile(resolve(directory, 'coverage.json'), 'utf8'));
|
|
139
|
+
if (cached.sha256 === upload.sha256) { coverageCache.set(upload.id, { start: cached.start, end: cached.end }); continue; }
|
|
140
|
+
} catch {}
|
|
141
|
+
try {
|
|
142
|
+
const aggregate = JSON.parse(await readFile(resolve(directory, 'aggregate.json'), 'utf8'));
|
|
143
|
+
if (aggregate.sha256 === upload.sha256 && aggregate.aggregate?.start) { coverageCache.set(upload.id, { start: aggregate.aggregate.start, end: aggregate.aggregate.end }); continue; }
|
|
144
|
+
} catch {}
|
|
145
|
+
try {
|
|
146
|
+
const result = await workerJob({ kind: 'coverage', file: resolve(directory, 'source.xlsx'), validation: upload.validation, moduleId: upload.moduleId }, () => {}, log);
|
|
147
|
+
coverageCache.set(upload.id, { start: result.start, end: result.end });
|
|
148
|
+
await atomicJson(resolve(directory, 'coverage.json'), { sha256: upload.sha256, start: result.start, end: result.end }).catch(log);
|
|
149
|
+
} catch (error) { log(error.stack); coverageCache.set(upload.id, { start: null, end: null }); }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const refreshCoverage = () => { if (coverageRun || closing) return; coverageRun = track(fillCoverage().catch(log).finally(() => { coverageRun = null; })); };
|
|
153
|
+
function view() {
|
|
154
|
+
return {
|
|
155
|
+
app: { id: APP_ID, name: '战区看板后台', version: '0.3.0', mode: 'real', dataDir },
|
|
156
|
+
token,
|
|
157
|
+
uploadLimits,
|
|
158
|
+
modules: moduleDefinitions.map(m => ({ ...m, flow: isFlowModule(m.id), updatable: isUpdatable(m.id), modes: modesFor(m.id), activeUpload: withCoverage(store.state.uploads.find(u => u.id === store.state.active[m.id])) || null,
|
|
159
|
+
candidateUpload: withCoverage(store.state.uploads.find(u => u.id === store.state.candidates?.[m.id])) || null,
|
|
160
|
+
reviewStatus: store.state.uploads.find(u => u.id === (store.state.candidates?.[m.id] || store.state.active[m.id]))?.reviewStatus ?? 'unchecked' })),
|
|
161
|
+
reviewRevision: store.state.review?.revision ?? 0,
|
|
162
|
+
uploads: [...store.state.uploads].reverse().map(withCoverage),
|
|
163
|
+
generations: [...store.state.generations].reverse().map(job => ({ ...job, ...(job.status === 'completed' ? { viewUrl: `/api/generations/${job.id}/view`, downloadUrl: `/api/generations/${job.id}/download` } : {}) })),
|
|
164
|
+
busy,
|
|
165
|
+
settings: { cycles: { ...DEFAULT_CYCLES, ...(store.state.settings?.cycles || {}) } },
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function guard(request, write = false) {
|
|
169
|
+
const hosts = [`127.0.0.1:${actualPort}`, `localhost:${actualPort}`];
|
|
170
|
+
if (!hosts.includes(request.headers.host)) throw new RequestError(403, '仅支持通过本机地址访问。');
|
|
171
|
+
if (request.headers.origin && !hosts.map(host => `http://${host}`).includes(request.headers.origin)) throw new RequestError(403, '不接受其他网页发起的请求。');
|
|
172
|
+
// Plugin mode: the DSH desktop window (dsh-app://app) is another site, so the
|
|
173
|
+
// iframe's top-level page load arrives cross-site. Only that read-only GET
|
|
174
|
+
// navigation of an HTML page into a frame is admitted; rendering is still limited by CSP
|
|
175
|
+
// frame-ancestors, and every fetch/write from the page is same-origin.
|
|
176
|
+
const pagePath = new URL(request.url, 'http://127.0.0.1').pathname;
|
|
177
|
+
const framePage = ['/', '/board', '/admin'].includes(pagePath) || /^\/api\/generations\/[a-f0-9-]{36}\/view$/.test(pagePath);
|
|
178
|
+
const frameNavigation = embedded && !write && framePage && request.headers['sec-fetch-mode'] === 'navigate' && request.headers['sec-fetch-dest'] === 'iframe';
|
|
179
|
+
if (request.headers['sec-fetch-site'] === 'cross-site' && !frameNavigation) throw new RequestError(403, '不接受跨站请求。');
|
|
180
|
+
if (write && request.headers['x-local-token'] !== token) throw new RequestError(403, '页面会话已失效,请刷新后台后重试。');
|
|
181
|
+
if (write && closing) throw new RequestError(503, '后台正在关闭,请稍后重新打开。');
|
|
182
|
+
}
|
|
183
|
+
function json(response, status, value) {
|
|
184
|
+
response.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
185
|
+
response.end(JSON.stringify(value));
|
|
186
|
+
}
|
|
187
|
+
function reserve(kind, moduleId) {
|
|
188
|
+
if (busy) throw new RequestError(409, '另一项上传或生成正在进行,请等待完成后再试。');
|
|
189
|
+
busy = { kind, ...(moduleId ? { moduleId } : {}), stage: kind === 'upload' ? '正在接收文件' : '正在锁定最新有效上传版本' };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const selectedUpload = (state, moduleId) => state.uploads.find(u => u.id === (state.candidates?.[moduleId] || state.active[moduleId]) && u.moduleId === moduleId) ?? null;
|
|
193
|
+
|
|
194
|
+
/** Validate, inspect and install a received workbook as the module's newest source. */
|
|
195
|
+
async function install({ moduleId, filename, temp, info, extra = {} }) {
|
|
196
|
+
const id = randomUUID();
|
|
197
|
+
let installed = false;
|
|
198
|
+
try {
|
|
199
|
+
const validationContract = await validationFingerprint(moduleId);
|
|
200
|
+
const current = selectedUpload(store.state, moduleId);
|
|
201
|
+
// Exact current bytes are idempotent; older versions may be chosen again as a fresh upload.
|
|
202
|
+
if (current?.sha256 === info.sha256 && current.validationContract === validationContract) return { record: current, duplicate: true };
|
|
203
|
+
busy.stage = '正在核对工作表、表头和数据行';
|
|
204
|
+
let validation;
|
|
205
|
+
try { validation = await workerJob({ kind: 'upload', file: temp, moduleId }, () => {}, log); }
|
|
206
|
+
catch (error) { throw new RequestError(422, error.message); }
|
|
207
|
+
if (!validation.ok) throw new RequestError(422, '文件结构校验未通过,原有效资料已保留。', { validation });
|
|
208
|
+
const checkedContract = await validationFingerprint(moduleId);
|
|
209
|
+
if (checkedContract !== validationContract) throw new RequestError(409, '校验期间规则发生修改,请重新上传。');
|
|
210
|
+
busy.stage = '正在检查重复候选和来源组织';
|
|
211
|
+
const inspection = await workerJob({ kind: 'inspect', file: temp, moduleId, sha256: info.sha256, validation }, () => {}, log);
|
|
212
|
+
const directory = resolve(dataDir, 'uploads', id);
|
|
213
|
+
await mkdir(directory, { mode: 0o700 });
|
|
214
|
+
await rename(temp, resolve(directory, 'source.xlsx'));
|
|
215
|
+
const record = { id, moduleId, filename, ...info, uploadedAt: new Date().toISOString(), validation, validationContract, coverage: inspection.coverage ?? null, ...extra };
|
|
216
|
+
await atomicJson(resolve(directory, 'metadata.json'), record);
|
|
217
|
+
await review.saveInspection(record, inspection);
|
|
218
|
+
await store.update(async next => {
|
|
219
|
+
next.uploads.push(record); next.candidates ??= {}; next.candidates[moduleId] = id;
|
|
220
|
+
next.review ??= emptyReview(); next.review.revision++;
|
|
221
|
+
await review.promote(next);
|
|
222
|
+
});
|
|
223
|
+
installed = true;
|
|
224
|
+
refreshCoverage();
|
|
225
|
+
return { record, duplicate: false };
|
|
226
|
+
} finally {
|
|
227
|
+
if (!installed) await rm(resolve(dataDir, 'uploads', id), { recursive: true, force: true }).catch(log);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function upload(request, response, moduleId) {
|
|
232
|
+
if (!knownModules.has(moduleId)) throw new RequestError(404, '没有这个资料入口。');
|
|
233
|
+
const filename = filenameFrom(request);
|
|
234
|
+
if (request.headers['content-type'] !== 'application/octet-stream') throw new RequestError(415, '上传格式无效,请从后台选择文件。');
|
|
235
|
+
reserve('upload', moduleId);
|
|
236
|
+
const temp = resolve(dataDir, 'temp', `upload-${randomUUID()}.xlsx`);
|
|
237
|
+
try {
|
|
238
|
+
const info = await receiveFile(request, temp);
|
|
239
|
+
const { record, duplicate } = await install({ moduleId, filename, temp, info, extra: isUpdatable(moduleId) ? { composition: { mode: 'full', step: 0, appliedAt: new Date().toISOString() } } : {} });
|
|
240
|
+
busy = null;
|
|
241
|
+
json(response, duplicate ? 200 : 201, { upload: record, ...(duplicate ? { duplicate: true } : {}), state: view() });
|
|
242
|
+
} finally {
|
|
243
|
+
busy = null;
|
|
244
|
+
await rm(temp, { force: true }).catch(log);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// ---- Incremental / range / full updates for invoice, movement and opening ----
|
|
249
|
+
const stagedDir = id => {
|
|
250
|
+
if (typeof id !== 'string' || !/^[a-f0-9-]{36}$/.test(id)) throw new RequestError(400, '待提交文件标识无效。');
|
|
251
|
+
return resolve(dataDir, 'temp', `staged-${id}`);
|
|
252
|
+
};
|
|
253
|
+
async function readStaged(id) {
|
|
254
|
+
try { return JSON.parse(await readFile(resolve(stagedDir(id), 'meta.json'), 'utf8')); }
|
|
255
|
+
catch (error) { if (error instanceof RequestError) throw error; throw new RequestError(410, '待提交文件已过期,请重新选择文件。'); }
|
|
256
|
+
}
|
|
257
|
+
async function baseAggregate(upload) {
|
|
258
|
+
if (!upload) return null;
|
|
259
|
+
const file = resolve(dataDir, 'uploads', upload.id, 'aggregate.json');
|
|
260
|
+
try {
|
|
261
|
+
const cached = JSON.parse(await readFile(file, 'utf8'));
|
|
262
|
+
if (cached.version === AGGREGATE_VERSION && cached.sha256 === upload.sha256) return cached.aggregate;
|
|
263
|
+
} catch {}
|
|
264
|
+
return null;
|
|
265
|
+
}
|
|
266
|
+
function alreadyApplied(state, moduleId, sha256) {
|
|
267
|
+
const current = selectedUpload(state, moduleId);
|
|
268
|
+
if (!current) return false;
|
|
269
|
+
if (current.sha256 === sha256 || lineageShas(state, current.id).includes(sha256)) return true;
|
|
270
|
+
for (let item = current, guard = 0; item && guard < 5000; guard++) {
|
|
271
|
+
if (item.composition?.partSha256 === sha256) return true;
|
|
272
|
+
item = state.uploads.find(upload => upload.id === item.composition?.baseUploadId);
|
|
273
|
+
}
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
const baseSummary = upload => upload ? { uploadId: upload.id, filename: upload.filename, coverage: withCoverage(upload).coverage ?? null, step: upload.composition?.step ?? 0 } : null;
|
|
277
|
+
|
|
278
|
+
async function analyzeUpdate(request, response) {
|
|
279
|
+
const moduleId = String(request.headers['x-module-id'] || '');
|
|
280
|
+
if (!isUpdatable(moduleId)) throw new RequestError(400, '经营目标暂不支持核对更新,请按原方式整份上传。');
|
|
281
|
+
const filename = filenameFrom(request);
|
|
282
|
+
if (request.headers['content-type'] !== 'application/octet-stream') throw new RequestError(415, '上传格式无效,请从后台选择文件。');
|
|
283
|
+
reserve('upload', moduleId); busy.stage = '正在读取文件日期';
|
|
284
|
+
const id = randomUUID(), directory = resolve(dataDir, 'temp', `staged-${id}`);
|
|
285
|
+
let kept = false;
|
|
286
|
+
try {
|
|
287
|
+
await mkdir(directory, { mode: 0o700 });
|
|
288
|
+
const file = resolve(directory, 'source.xlsx');
|
|
289
|
+
const info = await receiveFile(request, file);
|
|
290
|
+
if (alreadyApplied(store.state, moduleId, info.sha256)) { busy = null; return json(response, 200, { duplicate: true, moduleId, filename, message: '这份文件已经处理过,不会重复计入。' }); }
|
|
291
|
+
let validation;
|
|
292
|
+
try { validation = await workerJob({ kind: 'upload', file, moduleId }, () => {}, log); }
|
|
293
|
+
catch (error) { throw new RequestError(422, error.message); }
|
|
294
|
+
if (!validation.ok) throw new RequestError(422, '文件结构校验未通过,原有效资料已保留。', { validation });
|
|
295
|
+
const base = selectedUpload(store.state, moduleId);
|
|
296
|
+
const cached = isFlowModule(moduleId) ? await baseAggregate(base) : null;
|
|
297
|
+
busy.stage = '正在对比现有数据';
|
|
298
|
+
const analysis = await workerJob({ kind: 'analyze', moduleId, partFile: file, partValidation: validation,
|
|
299
|
+
baseFile: base ? resolve(dataDir, 'uploads', base.id, 'source.xlsx') : null, baseValidation: base?.validation, baseAggregate: cached }, () => {}, log);
|
|
300
|
+
if (base && !cached && analysis.base && isFlowModule(moduleId)) await atomicJson(resolve(dataDir, 'uploads', base.id, 'aggregate.json'), { version: AGGREGATE_VERSION, sha256: base.sha256, aggregate: analysis.base }).catch(log);
|
|
301
|
+
const suggestion = suggestMode(analysis.base, analysis.part);
|
|
302
|
+
const meta = { id, moduleId, filename, ...info, validation, createdAt: new Date().toISOString(), baseUploadId: base?.id ?? null, base: analysis.base, part: analysis.part, existingByDate: analysis.existingByDate, suggestion };
|
|
303
|
+
await atomicJson(resolve(directory, 'meta.json'), meta);
|
|
304
|
+
kept = true;
|
|
305
|
+
busy = null;
|
|
306
|
+
const preview = flowReceipt({ moduleId, base: analysis.base, part: analysis.part, mode: suggestion.mode, start: suggestion.start, end: suggestion.end, existingByDate: analysis.existingByDate });
|
|
307
|
+
json(response, 200, { stagedId: id, moduleId, filename, file: { rows: analysis.part.rows, start: analysis.part.start, end: analysis.part.end }, base: baseSummary(base), suggestion, receipt: preview });
|
|
308
|
+
} finally {
|
|
309
|
+
busy = null;
|
|
310
|
+
if (!kept) await rm(directory, { recursive: true, force: true }).catch(log);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function updateOptions(body) {
|
|
315
|
+
if (!['incremental', 'range', 'full'].includes(body.mode)) throw new RequestError(400, '更新方式无效。');
|
|
316
|
+
return { mode: body.mode, start: typeof body.start === 'string' ? body.start : null, end: typeof body.end === 'string' ? body.end : null, confirmMissing: body.confirmMissing === true };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function previewUpdate(body) {
|
|
320
|
+
const meta = await readStaged(body.stagedId), options = updateOptions(body);
|
|
321
|
+
if (!modesFor(meta.moduleId).includes(options.mode)) throw new RequestError(400, '这个板块只支持整份替换。');
|
|
322
|
+
return flowReceipt({ moduleId: meta.moduleId, base: meta.base, part: meta.part, mode: options.mode, start: options.start, end: options.end, existingByDate: meta.existingByDate });
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async function applyUpdate(body, response) {
|
|
326
|
+
const meta = await readStaged(body.stagedId), options = updateOptions(body);
|
|
327
|
+
reserve('upload', meta.moduleId); busy.stage = '正在核对更新内容';
|
|
328
|
+
const directory = stagedDir(meta.id);
|
|
329
|
+
const composedFile = resolve(dataDir, 'temp', `composed-${meta.id}.xlsx`);
|
|
330
|
+
try {
|
|
331
|
+
const base = selectedUpload(store.state, meta.moduleId);
|
|
332
|
+
if ((base?.id ?? null) !== meta.baseUploadId) throw new RequestError(409, '这个板块的当前资料已经变化,请重新选择文件核对。');
|
|
333
|
+
if (!modesFor(meta.moduleId).includes(options.mode)) throw new RequestError(400, '这个板块只支持整份替换。');
|
|
334
|
+
const partFile = resolve(directory, 'source.xlsx');
|
|
335
|
+
let checked = flowReceipt({ moduleId: meta.moduleId, base: meta.base, part: meta.part, mode: options.mode, start: options.start, end: options.end, existingByDate: meta.existingByDate });
|
|
336
|
+
const refuse = result => {
|
|
337
|
+
if (result.blocked.length) throw new RequestError(422, result.blocked.join(' '), { receipt: result });
|
|
338
|
+
if (result.requiresConfirmation && !options.confirmMissing) throw new RequestError(422, isWholeModule(meta.moduleId) ? '有当前协议在新文件里找不到,请先核对并勾选确认。' : '有组织在新文件里缺失,请先核对并勾选确认。', { receipt: result });
|
|
339
|
+
};
|
|
340
|
+
refuse(checked);
|
|
341
|
+
if (options.mode === 'full' || !base) {
|
|
342
|
+
// Check again from the files themselves (the range / incremental path rechecks while composing).
|
|
343
|
+
busy.stage = '正在重新核对文件';
|
|
344
|
+
const cached = isFlowModule(meta.moduleId) ? await baseAggregate(base) : null;
|
|
345
|
+
const fresh = await workerJob({ kind: 'analyze', moduleId: meta.moduleId, partFile, partValidation: meta.validation,
|
|
346
|
+
baseFile: base ? resolve(dataDir, 'uploads', base.id, 'source.xlsx') : null, baseValidation: base?.validation, baseAggregate: cached }, () => {}, log);
|
|
347
|
+
checked = flowReceipt({ moduleId: meta.moduleId, base: fresh.base, part: fresh.part, mode: options.mode, start: options.start, end: options.end, existingByDate: fresh.existingByDate });
|
|
348
|
+
refuse(checked);
|
|
349
|
+
}
|
|
350
|
+
const appliedAt = new Date().toISOString();
|
|
351
|
+
const partId = randomUUID();
|
|
352
|
+
const partRecord = { id: partId, moduleId: meta.moduleId, filename: meta.filename, sha256: meta.sha256, bytes: meta.bytes, rows: meta.part.rows, start: meta.part.start, end: meta.part.end, mode: options.mode, rangeStart: checked.start, rangeEnd: checked.end, receivedAt: meta.createdAt, appliedAt };
|
|
353
|
+
let result, warnings = checked.warnings;
|
|
354
|
+
if (options.mode === 'full' || !base) {
|
|
355
|
+
result = await install({ moduleId: meta.moduleId, filename: meta.filename, temp: partFile, info: { bytes: meta.bytes, sha256: meta.sha256 },
|
|
356
|
+
extra: { composition: { mode: 'full', step: 0, partId, partSha256: meta.sha256, partFilename: meta.filename, partRows: meta.part.rows, appliedAt } } });
|
|
357
|
+
} else {
|
|
358
|
+
busy.stage = '正在合并为新版本';
|
|
359
|
+
let composed;
|
|
360
|
+
try {
|
|
361
|
+
composed = await workerJob({ kind: 'compose', moduleId: meta.moduleId, mode: options.mode, start: checked.start, end: checked.end, confirmMissing: options.confirmMissing,
|
|
362
|
+
baseFile: resolve(dataDir, 'uploads', base.id, 'source.xlsx'), baseValidation: base.validation, partFile, partValidation: meta.validation, outFile: composedFile }, () => {}, log);
|
|
363
|
+
} catch (error) { throw new RequestError(422, error.message || '合并前复核未通过,当前资料保持不变。'); }
|
|
364
|
+
warnings = composed.warnings;
|
|
365
|
+
const bytes = await readFile(composedFile);
|
|
366
|
+
const info = { bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
|
367
|
+
// Keep the received file for tracing before the composed source becomes current.
|
|
368
|
+
const partDirectory = resolve(dataDir, 'parts', partId);
|
|
369
|
+
await mkdir(partDirectory, { mode: 0o700 });
|
|
370
|
+
await writeFile(resolve(partDirectory, 'source.xlsx'), await readFile(partFile), { flag: 'wx', mode: 0o600 });
|
|
371
|
+
await atomicJson(resolve(partDirectory, 'metadata.json'), partRecord);
|
|
372
|
+
result = await install({ moduleId: meta.moduleId, filename: meta.filename, temp: composedFile, info,
|
|
373
|
+
extra: { composition: { mode: options.mode, start: checked.start, end: checked.end, step: (base.composition?.step ?? 0) + 1, baseUploadId: base.id, baseSha256: base.sha256,
|
|
374
|
+
partId, partSha256: meta.sha256, partFilename: meta.filename, partRows: meta.part.rows, kept: composed.kept, appended: composed.appended, appliedAt } } });
|
|
375
|
+
}
|
|
376
|
+
busy = null;
|
|
377
|
+
await rm(directory, { recursive: true, force: true }).catch(log);
|
|
378
|
+
json(response, result.duplicate ? 200 : 201, { upload: result.record, duplicate: result.duplicate, receipt: checked, warnings, state: view() });
|
|
379
|
+
} finally {
|
|
380
|
+
busy = null;
|
|
381
|
+
await rm(composedFile, { force: true }).catch(log);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function generate(job) {
|
|
386
|
+
const scratch = resolve(dataDir, 'temp', `generation-${job.id}`);
|
|
387
|
+
const directory = resolve(dataDir, 'generations', job.id);
|
|
388
|
+
let published = false;
|
|
389
|
+
try {
|
|
390
|
+
await mkdir(scratch, { mode: 0o700 });
|
|
391
|
+
const result = await workerJob({ kind: 'generate', project, dataDir, sourceVersions: job.sourceVersions, selection: job.selection, allowPending: job.allowPending, outputDir: scratch }, stage => {
|
|
392
|
+
if (busy) busy.stage = stage;
|
|
393
|
+
store.update(next => { const record = next.generations.find(g => g.id === job.id); record.stage = stage; }).catch(log);
|
|
394
|
+
}, log);
|
|
395
|
+
await verifyGenerationSnapshot({ project, dataDir, sourceVersions: job.sourceVersions, selection: job.selection, codeSha256: result.codeSha256, decisionsSha256: result.decisionsSha256, reviewSha256: result.reviewSha256 });
|
|
396
|
+
const completed = { ...job, ...result, status: 'completed', stage: '生成完成', finishedAt: new Date().toISOString(), mode: 'real' };
|
|
397
|
+
if (completed.needsReview) completed.filename = completed.filename.replace('_真实数据_', '_待确认_');
|
|
398
|
+
await atomicJson(resolve(scratch, 'manifest.json'), { ...completed, note: '使用点击生成时最新校验通过的上传版本计算;待确认指标保持不可用。历史成品与原始上传未改写。' });
|
|
399
|
+
await rename(scratch, directory);
|
|
400
|
+
published = true;
|
|
401
|
+
await store.update(next => { Object.assign(next.generations.find(g => g.id === job.id), completed); });
|
|
402
|
+
} catch (error) {
|
|
403
|
+
log(error.stack);
|
|
404
|
+
if (published) await rm(directory, { recursive: true, force: true }).catch(log);
|
|
405
|
+
await store.update(next => { Object.assign(next.generations.find(g => g.id === job.id), { status: 'failed', stage: '生成失败', finishedAt: new Date().toISOString(), error: error.message || '生成未完成,请重试。' }); });
|
|
406
|
+
} finally {
|
|
407
|
+
await rm(scratch, { recursive: true, force: true }).catch(log);
|
|
408
|
+
busy = null;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
async function route(request, response) {
|
|
413
|
+
response.setHeader('Cache-Control', 'no-store');
|
|
414
|
+
response.setHeader('X-Content-Type-Options', 'nosniff');
|
|
415
|
+
response.setHeader('Referrer-Policy', 'no-referrer');
|
|
416
|
+
// Plugin mode relies on CSP frame-ancestors (which browsers prefer over XFO);
|
|
417
|
+
// X-Frame-Options cannot list another origin.
|
|
418
|
+
if (!embedded) response.setHeader('X-Frame-Options', 'SAMEORIGIN');
|
|
419
|
+
const write = !['GET', 'HEAD'].includes(request.method);
|
|
420
|
+
guard(request, write);
|
|
421
|
+
const path = new URL(request.url, `http://127.0.0.1:${actualPort}`).pathname;
|
|
422
|
+
if (request.method === 'GET' && path === '/api/health') return json(response, 200, { appId: APP_ID, version: '0.3.0', mode: 'real', ready: !closing });
|
|
423
|
+
if (request.method === 'GET' && path === '/api/state') return json(response, 200, view());
|
|
424
|
+
if (request.method === 'GET' && path === '/api/review') return json(response, 200, await review.view());
|
|
425
|
+
if (request.method === 'GET' && path === '/api/review/backup') {
|
|
426
|
+
response.setHeader('Content-Disposition', 'attachment; filename="review-settings.json"');
|
|
427
|
+
return json(response, 200, review.backup());
|
|
428
|
+
}
|
|
429
|
+
if (request.method === 'POST' && path.startsWith('/api/review/')) {
|
|
430
|
+
const body = await readJson(request, path === '/api/review/restore' ? 32 * 1048576 + 1024 : 8 * 1048576);
|
|
431
|
+
reserve('review'); busy.stage = '正在检查和保存处理结果';
|
|
432
|
+
try {
|
|
433
|
+
const action = path.slice('/api/review/'.length);
|
|
434
|
+
const result = action === 'check' ? await review.check() : await review.mutate(action, body);
|
|
435
|
+
busy = null;
|
|
436
|
+
return json(response, 200, { review: result, state: view() });
|
|
437
|
+
} finally { busy = null; }
|
|
438
|
+
}
|
|
439
|
+
if (request.method === 'POST' && path === '/api/identify') {
|
|
440
|
+
if (request.headers['content-type'] !== 'application/octet-stream') throw new RequestError(415, '上传格式无效,请从后台选择文件。');
|
|
441
|
+
const temp = resolve(dataDir, 'temp', `identify-${randomUUID()}.xlsx`);
|
|
442
|
+
let result;
|
|
443
|
+
try { await receiveFile(request, temp); result = await identifyWorkbook(temp); }
|
|
444
|
+
finally { await rm(temp, { force: true }).catch(log); }
|
|
445
|
+
return json(response, 200, result);
|
|
446
|
+
}
|
|
447
|
+
if (request.method === 'POST' && path === '/api/settings/cycle') {
|
|
448
|
+
const body = await readJson(request, 1024);
|
|
449
|
+
if (!knownModules.has(body.moduleId) || !CYCLES.includes(body.cycle)) throw new RequestError(400, '更新周期设置无效。');
|
|
450
|
+
await store.update(next => { next.settings ??= {}; next.settings.cycles = { ...(next.settings.cycles || {}), [body.moduleId]: body.cycle }; });
|
|
451
|
+
return json(response, 200, { state: view() });
|
|
452
|
+
}
|
|
453
|
+
if (request.method === 'POST' && path.startsWith('/api/uploads/')) return upload(request, response, path.slice('/api/uploads/'.length));
|
|
454
|
+
if (request.method === 'POST' && path === '/api/updates/analyze') return analyzeUpdate(request, response);
|
|
455
|
+
if (request.method === 'POST' && path === '/api/updates/preview') return json(response, 200, { receipt: await previewUpdate(await readJson(request, 4096)) });
|
|
456
|
+
if (request.method === 'POST' && path === '/api/updates/apply') return applyUpdate(await readJson(request, 4096), response);
|
|
457
|
+
if (request.method === 'POST' && path === '/api/updates/discard') {
|
|
458
|
+
const body = await readJson(request, 1024);
|
|
459
|
+
await rm(stagedDir(body.stagedId), { recursive: true, force: true }).catch(log);
|
|
460
|
+
return json(response, 200, { ok: true });
|
|
461
|
+
}
|
|
462
|
+
if (request.method === 'POST' && path === '/api/generations') {
|
|
463
|
+
const options = await readJson(request, 1024);
|
|
464
|
+
if ('allowPending' in options && typeof options.allowPending !== 'boolean') throw new RequestError(400, '待确认生成选项无效。');
|
|
465
|
+
reserve('generate');
|
|
466
|
+
let sourceVersions;
|
|
467
|
+
let reviewResult;
|
|
468
|
+
try {
|
|
469
|
+
reviewResult = await review.view();
|
|
470
|
+
if (reviewResult.modules.some(module => module.status === 'unchecked')) reviewResult = await review.check();
|
|
471
|
+
const unresolved = reviewResult.modules.filter(module => ['pending', 'error'].includes(module.status));
|
|
472
|
+
if (unresolved.length && !options.allowPending) throw new Error(`还有 ${unresolved.length} 个板块需要处理,请在导入检查中确认后生成,或明确选择生成待确认版本。`);
|
|
473
|
+
sourceVersions = captureSourceSnapshot(store.state, { includeCandidates: true });
|
|
474
|
+
if (!Object.keys(sourceVersions).length) throw new Error('请先上传并校验至少一个板块的真实资料。');
|
|
475
|
+
} catch (error) { busy = null; throw new RequestError(422, error.message); }
|
|
476
|
+
const id = randomUUID();
|
|
477
|
+
const createdAt = new Date().toISOString();
|
|
478
|
+
const needsReview = reviewResult.modules.some(module => ['pending', 'error'].includes(module.status));
|
|
479
|
+
const job = { id, createdAt, status: 'running', stage: busy.stage, mode: 'real', selection: 'review', allowPending: options.allowPending === true, needsReview, sourceVersions, sourceIds: Object.fromEntries(Object.entries(sourceVersions).map(([id, source]) => [id, source.uploadId])), filename: `战区经营看板_v10_${needsReview ? '待确认' : '真实数据'}_${createdAt.replace(/[-:]/g, '').replace(/\.\d+Z/, 'Z')}_${id.slice(0, 6)}.html` };
|
|
480
|
+
try { await store.update(next => { next.generations.push(job); }); }
|
|
481
|
+
catch (error) { busy = null; throw error; }
|
|
482
|
+
json(response, 202, { generation: job });
|
|
483
|
+
track(generate(job)).catch(log);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
const outputMatch = /^\/api\/generations\/([a-f0-9-]{36})\/(view|download)$/.exec(path);
|
|
487
|
+
if (request.method === 'GET' && outputMatch) {
|
|
488
|
+
const job = store.state.generations.find(g => g.id === outputMatch[1] && g.status === 'completed');
|
|
489
|
+
if (!job) throw new RequestError(404, '成品不存在或尚未完成。');
|
|
490
|
+
const file = resolve(dataDir, 'generations', job.id, 'dashboard.html');
|
|
491
|
+
const info = await stat(file);
|
|
492
|
+
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': info.size, 'Content-Disposition': `${outputMatch[2] === 'download' ? 'attachment' : 'inline'}; filename="dashboard.html"; filename*=UTF-8''${encodeURIComponent(job.filename)}`, 'Content-Security-Policy': `default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; base-uri 'none'; frame-ancestors ${ancestors()}; form-action 'none'` });
|
|
493
|
+
await pipeline(createReadStream(file), response);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
if (request.method === 'GET' && path === '/api/target-template') {
|
|
497
|
+
// Organization names come from source inspections; scan any active source
|
|
498
|
+
// that has not been inspected yet so the template is not left blank.
|
|
499
|
+
for (const id of ['invoice', 'movement', 'opening']) {
|
|
500
|
+
const upload = store.state.uploads.find(item => item.id === store.state.active[id] && item.moduleId === id);
|
|
501
|
+
if (upload && !(await review.inspection(upload).catch(() => null))) await review.inspect(upload).catch(log);
|
|
502
|
+
}
|
|
503
|
+
const content = await buildTargetTemplate({ organizations: await targetOrganizations(dataDir, store.state) });
|
|
504
|
+
response.writeHead(200, { 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'Content-Length': content.length,
|
|
505
|
+
'Content-Disposition': `attachment; filename="target-template.xlsx"; filename*=UTF-8''${encodeURIComponent('经营目标模板.xlsx')}` });
|
|
506
|
+
response.end(content);
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
if (request.method === 'GET' && publicFiles.has(path)) {
|
|
510
|
+
const [file, type] = publicFiles.get(path);
|
|
511
|
+
const content = await readFile(resolve(here, 'public', file));
|
|
512
|
+
response.writeHead(200, { 'Content-Type': type, 'Content-Security-Policy': `default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; frame-ancestors ${ancestors()}; form-action 'self'` });
|
|
513
|
+
response.end(content);
|
|
514
|
+
return;
|
|
515
|
+
}
|
|
516
|
+
if (path === '/favicon.ico') { response.writeHead(204); response.end(); return; }
|
|
517
|
+
throw new RequestError(404, '没有这个页面或接口。');
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const server = http.createServer((request, response) => {
|
|
521
|
+
track(route(request, response)).catch(error => {
|
|
522
|
+
if (response.headersSent || response.destroyed) return;
|
|
523
|
+
if (!(error instanceof RequestError)) log(error.stack);
|
|
524
|
+
json(response, error.status || 500, { error: error.status ? error.message : '本机操作未完成,请检查文件或存储空间后重试。', ...(error.extra || {}) });
|
|
525
|
+
});
|
|
526
|
+
});
|
|
527
|
+
server.requestTimeout = 180_000;
|
|
528
|
+
server.headersTimeout = 15_000;
|
|
529
|
+
try {
|
|
530
|
+
await new Promise((ok, fail) => { server.once('error', fail); server.listen(port, '127.0.0.1', ok); });
|
|
531
|
+
actualPort = server.address().port;
|
|
532
|
+
} catch (error) { await store.release(); throw error; }
|
|
533
|
+
refreshCoverage();
|
|
534
|
+
return {
|
|
535
|
+
server, port: actualPort, url: `http://127.0.0.1:${actualPort}/`, dataDir,
|
|
536
|
+
async close() {
|
|
537
|
+
closing = true;
|
|
538
|
+
const stopped = new Promise(ok => server.close(ok));
|
|
539
|
+
server.closeIdleConnections();
|
|
540
|
+
await Promise.allSettled([...pending]);
|
|
541
|
+
await stopped;
|
|
542
|
+
await store.release();
|
|
543
|
+
},
|
|
544
|
+
};
|
|
545
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile, rename, unlink, open, rmdir } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
export async function atomicJson(file, value) {
|
|
6
|
+
const temp = `${file}.${randomUUID()}.tmp`;
|
|
7
|
+
try {
|
|
8
|
+
const handle = await open(temp, 'wx', 0o600);
|
|
9
|
+
try { await handle.writeFile(JSON.stringify(value, null, 2)); await handle.sync(); }
|
|
10
|
+
finally { await handle.close(); }
|
|
11
|
+
await rename(temp, file);
|
|
12
|
+
} finally { await unlink(temp).catch(() => {}); }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function openStore(dataDir) {
|
|
16
|
+
await mkdir(dataDir, { recursive: true, mode: 0o700 });
|
|
17
|
+
const lock = resolve(dataDir, 'server.lock');
|
|
18
|
+
const gate = resolve(dataDir, 'startup.lock');
|
|
19
|
+
const owner = randomUUID();
|
|
20
|
+
// mkdir is exclusive. Serialize stale-lock recovery so two launches cannot steal
|
|
21
|
+
// a newly acquired lock. An interrupted gate is kept for explicit recovery.
|
|
22
|
+
try { await mkdir(gate, { mode: 0o700 }); }
|
|
23
|
+
catch (error) { if (error.code === 'EEXIST') throw new Error('另一个后台正在启动。若确认没有后台进程,请移除空的 startup.lock 目录后重试。'); throw error; }
|
|
24
|
+
try {
|
|
25
|
+
try { await writeFile(lock, JSON.stringify({ pid: process.pid, owner }), { flag: 'wx', mode: 0o600 }); }
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (error.code !== 'EEXIST') throw error;
|
|
28
|
+
let old;
|
|
29
|
+
try { old = JSON.parse(await readFile(lock, 'utf8')); }
|
|
30
|
+
catch { throw new Error('后台数据目录中的运行锁无法读取,请检查 server.lock;原数据未改动。'); }
|
|
31
|
+
if (!Number.isInteger(old.pid) || old.pid <= 0) throw new Error('后台运行锁无效,请检查 server.lock。');
|
|
32
|
+
try { process.kill(old.pid, 0); throw new Error('此数据目录已有后台进程在使用。'); }
|
|
33
|
+
catch (error) { if (error.code !== 'ESRCH') throw error; }
|
|
34
|
+
await unlink(lock);
|
|
35
|
+
await writeFile(lock, JSON.stringify({ pid: process.pid, owner }), { flag: 'wx', mode: 0o600 });
|
|
36
|
+
}
|
|
37
|
+
} finally { await rmdir(gate); }
|
|
38
|
+
const release = async () => { try { const current = JSON.parse(await readFile(lock, 'utf8')); if (current.owner === owner) await unlink(lock); } catch {} };
|
|
39
|
+
try {
|
|
40
|
+
for (const name of ['uploads', 'parts', 'generations', 'temp', 'logs']) await mkdir(resolve(dataDir, name), { recursive: true, mode: 0o700 });
|
|
41
|
+
const manifestPath = resolve(dataDir, 'state.json');
|
|
42
|
+
let state;
|
|
43
|
+
try { state = JSON.parse(await readFile(manifestPath, 'utf8')); }
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (error.code !== 'ENOENT') throw new Error('后台记录无法读取,已停止启动以保留原数据。请检查 state.json。');
|
|
46
|
+
state = { schemaVersion: 1, uploads: [], active: {}, generations: [] };
|
|
47
|
+
}
|
|
48
|
+
if (state.schemaVersion !== 1 || !Array.isArray(state.uploads) || !Array.isArray(state.generations) || !state.active || typeof state.active !== 'object') throw new Error('后台记录格式不受支持,原数据已保留。');
|
|
49
|
+
if (state.review && (state.review.version !== 1 || !Number.isSafeInteger(state.review.revision) || !Array.isArray(state.review.decisions) || !Array.isArray(state.review.organizationRules) || !Array.isArray(state.review.history))) throw new Error('检查处理记录格式不受支持,原数据已保留。');
|
|
50
|
+
if (state.candidates && (typeof state.candidates !== 'object' || Array.isArray(state.candidates))) throw new Error('待处理来源记录格式无效,原数据已保留。');
|
|
51
|
+
let queue = Promise.resolve();
|
|
52
|
+
async function update(change) {
|
|
53
|
+
const pending = queue.then(async () => {
|
|
54
|
+
const next = structuredClone(state);
|
|
55
|
+
await change(next);
|
|
56
|
+
await atomicJson(manifestPath, next);
|
|
57
|
+
state = next;
|
|
58
|
+
return next;
|
|
59
|
+
});
|
|
60
|
+
queue = pending.catch(() => {});
|
|
61
|
+
return pending;
|
|
62
|
+
}
|
|
63
|
+
await update(next => {
|
|
64
|
+
for (const job of next.generations) if (job.status === 'running') Object.assign(job, { status: 'failed', stage: '生成中断', error: '上次后台退出时任务尚未完成,请重新生成。', finishedAt: new Date().toISOString() });
|
|
65
|
+
});
|
|
66
|
+
return { get state() { return state; }, update, release };
|
|
67
|
+
} catch (error) { await release(); throw error; }
|
|
68
|
+
}
|