'use strict'; // 旧三人列继续逐值保留;新增员工的分摊单独保存,避免借用其他员工的列。 const LEGACY = ['owner', 'assistant', 'assistant2']; const isKey = value => LEGACY.includes(value) || (typeof value === 'string' && /^staff_[a-f0-9-]{36}$/.test(value)); function keys(...values) { const result = new Set(LEGACY); const visit = value => { if (Array.isArray(value)) { for (const row of value) visit(row); return; } if (!value || typeof value !== 'object') return; for (const [key, child] of Object.entries(value)) { if (['payer', 'materialOwner', 'member'].includes(key) && isKey(child)) result.add(child); if (key.endsWith('_amount') && isKey(key.slice(0, -7))) result.add(key.slice(0, -7)); if (child && typeof child === 'object') visit(child); } }; for (const value of values) visit(value); return [...result]; } function parts(row) { return ( row.allocations ?? keys(row) .map(payer => ({ payer, amount: row[payer + '_amount'] ?? 0 })) .filter(part => part.amount > 0) ); } function fields(allocations, amount, { third = true } = {}) { const members = keys(allocations), result = Object.fromEntries( members .filter(payer => payer !== 'assistant2' || third) .map(payer => [ payer + '_amount', amount === null ? null : allocations.filter(part => part.payer === payer).reduce((sum, part) => sum + part.amount, 0), ]), ); if (members.some(payer => !LEGACY.includes(payer))) result.allocations = allocations; return result; } function initialize(ledger) { ledger.db.exec( 'CREATE TABLE IF NOT EXISTS material_usage_allocations(usage_id TEXT PRIMARY KEY REFERENCES material_pool_usages(id),allocations TEXT NOT NULL)', ); } function read(ledger, id) { const row = ledger.one('SELECT allocations FROM material_usage_allocations WHERE usage_id=?', id); if (!row) return {}; const allocations = JSON.parse(row.allocations); return { allocations, ...fields(allocations, allocations.some(part => part.amount === null) ? null : 0) }; } function save(ledger, id, row) { const allocations = parts(row); if (!allocations.some(part => !LEGACY.includes(part.payer))) { ledger.run('DELETE FROM material_usage_allocations WHERE usage_id=?', id); return; } ledger.run( 'INSERT INTO material_usage_allocations VALUES (?,?) ON CONFLICT(usage_id) DO UPDATE SET allocations=excluded.allocations', id, JSON.stringify(allocations), ); } module.exports = { LEGACY, isKey, keys, parts, fields, initialize, read, save };