Files
leadboard/archive-store.js
2026-11-23 08:04:01 +00:00

54 lines
2.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 年度封存:年底(H2 定錨之後)把這一年的結果存成唯讀快照,之後可以切換年份查看。
// 存在 archives/<年>.json(leadboard.db 的 documents 表;STORAGE_BACKEND=json 時是 COST_MODEL_DATA_DIR/archives/ 資料夾)。封存後不能修改或覆蓋。
import { bindDirectory } from './storage.js';
const round = (value) => Math.round(Number(value) || 0);
// 只存部門、組的數字與定錨結果;個人資料不進封存。
export function buildArchive(model, anchors, { year, by, note, at }) {
return {
year, by, note: String(note || '').slice(0, 500), archivedAt: at,
calcVersion: model.calcVersion,
anchors: anchors?.anchors || [],
invoiceTotal: round(model.invoice?.finalInvoiceTotal),
depts: Object.entries(model.codaGroups || {}).map(([dept, data]) => ({
dept, company: model.deptCompany?.[dept] || '',
actualCoda: round(data.coda), avgDailyCoda: round(data.avgDailyCoda),
invoice: model.allocations?.deptData?.[dept] ? round(model.invoice.finalInvoiceTotal * (model.allocations.deptData[dept].finalPct || 0)) : null,
anchoredInvoice: anchors?.invoice?.[dept] ? { annual: round(anchors.invoice[dept].annual), h1: round(anchors.invoice[dept].h1), h2: anchors.invoice[dept].h2 === null ? null : round(anchors.invoice[dept].h2) } : null,
anchoredCoda: anchors?.coda?.[dept] ? { annual: round(anchors.coda[dept].value), h1: round(anchors.coda[dept].h1), h2: anchors.coda[dept].h2 === null ? null : round(anchors.coda[dept].h2) } : null,
groups: Object.entries(data.groups).map(([group, g]) => ({
group, actualCoda: round(g.coda), avgDailyCoda: round(g.avgDailyCoda),
anchoredCoda: anchors?.coda?.[dept]?.groups?.[group] ? round(anchors.coda[dept].groups[group].value) : null,
})),
})),
};
}
export function createArchiveStore(source) {
const memory = new Map();
const storage = bindDirectory(source);
const name = (year) => `${Number(year)}.json`;
return {
async list() {
if (!storage) return [...memory.keys()].sort();
return storage.list().map(entry => /^(\d{4})\.json$/.exec(entry)?.[1]).filter(Boolean).map(Number).sort();
},
async get(year) {
if (!storage) return memory.get(Number(year)) || null;
const text = storage.read(name(year));
return text === null ? null : JSON.parse(text);
},
async save(archive) {
const year = Number(archive.year);
if (!Number.isInteger(year)) throw new RangeError('invalid year');
if (await this.get(year)) throw new RangeError(`${year} already archived`);
if (!storage) { memory.set(year, archive); return; }
try { storage.write(name(year), `${JSON.stringify(archive)}\n`, { exclusive: true }); } catch (error) {
if (error.code === 'EEXIST') throw new RangeError(`${year} already archived`);
throw error;
}
},
};
}