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,47 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import ExcelJS from 'exceljs';
|
|
4
|
+
|
|
5
|
+
const SOURCES = ['invoice', 'movement', 'opening'];
|
|
6
|
+
|
|
7
|
+
// Prefill organization names already seen in the active sources. Business
|
|
8
|
+
// values stay blank: the template never suggests or copies a target amount.
|
|
9
|
+
export async function targetOrganizations(dataDir, state) {
|
|
10
|
+
const seen = new Map();
|
|
11
|
+
for (const id of SOURCES) {
|
|
12
|
+
const uploadId = state.active?.[id];
|
|
13
|
+
if (typeof uploadId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(uploadId)) continue;
|
|
14
|
+
try {
|
|
15
|
+
const inspection = JSON.parse(await readFile(resolve(dataDir, 'uploads', uploadId, 'inspection.json'), 'utf8'));
|
|
16
|
+
for (const org of inspection.organizations || []) {
|
|
17
|
+
const names = (org.path || []).slice(3, 6).map(value => String(value ?? '').trim());
|
|
18
|
+
if (names.length === 3 && names.every(Boolean)) seen.set(JSON.stringify(names), names);
|
|
19
|
+
}
|
|
20
|
+
} catch { /* An unchecked source simply contributes no names. */ }
|
|
21
|
+
}
|
|
22
|
+
return [...seen.values()].sort((a, b) => a.join('/').localeCompare(b.join('/'), 'zh-CN'));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function buildTargetTemplate({ organizations = [], month = new Date().toISOString().slice(0, 7) } = {}) {
|
|
26
|
+
const workbook = new ExcelJS.Workbook();
|
|
27
|
+
const sheet = workbook.addWorksheet('经营目标');
|
|
28
|
+
sheet.columns = [['年月', 12], ['大区', 16], ['办事处', 18], ['主任单元', 22], ['发票目标(万元)', 18], ['动销目标(万元)', 18]].map(([header, width]) => ({ header, width }));
|
|
29
|
+
sheet.getRow(1).font = { bold: true };
|
|
30
|
+
sheet.views = [{ state: 'frozen', ySplit: 1 }];
|
|
31
|
+
for (const names of organizations) sheet.addRow([month, ...names, null, null]);
|
|
32
|
+
if (!organizations.length) sheet.addRow([month, '', '', '', null, null]);
|
|
33
|
+
sheet.getColumn(1).numFmt = '@';
|
|
34
|
+
const guide = workbook.addWorksheet('填写说明');
|
|
35
|
+
guide.columns = [{ header: '说明', width: 110 }];
|
|
36
|
+
guide.getRow(1).font = { bold: true };
|
|
37
|
+
for (const line of [
|
|
38
|
+
'只读取“经营目标”工作表;第 1 行表头请勿修改。每行一个月份 × 组织,发票目标、动销目标分两列填写。',
|
|
39
|
+
'年月写成 2026-11 这样的格式;同一组织不同月份请分行填写。',
|
|
40
|
+
'金额单位为万元。如需按元填写,可把表头改成“发票目标(元)”“动销目标(元)”。需要开瓶目标时可加一列“开瓶目标(瓶)”。',
|
|
41
|
+
'主任单元留空 = 目标填在办事处层级;办事处也留空 = 大区层级;三级都留空 = 全战区目标。上级目标不会自动拆分到下级,可以只填大区或部分办事处。',
|
|
42
|
+
'大区、办事处、主任单元名称需与经营来源中的名称一致,对不上的目标不会计入。',
|
|
43
|
+
'某一列留空表示该组织当月没有这项目标;整行都没填的可以保留也可以删除。同一年月、组织请只填一行;重复时该目标显示待确认。',
|
|
44
|
+
'已预填的组织名称来自当前已上传的发票、动销、开瓶资料,目标值需自行填写。',
|
|
45
|
+
]) guide.addRow([line]);
|
|
46
|
+
return Buffer.from(await workbook.xlsx.writeBuffer());
|
|
47
|
+
}
|
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import yauzl from 'yauzl';
|
|
2
|
+
import { SaxesParser } from 'saxes';
|
|
3
|
+
import { posix } from 'node:path';
|
|
4
|
+
import { moduleById, moduleDefinitions, normalizeHeader } from './modules.mjs';
|
|
5
|
+
import { createRecognitionResult, addIssue, mapFields } from './recognition/result.mjs';
|
|
6
|
+
import { uploadLimits as limits, formatUploadMB } from './recognition/upload-limits.mjs';
|
|
7
|
+
|
|
8
|
+
class WorkbookValidationError extends Error {
|
|
9
|
+
constructor(message, code = 'WORKBOOK_UNREADABLE') { super(message); this.code = code; }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function expansionError(entry, bytes, totalBytes) {
|
|
13
|
+
if (bytes > limits.entryBytes) {
|
|
14
|
+
const label = /^xl\/worksheets\/[^/]+\.xml$/i.test(entry.fileName) ? '单张工作表' : '单个工作簿内部文件';
|
|
15
|
+
return new WorkbookValidationError(`${label}解压后大小为 ${formatUploadMB(bytes)},超过 ${limits.entryBytes / 1048576} MB 上限。请整理文件后重试;多次上传不会合并。`, 'WORKBOOK_ENTRY_TOO_LARGE');
|
|
16
|
+
}
|
|
17
|
+
if (totalBytes > limits.totalBytes) return new WorkbookValidationError(`工作簿累计解压内容为 ${formatUploadMB(totalBytes)},超过整本 ${limits.totalBytes / 1048576} MB(1 GB)上限。请整理文件后重试;多次上传不会合并。`, 'WORKBOOK_TOTAL_TOO_LARGE');
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Scan and decompress without extracting files. Checking actual bytes also catches
|
|
22
|
+
// forged ZIP sizes before the spreadsheet parser sees the archive.
|
|
23
|
+
async function checkArchive(path) {
|
|
24
|
+
await new Promise((resolve, reject) => {
|
|
25
|
+
yauzl.open(path, { lazyEntries: true, autoClose: true, validateEntrySizes: true }, (error, zip) => {
|
|
26
|
+
if (error) return reject(new WorkbookValidationError('文件不是可读取的 XLSX 工作簿,可能已损坏或加密。'));
|
|
27
|
+
let ended = false, entryCount = 0, declaredBytes = 0, actualBytes = 0;
|
|
28
|
+
const names = new Set();
|
|
29
|
+
const fail = error => { if (!ended) { ended = true; zip.close(); reject(error); } };
|
|
30
|
+
zip.on('error', () => fail(new WorkbookValidationError('XLSX 压缩内容不完整或已损坏。')));
|
|
31
|
+
zip.on('entry', entry => {
|
|
32
|
+
if (ended) return;
|
|
33
|
+
entryCount++;
|
|
34
|
+
declaredBytes += entry.uncompressedSize;
|
|
35
|
+
if (entryCount > limits.entries) return fail(new WorkbookValidationError(`工作簿内部文件已超过 ${limits.entries} 个(当前至少 ${entryCount} 个),请整理无用内容后重试。`, 'WORKBOOK_TOO_MANY_ENTRIES'));
|
|
36
|
+
const declaredError = expansionError(entry, entry.uncompressedSize, declaredBytes);
|
|
37
|
+
if (declaredError) return fail(declaredError);
|
|
38
|
+
if (names.has(entry.fileName)) return fail(new WorkbookValidationError('工作簿包含重复的内部文件,无法可靠校验。'));
|
|
39
|
+
names.add(entry.fileName);
|
|
40
|
+
if (/vbaProject\.bin$/i.test(entry.fileName)) return fail(new WorkbookValidationError('此入口仅支持不含宏的 .xlsx 文件。'));
|
|
41
|
+
if (entry.generalPurposeBitFlag & 1) return fail(new WorkbookValidationError('暂不支持加密工作簿,请另存为未加密的 .xlsx 文件。'));
|
|
42
|
+
if (entry.fileName.endsWith('/')) { zip.readEntry(); return; }
|
|
43
|
+
zip.openReadStream(entry, (error, stream) => {
|
|
44
|
+
if (error) return fail(new WorkbookValidationError('XLSX 压缩内容无法读取。'));
|
|
45
|
+
let entryBytes = 0;
|
|
46
|
+
stream.on('data', chunk => {
|
|
47
|
+
entryBytes += chunk.length; actualBytes += chunk.length;
|
|
48
|
+
const actualError = expansionError(entry, entryBytes, actualBytes);
|
|
49
|
+
if (actualError) {
|
|
50
|
+
stream.destroy();
|
|
51
|
+
fail(actualError);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
stream.on('error', () => fail(new WorkbookValidationError('XLSX 压缩内容不完整或已损坏。')));
|
|
55
|
+
stream.on('end', () => { if (!ended) zip.readEntry(); });
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
zip.on('end', () => {
|
|
59
|
+
if (ended) return;
|
|
60
|
+
ended = true;
|
|
61
|
+
if (!names.has('[Content_Types].xml') || !names.has('xl/workbook.xml')) {
|
|
62
|
+
reject(new WorkbookValidationError('文件缺少 XLSX 工作簿结构,请用 Excel 另存为 .xlsx 后重试。'));
|
|
63
|
+
} else resolve();
|
|
64
|
+
});
|
|
65
|
+
zip.readEntry();
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function openArchive(path) {
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
yauzl.open(path, { lazyEntries: true, autoClose: false, validateEntrySizes: true }, (error, zip) => {
|
|
73
|
+
if (error) return reject(error);
|
|
74
|
+
const entries = new Map();
|
|
75
|
+
zip.on('error', reject);
|
|
76
|
+
zip.on('entry', entry => { entries.set(entry.fileName, entry); zip.readEntry(); });
|
|
77
|
+
zip.on('end', () => resolve({ zip, entries }));
|
|
78
|
+
zip.readEntry();
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async function parseXml(archive, path, handlers) {
|
|
84
|
+
const entry = archive.entries.get(path);
|
|
85
|
+
if (!entry) throw new WorkbookValidationError('工作簿缺少必需的内部工作表内容。');
|
|
86
|
+
const stream = await new Promise((resolve, reject) => archive.zip.openReadStream(entry, (error, value) => error ? reject(error) : resolve(value)));
|
|
87
|
+
const parser = new SaxesParser();
|
|
88
|
+
parser.on('doctype', () => { throw new WorkbookValidationError('工作簿含不支持的 XML 文档声明,请另存为标准 XLSX。'); });
|
|
89
|
+
for (const [name, handler] of Object.entries(handlers)) parser.on(name, handler);
|
|
90
|
+
stream.setEncoding('utf8');
|
|
91
|
+
try { for await (const chunk of stream) parser.write(chunk); parser.close(); }
|
|
92
|
+
finally { stream.destroy(); }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const localName = node => node.name.split(':').at(-1);
|
|
96
|
+
const sourceFormats = module => module.sourceFormats ?? [module];
|
|
97
|
+
const acceptsSheet = (format, sheet) => format.sheetNames.some(name => normalizeHeader(name) === normalizeHeader(sheet));
|
|
98
|
+
|
|
99
|
+
async function readStructure(filePath, module) {
|
|
100
|
+
const archive = await openArchive(filePath);
|
|
101
|
+
try {
|
|
102
|
+
const sheets = [], relationships = new Map(), sharedStrings = [];
|
|
103
|
+
await parseXml(archive, 'xl/workbook.xml', { opentag(node) {
|
|
104
|
+
if (localName(node) === 'sheet') {
|
|
105
|
+
if (!node.attributes.name || node.attributes.name.length > 128) throw new WorkbookValidationError('工作表名称为空或过长。');
|
|
106
|
+
const relId = Object.entries(node.attributes).find(([name]) => name.endsWith(':id'))?.[1];
|
|
107
|
+
sheets.push({ name: node.attributes.name, relId });
|
|
108
|
+
}
|
|
109
|
+
} });
|
|
110
|
+
await parseXml(archive, 'xl/_rels/workbook.xml.rels', { opentag(node) {
|
|
111
|
+
if (localName(node) === 'Relationship' && /\/worksheet$/.test(node.attributes.Type ?? '')) {
|
|
112
|
+
if (node.attributes.TargetMode === 'External') throw new WorkbookValidationError('主工作表不能是外部链接。');
|
|
113
|
+
const target = node.attributes.Target ?? '';
|
|
114
|
+
const path = posix.normalize(target.startsWith('/') ? target.slice(1) : posix.join('xl', target));
|
|
115
|
+
if (!path.startsWith('xl/')) throw new WorkbookValidationError('工作簿内部工作表路径无效。');
|
|
116
|
+
relationships.set(node.attributes.Id, path);
|
|
117
|
+
}
|
|
118
|
+
} });
|
|
119
|
+
if (archive.entries.has('xl/sharedStrings.xml')) {
|
|
120
|
+
let value = '', inText = false, inString = false, totalCharacters = 0;
|
|
121
|
+
await parseXml(archive, 'xl/sharedStrings.xml', {
|
|
122
|
+
opentag(node) { const name = localName(node); if (name === 'si') { value = ''; inString = true; } if (name === 't' && inString) inText = true; },
|
|
123
|
+
text(text) { if (inText) { value += text; totalCharacters += text.length; if (value.length > 1_000_000 || totalCharacters > 64 * 1024 * 1024) throw new WorkbookValidationError('工作簿文字内容过大,请整理无用文字或格式后重试;多次上传不会合并。'); } },
|
|
124
|
+
closetag(node) { const name = localName(node); if (name === 't') inText = false; if (name === 'si') { sharedStrings.push(value); inString = false; if (sharedStrings.length > 1_000_000) throw new WorkbookValidationError('工作簿文字条目过多,请整理无用内容后重试;多次上传不会合并。'); } },
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
const output = [];
|
|
128
|
+
for (const sheet of sheets) {
|
|
129
|
+
const path = relationships.get(sheet.relId);
|
|
130
|
+
if (!path) continue; // Chart sheets have no business rows.
|
|
131
|
+
const result = { sheet: sheet.name, headers: [], rowCount: 0 };
|
|
132
|
+
const format = sourceFormats(module).find(format => acceptsSheet(format, sheet.name));
|
|
133
|
+
const isMain = Boolean(format);
|
|
134
|
+
const sourceColumnLimit = format?.sourceColumnLimit ?? module.sourceColumnLimit;
|
|
135
|
+
let rowNumber = 0, previousRow = 0, nonempty = false, cell = null, capture = false, previousCol = 0;
|
|
136
|
+
await parseXml(archive, path, {
|
|
137
|
+
opentag(node) {
|
|
138
|
+
const name = localName(node);
|
|
139
|
+
if (name === 'row') {
|
|
140
|
+
rowNumber = node.attributes.r === undefined ? previousRow + 1 : Number(node.attributes.r);
|
|
141
|
+
if (!Number.isInteger(rowNumber) || rowNumber <= previousRow || rowNumber > limits.rows + 1) throw new WorkbookValidationError('工作表行号无效或超过 100 万行,请整理后再上传。');
|
|
142
|
+
previousRow = rowNumber; previousCol = 0; nonempty = false;
|
|
143
|
+
}
|
|
144
|
+
if (name === 'c') {
|
|
145
|
+
const reference = node.attributes.r;
|
|
146
|
+
const address = reference?.match(/^([A-Z]+)([1-9][0-9]*)$/);
|
|
147
|
+
const letters = address?.[1];
|
|
148
|
+
const column = reference === undefined ? previousCol + 1 : letters ? [...letters].reduce((n, c) => n * 26 + c.charCodeAt(0) - 64, 0) : 0;
|
|
149
|
+
if (!rowNumber || !column || column <= previousCol || column > limits.columns || (address && Number(address[2]) !== rowNumber)) throw new WorkbookValidationError('工作表单元格位置无效或超过 512 列,请保留业务表后再上传。');
|
|
150
|
+
previousCol = column; cell = { type: node.attributes.t, column, value: '', formula: false };
|
|
151
|
+
}
|
|
152
|
+
if (name === 'f' && cell) cell.formula = true;
|
|
153
|
+
if ((name === 't' || name === 'v') && cell) capture = true;
|
|
154
|
+
},
|
|
155
|
+
text(text) { if (capture && cell) { cell.value += text; if (cell.value.length > 1_000_000) throw new WorkbookValidationError('单元格文字过大,请整理后再上传。'); } },
|
|
156
|
+
closetag(node) {
|
|
157
|
+
const name = localName(node);
|
|
158
|
+
if (name === 't' || name === 'v') capture = false;
|
|
159
|
+
if (name === 'c' && cell) {
|
|
160
|
+
// Business recognition is bounded by the module's reviewed source
|
|
161
|
+
// columns. Archive integrity and resource limits still apply above.
|
|
162
|
+
if (isMain && sourceColumnLimit && cell.column > sourceColumnLimit) { cell = null; return; }
|
|
163
|
+
let value = cell.value;
|
|
164
|
+
if (cell.type === 's') {
|
|
165
|
+
const index = Number(value);
|
|
166
|
+
if (!value.trim() || !Number.isInteger(index) || index < 0 || index >= sharedStrings.length) throw new WorkbookValidationError('工作簿文字引用损坏,请另存为 XLSX 后重试。');
|
|
167
|
+
value = sharedStrings[index];
|
|
168
|
+
}
|
|
169
|
+
if (value.trim() !== '' || cell.formula) nonempty = true;
|
|
170
|
+
if (isMain && rowNumber === 1) {
|
|
171
|
+
if (cell.formula || cell.type === 'e') throw new WorkbookValidationError('第 1 行表头需为普通文字,不能使用公式或错误值。');
|
|
172
|
+
if (value.length > 256) throw new WorkbookValidationError('第 1 行含过长表头,请确认第 1 行是字段名称。');
|
|
173
|
+
while (result.headers.length < cell.column) result.headers.push('');
|
|
174
|
+
result.headers[cell.column - 1] = value.trim();
|
|
175
|
+
}
|
|
176
|
+
cell = null;
|
|
177
|
+
}
|
|
178
|
+
if (name === 'row' && rowNumber > 1 && nonempty) result.rowCount++;
|
|
179
|
+
},
|
|
180
|
+
});
|
|
181
|
+
output.push(result);
|
|
182
|
+
}
|
|
183
|
+
return output;
|
|
184
|
+
} finally { archive.zip.close(); }
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export async function validateWorkbook(filePath, moduleId) {
|
|
188
|
+
const result = createRecognitionResult(moduleId);
|
|
189
|
+
const module = moduleById.get(moduleId);
|
|
190
|
+
if (!module) { addIssue(result, 'error', 'UNSUPPORTED_MODULE', '不支持的板块。'); return result; }
|
|
191
|
+
try {
|
|
192
|
+
await checkArchive(filePath);
|
|
193
|
+
const structure = await readStructure(filePath, module);
|
|
194
|
+
result.sheets = structure.map(sheet => ({ name: sheet.sheet, rowCount: sheet.rowCount }));
|
|
195
|
+
const matches = structure.flatMap(sheet => sourceFormats(module).filter(format => acceptsSheet(format, sheet.sheet)).map(format => ({ sheet, format })));
|
|
196
|
+
if (matches.length !== 1) {
|
|
197
|
+
addIssue(result, 'error', matches.length ? 'AMBIGUOUS_SHEET' : 'MISSING_SHEET', matches.length ? '存在多个名称等价的主工作表,请只保留一份待校验主表。' : `未找到主工作表“${module.sheetNames[0]}”,请检查是否选错板块或文件。`);
|
|
198
|
+
return result;
|
|
199
|
+
}
|
|
200
|
+
const { sheet, format } = matches[0];
|
|
201
|
+
Object.assign(result, sheet);
|
|
202
|
+
if (format.sourceFormat) result.sourceFormat = format.sourceFormat;
|
|
203
|
+
result.fieldMappings = mapFields(format.fields, result.headers);
|
|
204
|
+
const normalized = result.headers.map(normalizeHeader);
|
|
205
|
+
const seen = new Set(), duplicates = new Set();
|
|
206
|
+
normalized.filter(Boolean).forEach(header => { if (seen.has(header)) duplicates.add(header); else seen.add(header); });
|
|
207
|
+
const headerLocation = { sheet: result.sheet, row: result.headerRow };
|
|
208
|
+
const missing = result.fieldMappings.filter(mapping => !mapping.matches.length);
|
|
209
|
+
result.missingHeaders = missing.map(mapping => mapping.expectedHeader);
|
|
210
|
+
if (!result.headers.length) addIssue(result, 'error', 'EMPTY_HEADER', '第 1 行没有表头,请将字段名称放在第 1 行。', headerLocation);
|
|
211
|
+
if (missing.length) addIssue(result, 'error', 'MISSING_HEADER', `缺少必需字段:${result.missingHeaders.join('、')}。`, { ...headerLocation, field: missing.length === 1 ? missing[0].field : null });
|
|
212
|
+
for (const header of duplicates) {
|
|
213
|
+
const columns = normalized.flatMap((value, index) => value === header ? [index + 1] : []);
|
|
214
|
+
const field = format.fields.find(field => normalizeHeader(field.header) === header)?.key ?? null;
|
|
215
|
+
addIssue(result, 'error', 'DUPLICATE_HEADER', `存在重复表头:${header}。`, { ...headerLocation, columns, field });
|
|
216
|
+
}
|
|
217
|
+
const extra = typeof module.headerCheck === 'function' && result.headers.length ? module.headerCheck(result.headers) : null;
|
|
218
|
+
if (extra) addIssue(result, 'error', 'MISSING_HEADER', extra, headerLocation);
|
|
219
|
+
if (!result.rowCount) addIssue(result, 'error', 'EMPTY_DATA', '主工作表只有表头或为空,没有非空数据行。', { sheet: result.sheet });
|
|
220
|
+
const blankColumns = result.headers.flatMap((header, index) => header ? [] : [index + 1]);
|
|
221
|
+
if (blankColumns.length) addIssue(result, 'warning', 'BLANK_HEADER', '表头中存在空白列;后续计算只会使用明确命名的字段。', { ...headerLocation, columns: blankColumns });
|
|
222
|
+
if (result.sheets.length > 1) addIssue(result, 'warning', 'OTHER_SHEETS_IGNORED', `共识别 ${result.sheets.length} 个工作表,仅以“${result.sheet}”进行板块表头校验,其他表不参与汇总。`, { sheet: result.sheet });
|
|
223
|
+
for (const note of format.notes ?? module.notes) addIssue(result, 'warning', 'MODULE_NOTE', note, { sheet: result.sheet });
|
|
224
|
+
result.ok = result.errors.length === 0;
|
|
225
|
+
return result;
|
|
226
|
+
} catch (error) {
|
|
227
|
+
addIssue(result, 'error', error instanceof WorkbookValidationError ? error.code : 'WORKBOOK_UNREADABLE', error instanceof WorkbookValidationError ? error.message : '无法解析此工作簿,请确认文件完整,并在 Excel 中另存为 .xlsx 后重试。');
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Identify which board a workbook belongs to from its sheet names only. This is
|
|
233
|
+
// a quick suggestion for batch uploads; the full structure check still runs on
|
|
234
|
+
// upload, and an ambiguous or unknown workbook must be assigned by the person.
|
|
235
|
+
export async function identifyWorkbook(filePath) {
|
|
236
|
+
try {
|
|
237
|
+
await checkArchive(filePath);
|
|
238
|
+
const archive = await openArchive(filePath);
|
|
239
|
+
const sheets = [];
|
|
240
|
+
try {
|
|
241
|
+
await parseXml(archive, 'xl/workbook.xml', { opentag(node) {
|
|
242
|
+
if (localName(node) === 'sheet' && typeof node.attributes.name === 'string' && node.attributes.name.length <= 128) sheets.push(node.attributes.name);
|
|
243
|
+
} });
|
|
244
|
+
} finally { archive.zip.close(); }
|
|
245
|
+
const matches = moduleDefinitions.filter(module => sheets.some(sheet => sourceFormats(module).some(format => acceptsSheet(format, sheet)))).map(module => module.id);
|
|
246
|
+
return { ok: true, sheets, matches, moduleId: matches.length === 1 ? matches[0] : null,
|
|
247
|
+
reason: matches.length === 1 ? null : matches.length ? '工作表同时符合多个板块,请手动选择' : '工作表名称不符合任何板块,请手动选择' };
|
|
248
|
+
} catch (error) {
|
|
249
|
+
return { ok: false, sheets: [], matches: [], moduleId: null, reason: error instanceof WorkbookValidationError ? error.message : '无法读取此工作簿,请确认是有效的 .xlsx 文件' };
|
|
250
|
+
}
|
|
251
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# 本地网站数据包
|
|
2
|
+
|
|
3
|
+
此目录的导出器只读现有后台资料,生成本地待验收结果,不联网、不更改当前上传、不写入原有生成记录。调用方完成本地验收后才能执行云端同步。
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
import { prepareWebsiteRelease } from './exporter.mjs';
|
|
7
|
+
|
|
8
|
+
const release = await prepareWebsiteRelease({
|
|
9
|
+
dataDir: '/absolute/path/to/local-data',
|
|
10
|
+
outputDir: '/absolute/path/to/new-release-directory',
|
|
11
|
+
previousRelease: '/absolute/path/to/previous-release/release.json', // 可省略,也接受上次返回对象
|
|
12
|
+
baseRevision: null, // 首次 null;否则明确填线上当前 revision,用于同步 CAS
|
|
13
|
+
uploadAttempts: {
|
|
14
|
+
invoice: { status: 'failed', attemptAt: '2026-11-01T01:00:00.000Z', error: '本次上传未通过' },
|
|
15
|
+
}, // 可省略;原后台仅记录成功上传,新控制器记录每板块最新尝试
|
|
16
|
+
onStage: text => { /* 本地展示任务阶段 */ },
|
|
17
|
+
});
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
`outputDir` 的父目录须存在,目标目录必须是全新目录。准备失败只清理本次创建的目标目录;已有目录拒绝覆盖。建议所有输出均放在仓库忽略目录 `本机后台数据/` 中。
|
|
21
|
+
|
|
22
|
+
返回字段:
|
|
23
|
+
|
|
24
|
+
- `payload`:完整本地处理结果,可供 `renderV10Dashboard(payload)` 生成管理员预览。
|
|
25
|
+
- `report`:仅本地使用的诊断,包括板块失败原因、混合来源规则状态、未确认组织归属记录数。
|
|
26
|
+
- `manifest`:云端同步清单,`revision / baseRevision / generatedAt / modules / scopes`。`modules[id]` 只有 `status / uploadId / updatedAt / error?`,不含业务总值、行数或源文件名。
|
|
27
|
+
- `objects`:各组织范围的 `{ id, path, sha256, bytes, file }`。`id` 是 `SHA256(JSON.stringify(path))`;`sha256` 和 `bytes` 针对 gzip 文件字节。文件解压后是 `packV10Payload(...)` 数据,前端用 `unpackV10Payload` 恢复。
|
|
28
|
+
- `manifestPath / releasePath`:清单和本地回退文件绝对路径。
|
|
29
|
+
- `sourceVersions`:实际采用的各板块上传 ID/SHA。
|
|
30
|
+
|
|
31
|
+
只允许向线上发送 `manifest` 和 `objects[].file`。`release.json` 保留用于下一次失败回退的完整本地数据和指纹,`diagnostics.json` 是内部诊断;这两者不应上传、打包进网站源码或进入 Git。
|
|
32
|
+
|
|
33
|
+
新板块处理失败时从上一份本地成功结果恢复该板块,其他成功板块正常推进。恢复后重新应用当前来源绑定组织映射,并校验跨表来源合同;过期规则保持待确认。首次无有效来源的失败板块不可用。原后台结构上传失败不会变更 active;调用方通过 `uploadAttempts` 明确这次失败,导出器因此将旧 active 标记为 retained。
|
|
34
|
+
|
|
35
|
+
组织作用域为管理员 `[]`、战区前三段、大区前四段、办事处前五段;每一段精确匹配。未确认归属、空缺和无效组织行只保留在管理员范围。普通范围不包含其他组织的数据、源文件名、内部字段或全局汇总。隐藏未知扫码身份后仍可能影响有效终端判断,因此相关规则保守置为 pending,避免把未知变成零。
|
|
36
|
+
|
|
37
|
+
独立验证:`node --test tests/web-sync-export.test.mjs`。测试使用临时合成 XLSX,不读取业务 Excel。
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
|
|
5
|
+
export function websiteOrigin(value) {
|
|
6
|
+
const url = new URL(value);
|
|
7
|
+
if (url.username || url.password || url.search || url.hash || url.pathname !== '/') throw new Error('网站地址只能填写网站首页地址。');
|
|
8
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(url.hostname))) throw new Error('网站必须使用 HTTPS;本机测试可以使用 loopback 地址。');
|
|
9
|
+
return url.origin;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function websiteRequest(config, path, { method = 'GET', body, binary = false, fetchImpl = fetch } = {}) {
|
|
13
|
+
const origin = websiteOrigin(config.siteUrl);
|
|
14
|
+
if (typeof config.syncKey !== 'string' || config.syncKey.length < 32) throw new Error('请先配置有效的网站同步凭据。');
|
|
15
|
+
const response = await fetchImpl(`${origin}${path}`, {
|
|
16
|
+
method, redirect: 'error', signal: AbortSignal.timeout(120_000),
|
|
17
|
+
headers: { Authorization: `Bearer ${config.syncKey}`, ...(body !== undefined ? { 'Content-Type': binary ? 'application/gzip' : 'application/json' } : {}) },
|
|
18
|
+
body: body === undefined ? undefined : binary ? body : JSON.stringify(body),
|
|
19
|
+
});
|
|
20
|
+
const text = await response.text();
|
|
21
|
+
let result; try { result = JSON.parse(text); } catch { throw new Error(`网站返回了非数据响应(${response.status}),请检查网站地址和部署状态。`); }
|
|
22
|
+
if (!response.ok) {
|
|
23
|
+
const error = new Error(result.error?.message || result.message || `网站请求失败(${response.status})。`);
|
|
24
|
+
error.code = result.error?.code || result.code; error.status = response.status; throw error;
|
|
25
|
+
}
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One accepted local release owns one immutable remote manifest. A retry never
|
|
30
|
+
* silently rebases an older release over a newer remote publication. */
|
|
31
|
+
export async function syncWebsiteRelease({ release, config, onStage = () => {}, fetchImpl = fetch }) {
|
|
32
|
+
const request = (path, options = {}) => websiteRequest(config, path, { ...options, fetchImpl });
|
|
33
|
+
const directory = resolve(release.releasePath, '..');
|
|
34
|
+
const syncPath = resolve(directory, 'sync-manifest.json');
|
|
35
|
+
let manifest;
|
|
36
|
+
try { manifest = JSON.parse(await readFile(syncPath, 'utf8')); }
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (error.code !== 'ENOENT') throw error;
|
|
39
|
+
const current = await request('/api/sync/state');
|
|
40
|
+
manifest = { ...release.manifest, baseRevision: current.revision };
|
|
41
|
+
await writeFile(syncPath, JSON.stringify(manifest), { flag: 'wx', mode: 0o600 });
|
|
42
|
+
}
|
|
43
|
+
const accepted = { ...release.manifest, baseRevision: manifest.baseRevision };
|
|
44
|
+
if (JSON.stringify(manifest) !== JSON.stringify(accepted)
|
|
45
|
+
|| !Array.isArray(manifest.scopes) || manifest.scopes.some(scope => !/^[a-f0-9]{64}$/.test(scope.id))) throw new Error('本地同步清单与验收版本不一致。');
|
|
46
|
+
onStage('正在核对线上版本');
|
|
47
|
+
const started = await request('/api/sync/start', { method: 'POST', body: manifest });
|
|
48
|
+
if (started.status !== 'committed') {
|
|
49
|
+
const uploaded = new Set(started.uploaded || []);
|
|
50
|
+
for (let i = 0; i < manifest.scopes.length; i++) {
|
|
51
|
+
const scope = manifest.scopes[i];
|
|
52
|
+
onStage(`正在同步授权数据 ${i + 1} / ${manifest.scopes.length}`);
|
|
53
|
+
if (uploaded.has(scope.id)) continue;
|
|
54
|
+
const bytes = await readFile(resolve(directory, 'objects', `${scope.id}.json.gz`));
|
|
55
|
+
if (bytes.length !== scope.bytes || createHash('sha256').update(bytes).digest('hex') !== scope.sha256) throw new Error('本地验收后的数据包已变化,请重新准备并验收。');
|
|
56
|
+
await request(`/api/sync/objects/${manifest.revision}/${scope.id}`, { method: 'PUT', body: bytes, binary: true });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
onStage('正在启用新版本');
|
|
60
|
+
const committed = await request('/api/sync/commit', { method: 'POST', body: { revision: manifest.revision } });
|
|
61
|
+
if (!committed.active) throw new Error('这个版本曾同步成功,但目前网站已使用其他版本;本次未覆盖线上数据。');
|
|
62
|
+
return { revision: manifest.revision, syncedAt: new Date().toISOString(), siteUrl: websiteOrigin(config.siteUrl) };
|
|
63
|
+
}
|