Files
weiguang-jewelry-ledger/新账系统/test/material-pool-fifo.test.js
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

532 lines
23 KiB
JavaScript
Raw Normal View History

'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
{ randomUUID, createHash } = require('node:crypto');
const fs = require('node:fs'),
os = require('node:os'),
path = require('node:path'),
{ DatabaseSync } = require('node:sqlite');
const { Ledger } = require('../ledger'),
{ allocatePayers } = require('../material-pools'),
{ prepareStartupMigrations } = require('../server');
const D = '2026-09-28',
SALE = '2026-09-29',
DELIVERY = '2026-09-30';
const actor = { id: 'fifo-test-owner', name: '合成麦麦', role: 'owner' },
system = { id: 'fifo-test-system', name: '系统升级合成测试', role: 'system' };
const line = (extra = {}) => ({
name: '合成足金',
unit: 'g',
quantity: '1',
pocket: '',
payer: 'owner',
sale: '1200',
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
costMaterial: { mode: 'pool', poolId: D },
...extra,
});
const input = (lines = [line()], extra = {}) => ({
date: SALE,
customer: '合成客户',
salesperson: '合成开单人',
payment_account: '助理微信',
fee_items: [],
lines,
...extra,
});
const contents = l =>
JSON.stringify(
l
.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
.map(({ name }) => [name, l.rows('SELECT * FROM "' + name + '"')]),
);
const allocations = (l, id) => l.detail(id).lines.map(row => row.materialPool?.allocations);
const immutable = l =>
Object.fromEntries(
[
'material_purchases',
'material_pool_settlements',
'payments',
'expenses',
'after_sales',
'settlements',
'movements',
'journal',
'inventory_snapshots',
].map(table => [table, l.rows('SELECT * FROM ' + table + ' ORDER BY rowid')]),
);
const net = l =>
l.rows('SELECT id FROM orders').reduce((total, row) => total + l.detail(row.id).knownSettlementDue, 0) +
l.materialPoolSettlement().knownSettlementDue;
function conserves(pool) {
if (pool.status === 'pending') return;
assert.equal(pool.consumedCost + pool.remainingCost, pool.totalAmount);
for (const payer of ['owner', 'assistant']) {
const row = pool.byPayer[payer];
assert.equal(row.consumed + row.remaining, row.purchased);
assert.ok(row.consumed >= 0);
assert.ok(row.remaining >= 0);
}
}
function fixture(t, filename = ':memory:') {
const l = new Ledger(filename);
t.after(() => l.close());
const run = (payload, fn) => l.transact(randomUUID(), actor, payload, fn);
const buy = (grams, total, payer = 'owner', date = D) => {
const p = { date, grams, total, payer, note: '合成凭据' };
return run(p, () => l.createMaterialPurchase(p, actor));
};
const issue = (p = input()) => run(p, () => l.issueOrder(p, actor)).id;
const save = (p = input()) => run(p, () => l.saveOrder(p, actor)).id;
const action = (id, kind, p = {}) => run({ id, kind, p }, () => l.action(id, kind, { date: SALE, ...p }, actor));
const edit = (id, change) => {
const info = l.orderEdit(id, actor),
p = { ...info.inputs, ...change, revision: info.revision, reason: '合成核对更正', verified: true };
return run(p, () => l.editOrder(id, p, actor));
};
return { l, run, buy, issue, save, action, edit };
}
// 合成旧比例快照。只用于内存或 /tmp 测试库,固定金额便于独立验证升级结果。
function legacyAllocation(l, id, parts) {
const order = l.rawOrder(id);
parts.forEach(([ownerAmount, assistantAmount], index) => {
l.run(
'UPDATE material_pool_usages SET owner_amount=?,assistant_amount=? WHERE order_id=? AND line_index=?',
ownerAmount,
assistantAmount,
id,
index,
);
order.lines[index].materialPool.allocations = [
{ payer: 'owner', amount: ownerAmount },
{ payer: 'assistant', amount: assistantAmount },
].filter(part => part.amount > 0);
if (!order.lines[index].materialPool.allocations.length)
order.lines[index].materialPool.allocations = [{ payer: 'owner', amount: 0 }];
});
l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(order.lines), id);
}
test('整数分FIFO逐笔用完再用下一笔,可跨两人且再次轮回麦麦,不用克重或比例切垫款', () => {
const purchases = [
{ amount: 300000, payer: 'owner' },
{ amount: 200000, payer: 'assistant' },
{ amount: 100000, payer: 'owner' },
];
assert.deepEqual(allocatePayers(purchases, 0, 400000), {
owner_amount: 300000,
assistant_amount: 100000,
zero_payer: 'owner',
});
assert.deepEqual(allocatePayers(purchases, 400000, 150000), {
owner_amount: 50000,
assistant_amount: 100000,
zero_payer: 'assistant',
});
assert.deepEqual(allocatePayers(purchases, 500000, 100000), {
owner_amount: 100000,
assistant_amount: 0,
zero_payer: 'owner',
});
assert.deepEqual(allocatePayers(purchases, 300000, 0), {
owner_amount: 0,
assistant_amount: 0,
zero_payer: 'assistant',
});
assert.throws(() => allocatePayers(purchases, 600000, 1), /不足/);
assert.throws(() => allocatePayers(purchases, -1, 1), /无效/);
});
test('混合采购继续当天加权料费,单笔用料金额越过首笔垫款时拆成双方归属', t => {
const f = fixture(t);
f.buy('1', '500');
f.buy('9', '9500', 'assistant');
const id = f.issue(),
order = f.l.detail(id),
pool = f.l.materialPoolDetail(D);
assert.equal(order.goodsCost, 100000);
assert.equal(order.profit, 20000);
assert.equal(pool.averageRate, 100000);
assert.deepEqual(allocations(f.l, id)[0], [
{ payer: 'owner', amount: 50000 },
{ payer: 'assistant', amount: 50000 },
]);
assert.equal(pool.byPayer.owner.remaining, 0);
assert.equal(pool.byPayer.assistant.remaining, 900000);
conserves(pool);
});
test('同毫秒采购和耗用以rowid稳定排序,助理先买先用且不会依付款人归并批次', t => {
const f = fixture(t);
f.buy('1', '1000', 'assistant');
f.buy('1', '1000', 'owner');
f.buy('1', '1000', 'assistant');
f.l.run('UPDATE material_purchases SET created=?', '2026-09-28T00:00:00.000Z');
const ids = [f.issue(), f.issue(), f.issue()];
f.l.run('UPDATE material_pool_usages SET created=?', '2026-09-29T00:00:00.000Z');
const first = f.l.materialPoolDetail(D).purchases[0];
f.run(first, () =>
f.l.editMaterialPurchase(
first.id,
{ revision: first.revision, date: D, grams: '1', total: '1000', payer: 'assistant', note: '仅触发同毫秒重算' },
actor,
),
);
assert.deepEqual(
ids.map(id => allocations(f.l, id)[0]),
[
[{ payer: 'assistant', amount: 100000 }],
[{ payer: 'owner', amount: 100000 }],
[{ payer: 'assistant', amount: 100000 }],
],
);
conserves(f.l.materialPoolDetail(D));
});
test('料池响应提供跨池全局消耗序号,同毫秒仍按rowid排序,新增展示字段兼容旧版revision且读取无写入', t => {
const f = fixture(t),
otherDay = '2026-09-27';
f.buy('3', '3000');
f.buy('3', '3000', 'assistant', otherDay);
f.issue();
f.issue(input([line({ costMaterial: { mode: 'pool', poolId: otherDay } })]));
f.issue();
f.l.run('UPDATE material_pool_usages SET created=?', '2026-09-29T00:00:00.000Z');
const before = contents(f.l),
pools = [f.l.materialPoolDetail(D), f.l.materialPoolDetail(otherDay)];
for (const pool of pools) {
const legacyUsages = f.l
.rows(
`SELECT u.*,o.number,o.customer,o.status AS order_status,o.lines FROM material_pool_usages u JOIN orders o ON o.id=u.order_id WHERE u.pool_id=? ORDER BY u.created,u.rowid`,
pool.id,
)
.map(({ lines, ...row }) => ({ ...row, product: JSON.parse(lines)[row.line_index]?.name ?? '' }));
const legacyRevision = createHash('sha256')
.update(JSON.stringify({ purchases: pool.purchases, usages: legacyUsages, settlements: pool.settlements }))
.digest('hex');
assert.equal(pool.revision, legacyRevision);
assert.deepEqual(
pool.usages.map(row => ({ id: row.id, fifo_sequence: row.fifo_sequence })),
f.l
.rows(
'SELECT id,rowid AS fifo_sequence FROM material_pool_usages WHERE pool_id=? ORDER BY created,rowid',
pool.id,
)
.map(row => ({ ...row })),
);
}
const globalOrder = pools
.flatMap(pool => pool.usages)
.sort((a, b) => (a.created < b.created ? -1 : a.created > b.created ? 1 : a.fifo_sequence - b.fifo_sequence));
assert.deepEqual(
globalOrder.map(row => row.id),
f.l.rows('SELECT id FROM material_pool_usages ORDER BY created,rowid').map(row => row.id),
);
assert.equal(contents(f.l), before);
});
test('草稿多行共享累计加权分币和FIFO起点,零分行保留当前来源,预估不占用且正式结果一致', t => {
const f = fixture(t);
f.buy('0.002', '0.01');
f.buy('0.005', '0.03', 'assistant');
f.issue(input([line({ quantity: '0.001', sale: '1' })]));
const p = input(Array.from({ length: 6 }, () => line({ quantity: '0.001', sale: '1' }))),
before = contents(f.l);
const preview = f.l.validateLines(p.lines, [], SALE);
assert.deepEqual(
preview.map(row => row.costParts.material),
[0, 1, 0, 1, 0, 1],
);
assert.deepEqual(preview[0].materialPool.allocations, [{ payer: 'assistant', amount: 0 }]);
assert.equal(contents(f.l), before);
const draft = f.save(p);
assert.equal(f.l.materialPoolDetail(D).usedMg, 1);
const id = f.run(p, () => f.l.issueOrder({ ...p, id: draft, revision: f.l.rawOrder(draft).revision }, actor)).id;
assert.deepEqual(
allocations(f.l, id),
preview.map(row => row.materialPool.allocations),
);
assert.deepEqual(
f.l.detail(id).lines.map(row => row.costParts.material),
preview.map(row => row.costParts.material),
);
assert.equal(f.l.materialPoolDetail(D).remainingCost, 0);
conserves(f.l.materialPoolDetail(D));
});
test('同单多行合计缺料时预估全部待补,先出单后补购恢复,释放先单让后单承接首笔垫款', t => {
const f = fixture(t);
f.buy('2', '2000');
const preview = f.l.validateLines([line({ quantity: '2' }), line()], [], SALE);
assert.ok(preview.every(row => row.materialPool.status === 'pending' && row.costParts.material === null));
const first = f.issue(input([line({ quantity: '2', sale: '2400' })])),
second = f.issue();
assert.equal(f.l.detail(first).profit, null);
f.buy('1', '1000', 'assistant');
assert.deepEqual(allocations(f.l, second)[0], [{ payer: 'assistant', amount: 100000 }]);
f.action(first, 'return', { verified: true, reason: '合成退货', returnPockets: ['金料'] });
assert.deepEqual(allocations(f.l, second)[0], [{ payer: 'owner', amount: 100000 }]);
assert.equal(f.l.detail(second).goodsCost, 100000);
assert.equal(f.l.materialPoolDetail(D).byPayer.assistant.remaining, 100000);
conserves(f.l.materialPoolDetail(D));
});
test('满池整单编辑按原usage位置预估,重排删除新增换池与再次启用的结果和正式调整一致', t => {
const f = fixture(t);
f.buy('1', '500');
f.buy('3', '3500', 'assistant');
f.buy('2', '2000', 'assistant', '2026-09-27');
const first = f.issue(input([line(), line()])),
other = f.issue(input([line({ quantity: '2', sale: '2400' })]));
const snapshot = f.l.rawOrder(first),
preview = f.l.validateLines([line(), line()], snapshot.lines, SALE, { orderId: first });
assert.ok(preview.every(row => row.materialPool.status === 'preview'));
assert.deepEqual(
preview.map(row => row.materialPool.allocations),
allocations(f.l, first),
);
const changed = [
line({ quantity: '2', sale: '2400' }),
line({ costMaterial: { mode: 'pool', poolId: '2026-09-27' } }),
line({ quantity: '0.5', sale: '600' }),
];
const predicted = f.l.validateLines(changed, snapshot.lines, SALE, { orderId: first });
f.edit(first, { lines: changed });
assert.deepEqual(
allocations(f.l, first),
predicted.map(row => row.materialPool.allocations),
);
const restored = [line(), line()];
f.edit(first, { lines: [line()] });
const finalPreview = f.l.validateLines(restored, f.l.rawOrder(first).lines, SALE, { orderId: first });
f.edit(first, { lines: restored });
assert.deepEqual(
allocations(f.l, first),
finalPreview.map(row => row.materialPool.allocations),
);
assert.equal(f.l.detail(other).goodsCost, 200000);
conserves(f.l.materialPoolDetail(D));
});
test('补录、修改、软删除采购逐笔重算FIFO而不造实际流水,等价总额变动不改变成本利润', t => {
const f = fixture(t);
const first = f.buy('1', '1000');
f.buy('2', '2000', 'assistant');
const id = f.issue(input([line({ quantity: '1.5', sale: '1800' })]));
const order = f.l.detail(id),
cash = immutable(f.l);
f.buy('1', '1000');
assert.deepEqual(allocations(f.l, id)[0], [
{ payer: 'owner', amount: 100000 },
{ payer: 'assistant', amount: 50000 },
]);
const row = f.l.materialPurchaseDetail(first.id).purchase;
f.run(row, () =>
f.l.editMaterialPurchase(
row.id,
{ revision: row.revision, date: D, grams: '1', total: '1000', payer: 'assistant', note: '合成付款人更正' },
actor,
),
);
assert.deepEqual(allocations(f.l, id)[0], [{ payer: 'assistant', amount: 150000 }]);
f.run(row, () => f.l.deleteMaterialPurchase(row.id, { revision: row.revision + 1 }, actor));
assert.deepEqual(allocations(f.l, id)[0], [{ payer: 'assistant', amount: 150000 }]);
for (const table of ['payments', 'expenses', 'after_sales', 'settlements', 'movements', 'journal'])
assert.deepEqual(immutable(f.l)[table], cash[table]);
assert.equal(f.l.detail(id).goodsCost, order.goodsCost);
assert.equal(f.l.detail(id).profit, order.profit);
conserves(f.l.materialPoolDetail(D));
});
test('显式历史升级保留原采购实付库存利润与退货快照,重分有效旧单且所有相关财务日期需重核', t => {
const f = fixture(t);
f.buy('10', '9000');
f.buy('20', '18120', 'assistant');
const returned = f.issue(
input([line({ payer: 'assistant', costParts: { material: '', labor: '40', accessories: '0', other: '0' } })]),
);
f.action(returned, 'return', { verified: true, reason: '合成退货', returnPockets: ['金料'] });
f.action(returned, 'refund', { verified: true, amount: '1200', account: '助理微信' });
const first = f.issue(input([line({ quantity: '3', sale: '3000' })])),
second = f.issue(input([line({ quantity: '8', sale: '8000' })]));
legacyAllocation(f.l, first, [[90000, 181200]]);
legacyAllocation(f.l, second, [[240000, 483200]]);
f.l.run('UPDATE orders SET delivered_date=? WHERE id=?', DELIVERY, first);
f.l.run('UPDATE journal SET date=? WHERE order_id=?', DELIVERY, first);
f.action(first, 'settlement', {
date: DELIVERY,
verified: true,
bucket: 'cost',
amount: '100',
direction: 'toOwner',
note: '合成实际交款',
});
const pool = f.l.materialPoolDetail(D);
f.run(pool, () =>
f.l.settleMaterialPool(
D,
{
date: DELIVERY,
verified: true,
revision: pool.revision,
amount: '50',
direction: 'toAssistant',
note: '合成垫款实际返还',
},
actor,
),
);
for (const date of [D, SALE, DELIVERY])
f.run({ date }, () => f.l.closeDay(date, actor, date === DELIVERY ? undefined : 'orderDate'));
const financial = immutable(f.l),
oldReturned = f.l.detail(returned),
beforeNet = net(f.l),
audits = f.l.rows('SELECT * FROM audit'),
events = f.l.rows('SELECT * FROM material_pool_events');
const costs = [first, second].map(id => ({ id, goods: f.l.detail(id).goodsCost, profit: f.l.detail(id).profit }));
const result = f.l.migrateMaterialPoolAllocation(system, { backupName: '合成迁移前完整备份.sqlite' });
assert.equal(result.changed, true);
assert.equal(result.version, 2);
assert.equal(result.migration.changedUsageCount, 2);
assert.deepEqual(allocations(f.l, first)[0], [{ payer: 'owner', amount: 271200 }]);
assert.deepEqual(allocations(f.l, second)[0], [
{ payer: 'owner', amount: 628800 },
{ payer: 'assistant', amount: 94400 },
]);
assert.deepEqual(immutable(f.l), financial);
assert.deepEqual(f.l.detail(returned), oldReturned);
assert.equal(net(f.l), beforeNet);
for (const row of costs) {
assert.equal(f.l.detail(row.id).goodsCost, row.goods);
assert.equal(f.l.detail(row.id).profit, row.profit);
}
assert.equal(f.l.reportByOrderDate(SALE).close.stale, true);
assert.equal(f.l.report(DELIVERY).close.stale, true);
assert.equal(f.l.reportByOrderDate(D).close.stale, false, '只有采购的日期实付未变,保持原开单日财务哈希兼容');
assert.deepEqual(f.l.rows('SELECT * FROM audit').slice(0, audits.length), audits);
assert.deepEqual(f.l.rows('SELECT * FROM material_pool_events').slice(0, events.length), events);
const audit = f.l.rows('SELECT * FROM audit').at(-1);
assert.equal(audit.actor, system.name);
assert.equal(JSON.parse(audit.detail).backupName, '合成迁移前完整备份.sqlite');
assert.ok(f.l.one('SELECT revision FROM sync WHERE entity=?', 'order:' + first));
conserves(f.l.materialPoolDetail(D));
const frozen = contents(f.l);
assert.equal(f.l.migrateMaterialPoolAllocation(system).changed, false);
assert.equal(contents(f.l), frozen);
});
test('待补与零分旧单也能升级,零分来源改变留审计且pending仍无伪利润', t => {
const f = fixture(t);
f.buy('0.002', '0.01');
f.buy('0.005', '0.03', 'assistant');
const id = f.issue(input(Array.from({ length: 7 }, () => line({ quantity: '0.001', sale: '1' }))));
legacyAllocation(f.l, id, [
[0, 1],
[0, 0],
[0, 1],
[0, 0],
[1, 0],
[0, 0],
[0, 1],
]);
const pending = f.issue(input([line({ costMaterial: { mode: 'pool', poolId: '2026-09-27' } })]));
const profit = f.l.detail(id).profit,
netBefore = net(f.l);
const result = f.l.migrateMaterialPoolAllocation(system);
assert.equal(result.changed, true);
assert.equal(f.l.detail(id).profit, profit);
assert.equal(net(f.l), netBefore);
assert.deepEqual(allocations(f.l, id)[1], [{ payer: 'assistant', amount: 0 }]);
assert.equal(f.l.detail(pending).profit, null);
assert.equal(f.l.detail(pending).settlementDue, null);
assert.ok(
f.l
.rows("SELECT * FROM material_pool_events WHERE kind='垫付归属FIFO升级'")
.some(row => JSON.parse(row.after_value).allocations?.[0]?.amount === 0),
);
});
test('迁移核对或末尾审计故障全事务回滚,版本原样保留且可重试', t => {
const f = fixture(t);
f.buy('10', '9000');
f.buy('20', '18120', 'assistant');
const id = f.issue(input([line({ quantity: '3', sale: '3000' })]));
legacyAllocation(f.l, id, [[90000, 181200]]);
const before = contents(f.l),
audit = f.l.audit.bind(f.l);
f.l.audit = (...args) => {
if (args[0] === 'system:material-pool-allocation') throw new Error('合成审计故障');
return audit(...args);
};
assert.throws(() => f.l.migrateMaterialPoolAllocation(system), /合成审计故障/);
assert.equal(contents(f.l), before);
f.l.audit = audit;
const touch = f.l.touch.bind(f.l);
f.l.touch = orderId => {
touch(orderId);
f.l.run('UPDATE payments SET amount=amount+1 WHERE order_id=?', orderId);
};
assert.throws(() => f.l.migrateMaterialPoolAllocation(system), /核对未通过/);
assert.equal(contents(f.l), before);
f.l.touch = touch;
f.l.run('UPDATE material_pool_usages SET amount=amount+1 WHERE order_id=?', id);
const inconsistent = contents(f.l);
assert.throws(() => f.l.migrateMaterialPoolAllocation(system), /加权成本不一致/);
assert.equal(contents(f.l), inconsistent);
});
test('启动升级先写独立完整备份再迁移,重开构造不静默改历史,重启幂等且空库无额外备份', async t => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-fifo-startup-')),
file = path.join(dir, 'ledger.sqlite');
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
let l = new Ledger(file);
const p = { date: D, grams: '10', total: '9000', payer: 'owner', note: '合成' };
l.createMaterialPurchase(p, actor);
l.createMaterialPurchase({ ...p, grams: '20', total: '18120', payer: 'assistant' }, actor);
const id = l.transact(randomUUID(), actor, {}, () =>
l.issueOrder(input([line({ quantity: '3', sale: '3000' })]), actor),
).id;
legacyAllocation(l, id, [[90000, 181200]]);
const before = contents(l);
l.close();
l = new Ledger(file);
t.after(() => l.close());
assert.equal(contents(l), before);
assert.equal(l.materialPoolAllocationStatus().migrationRequired, true);
const result = await prepareStartupMigrations({ ledger: l, dataDir: dir });
const backups = fs.readdirSync(path.join(dir, 'backups')).filter(name => name.endsWith('.sqlite'));
assert.equal(backups.length, 1);
assert.match(backups[0], /^ledger-before-material-fifo-v2-/);
const check = new DatabaseSync(path.join(dir, 'backups', backups[0]), { readOnly: true });
try {
assert.equal(
check.prepare('SELECT owner_amount FROM material_pool_usages WHERE order_id=?').get(id).owner_amount,
90000,
);
assert.equal(
check.prepare('SELECT COUNT(*) AS count FROM meta WHERE key=?').get('material-pool-allocation-version').count,
0,
);
} finally {
check.close();
}
assert.equal(result.migration.backupName, backups[0]);
assert.equal(l.materialPoolAllocationStatus().migrationRequired, false);
const frozen = contents(l);
assert.equal((await prepareStartupMigrations({ ledger: l, dataDir: dir })).changed, false);
assert.equal(contents(l), frozen);
assert.equal(fs.readdirSync(path.join(dir, 'backups')).filter(name => name.endsWith('.sqlite')).length, 1);
const emptyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-fifo-empty-'));
t.after(() => fs.rmSync(emptyDir, { recursive: true, force: true }));
const empty = new Ledger(':memory:');
t.after(() => empty.close());
assert.equal((await prepareStartupMigrations({ ledger: empty, dataDir: emptyDir })).version, 2);
assert.equal(fs.existsSync(path.join(emptyDir, 'backups')), false);
});
test('升级前备份失败或无效时不执行迁移,历史账和版本完全不变', async t => {
const f = fixture(t);
f.buy('1', '1000');
f.issue();
const before = contents(f.l),
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-fifo-fail-'));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
f.l.backupTo = async () => {
throw new Error('合成磁盘故障');
};
await assert.rejects(prepareStartupMigrations({ ledger: f.l, dataDir: dir }), /合成磁盘故障/);
assert.equal(contents(f.l), before);
f.l.backupTo = async destination => {
fs.mkdirSync(path.dirname(destination), { recursive: true });
fs.writeFileSync(destination, '无效备份');
};
await assert.rejects(prepareStartupMigrations({ ledger: f.l, dataDir: dir }));
assert.equal(contents(f.l), before);
});