Files
weiguang-jewelry-ledger/新账系统/domains/materials/material-member-amounts.js
T
黄健铭andClaude Opus 5.5 9ec37196d4 目录重组:后端按core/domains分领域存放(仅移动与更新引用)
- 50个后端模块用git mv移入core/与domains/<领域>/,入口server.js、launch.js、restore.js及server/原位不动
- 所有require路径由脚本按新旧位置统一换算(后端、server/、测试)
- 新增test/app-paths.test.js,锁定默认数据目录、public目录与飞书配置文件的绝对位置
- 维护与部署.md补充目录说明并更新模块路径

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 13:01:19 -08:00

69 lines
2.6 KiB
JavaScript

'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 };