Files
weiguang-jewelry-ledger/新账系统/test/price-lock-pool-order-edit.test.js
T
黄健铭andClaude Opus 5.5 28c64814f0 格式化:Prettier统一代码风格(仅格式,无逻辑变化)
仅为 npm run format 的输出;黄金对照、旧库兼容、浏览器流程与单元测试全部通过且零差异。

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

435 lines
18 KiB
JavaScript

'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
{ randomUUID } = require('node:crypto');
const { Ledger, today, day, money, weight, text, fail, ACCOUNTS, ACTIVE_POCKETS } = require('../ledger'),
{ createUser } = require('../server');
const Rolling = require('../rolling-material-pools'),
Locks = require('../price-locks'),
Pools = require('../price-lock-pools'),
Calc = require('../public/calculations');
const D = today(),
previous = (date, n = 1) => new Date(Date.parse(date + 'T12:00:00Z') - n * 86400000).toISOString().slice(0, 10),
P = previous(D),
P2 = previous(D, 2);
function fixture(t) {
const l = new Ledger(':memory:');
t.after(() => l.close());
const actors = {};
for (const member of ['owner', 'assistant', 'assistant2']) {
const role = member === 'owner' ? 'owner' : 'assistant',
name = '合成池改单' + member;
actors[member] = { id: createUser(l, name, role, 'synthetic-lock-pool-edit-password', member), name, role, member };
}
l.enableTeamMode();
const env = {
day,
money,
weight,
text,
fail,
accounts: ACCOUNTS,
pockets: ACTIVE_POCKETS,
selfPockets: ['现货', '金料', '回收旧料'],
today: () => D,
now: () => new Date().toISOString(),
orderIdentity: (value, name, max) => text(value, name, max),
pick: (value, choices, name) => (choices.includes(value) ? value : fail(name + '无效')),
};
const run = (fn, member = 'owner') => l.scope(actors[member], () => l.transact(randomUUID(), actors[member], {}, fn));
const historic = fn => Rolling.withHistorical(l, fn);
const buy = (grams, total, date = D, payer = 'owner') =>
run(() => historic(() => l.createMaterialPurchase({ date, grams, total, payer, note: '合成购料' }, actors.owner)));
const enable = date => {
const e = { ...env, today: () => date },
preview = Rolling.previewEnable(l, { date }, actors.owner, e);
return run(() => Rolling.enable(l, { date, revision: preview.revision, verified: true }, actors.owner, e));
};
const lock = (grams = '1.500', date = D) => {
const e = { ...env, today: () => date },
pool = l.materialPoolDetail(date),
input = {
date,
customer: '合成客户',
salesperson: '合成开单人',
line: { name: '足金999挂件', unit: 'g', quantity: grams, goldPrice: '2000', laborRate: '0', laborMode: 'gram' },
material: { source: 'pool', poolId: date, revision: pool.revision },
payment: { amount: String(Number(grams) * 2000), account: '助理微信', verified: true },
};
return run(() => historic(() => Locks.create(l, input, actors.assistant, e)), 'assistant');
};
const deliver = (id, grams, date = D, extra = {}) => {
const lock = l.priceLockDetail(id),
total = Calc.orderTotal([Math.round(Number(grams) * 200000)], 0, 'yuan').total,
diff = total - lock.netReceived,
input = {
date,
revision: lock.revision,
verified: true,
line: {
quantity: grams,
laborRate: '0',
laborMode: 'gram',
payer: 'assistant',
costParts: { labor: '0', accessories: '0', other: '0' },
costPayers: { material: 'owner', labor: 'assistant' },
},
discount: '0',
inventory: { pocket: '现货', original: 'stocked' },
settlement: { amount: (Math.abs(diff) / 100).toFixed(2), account: '助理微信', verified: true },
fee_items: [],
...extra,
};
return run(() => historic(() => l.deliverPriceLock(id, input, actors.owner))).id;
};
const issue = (grams, date = D) => {
const input = {
date,
customer: '合成普通客户',
salesperson: '合成',
payment_account: '麦麦微信',
rounding_mode: 'cent',
lines: [
{
name: '足金999',
unit: 'g',
quantity: grams,
pocket: '现货',
payer: 'owner',
sale: String(Number(grams) * 2000),
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
costMaterial: { mode: 'pool', poolId: date },
},
],
fee_items: [],
};
return run(() => historic(() => l.issueOrder(input, actors.owner))).id;
};
run(() => l.stock({ date: P2, kind: 'opening', pocket: '现货', grams: '100', note: '合成库存' }, actors.owner));
return { l, actors, env, run, historic, buy, enable, lock, deliver, issue };
}
function facts(l) {
return JSON.stringify(
l
.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name")
.map(({ name }) => [name, l.rows('SELECT * FROM "' + name + '" ORDER BY rowid')]),
);
}
function flows(l) {
return Object.fromEntries(
['material_purchases', 'price_lock_events', 'payments', 'expenses', 'movements', 'team_fund_cash'].map(table => [
table,
l.rows('SELECT * FROM ' + table + ' ORDER BY rowid'),
]),
);
}
function manualLine(l, lockId, amount = 70000) {
const lock = l.one('SELECT * FROM price_locks WHERE id=?', lockId),
order = l.rawOrder(lock.final_order_id),
line = order.lines[0];
delete line.priceLockPool;
delete line.materialAllocations;
line.costMaterial = { mode: 'gram', rate: amount * 2 };
line.costParts.material = amount;
line.cost = Object.values(line.costParts).reduce((a, b) => a + b, 0);
l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(order.lines), order.id);
l.run('UPDATE price_locks SET buy_rate=?,material_amount=? WHERE id=?', amount * 2, amount * 3, lockId);
return order.lines;
}
function assertNoPoolRelations(l, lockId, reservation, rows) {
assert.equal(Pools.find(l, lockId), null);
assert.deepEqual(l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?', lockId), []);
assert.equal(
l.one("SELECT * FROM material_usage_order WHERE kind='priceLock' AND source_id=?", reservation.id),
undefined,
);
for (const row of rows)
assert.equal(
l.one("SELECT * FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?", row.id),
undefined,
);
}
function move(f, id, date) {
return f.run(() => f.historic(() => Pools.moveDeliveryDate(f.l, id, date, f.actors.owner, f.env)));
}
test('池锁改独立料价完整释放预留、余料及FIFO身份,保留手填值和真实流水', t => {
const f = fixture(t);
f.buy('0.800', '800', D, 'assistant');
f.buy('1.200', '1200');
f.enable(D);
const lock = f.lock(),
id = f.deliver(lock.id, '0.500'),
reservation = Pools.find(f.l, lock.id),
rows = f.l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?', lock.id),
actual = flows(f.l);
let wanted;
const result = f.run(() => {
wanted = manualLine(f.l, lock.id);
return Pools.releaseForOrderEdit(f.l, lock.id, f.actors.owner, f.env, { skipJournalOrder: id });
});
assert.equal(result.released, true);
assert.deepEqual(result.affectedDates, [D]);
assert.equal(result.earliestDate, D);
assertNoPoolRelations(f.l, lock.id, reservation, rows);
assert.deepEqual(f.l.rawOrder(id).lines, wanted);
assert.equal(f.l.one('SELECT material_amount FROM price_locks WHERE id=?', lock.id).material_amount, 210000);
const pool = f.l.materialPools().current;
assert.equal(pool.totalMg, 2000);
assert.equal(pool.usedMg, 0);
assert.equal(pool.remainingCost, 200000);
assert.deepEqual(flows(f.l), actual);
assert.equal(
f.l
.rows(
"SELECT * FROM team_fund_entries WHERE source_kind='price_lock' AND source_id=? AND kind='material_usage'",
lock.id,
)
.reduce((sum, row) => sum + row.amount, 0),
0,
);
assert.equal(f.l.one('PRAGMA integrity_check').integrity_check, 'ok');
assert.deepEqual(f.l.rows('PRAGMA foreign_key_check'), []);
});
test('跨日池锁改独立料价从原池重建结转,移除全部余料与退货回料而不重复现金', t => {
const f = fixture(t);
f.buy('0.800', '800', P2, 'assistant');
f.buy('1.200', '1200', P2);
f.enable(P2);
const lock = f.lock('1.500', P2),
id = f.deliver(lock.id, '0.500', P);
f.run(() =>
f.l.action(
id,
'return',
{ date: D, verified: true, reason: '合成实物退回', returnPockets: ['金料'] },
f.actors.owner,
),
);
const reservation = Pools.find(f.l, lock.id),
rows = f.l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?', lock.id),
actual = flows(f.l);
assert.deepEqual(rows.map(row => row.kind).sort(), ['goods', 'leftover']);
const result = f.run(() =>
f.historic(() => {
manualLine(f.l, lock.id);
return Pools.releaseForOrderEdit(f.l, lock.id, f.actors.owner, f.env, { skipJournalOrder: id });
}),
);
assert.deepEqual(result.affectedDates, [P2, P, D]);
assertNoPoolRelations(f.l, lock.id, reservation, rows);
const pool = f.l.materialPools().current;
assert.equal(pool.totalMg, 2000);
assert.equal(pool.totalAmount, 200000);
assert.equal(pool.remainingCost, 200000);
assert.deepEqual(flows(f.l), actual);
});
test('补重池锁解除时额外退料身份也完整释放,手动补重采购事件和实际支出仍只保留原笔', t => {
const f = fixture(t);
f.buy('2.000', '2000', P);
f.enable(P);
const lock = f.lock('1.500', P),
id = f.deliver(lock.id, '1.700', D, {
extraMaterial: { rate: '1200', payer: 'assistant2', verified: true },
inventory: { pocket: '现货', original: 'stocked', extra: 'receive' },
});
f.run(() =>
f.l.action(
id,
'return',
{ date: D, verified: true, reason: '合成补重退回', returnPockets: ['金料'] },
f.actors.owner,
),
);
const reservation = Pools.find(f.l, lock.id),
rows = f.l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?', lock.id),
actual = flows(f.l);
assert.deepEqual(rows.map(row => row.kind).sort(), ['extra', 'goods']);
f.run(() => f.historic(() => Pools.releaseForOrderEdit(f.l, lock.id, f.actors.owner, f.env)));
assertNoPoolRelations(f.l, lock.id, reservation, rows);
assert.deepEqual(flows(f.l), actual);
assert.equal(f.l.materialPools().current.remainingMg, 2000);
assert.equal(f.l.materialPools().current.remainingCost, 200000);
});
test('跨日挪交付日沿同一余料来源移日,冻结原锁价分厘与付款归属并重算下游', t => {
const f = fixture(t);
f.buy('0.800', '800', P2, 'assistant');
f.buy('1.200', '1200', P2);
f.enable(P2);
const lock = f.lock('1.500', P2),
id = f.deliver(lock.id, '0.500', P);
f.buy('1.000', '2000', P);
const old = f.issue('0.500', P);
f.buy('1.000', '3000');
const next = f.issue('0.500');
const reservation = Pools.find(f.l, lock.id),
line = f.l.rawOrder(id).lines[0],
before = f.l.one('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?', lock.id),
source = f.l.one("SELECT * FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?", before.id),
origin = f.l.one('SELECT * FROM material_rolling_days WHERE date=?', P2),
actual = flows(f.l);
const changed = move(f, lock.id, D);
const after = f.l.one('SELECT * FROM price_lock_pool_returns WHERE id=?', before.id);
assert.deepEqual(changed.affectedDates, [P, D]);
assert.deepEqual(f.l.one('SELECT * FROM material_rolling_days WHERE date=?', P2), origin);
assert.equal(after.date, D);
assert.equal(after.same_day, 0);
assert.equal(after.amount, 100000);
assert.deepEqual(JSON.parse(after.allocations), JSON.parse(before.allocations));
assert.deepEqual(
f.l.one("SELECT * FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?", before.id),
source,
);
assert.deepEqual(Pools.find(f.l, lock.id), reservation);
assert.deepEqual(f.l.rawOrder(id).lines[0], line);
assert.equal(JSON.parse(f.l.one('SELECT delivery FROM price_locks WHERE id=?', lock.id).delivery).date, D);
assert.equal(f.l.detail(old).goodsCost, 83333);
assert.equal(f.l.detail(next).goodsCost, 94445);
assert.equal(f.l.materialPools().current.remainingCost, 472222);
assert.deepEqual(flows(f.l), actual);
});
test('同日与跨日来回挪交付保持冻结成本的每一分,后续FIFO精确重算且早于受影响日的快照不变', t => {
const f = fixture(t);
f.enable(P2);
f.buy('0.800', '800.01', P, 'assistant');
f.buy('2.200', '4200.01', P);
const prefix = f.issue('0.200', P),
lock = f.lock('1.500', P),
id = f.deliver(lock.id, '1.000', P),
next = f.issue('0.500', P);
f.buy('1.000', '1000');
const reservation = Pools.find(f.l, lock.id),
line = f.l.rawOrder(id).lines[0],
returnBefore = f.l.one('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?', lock.id),
dayBefore = f.l.one('SELECT * FROM material_rolling_days WHERE date=?', P2),
actual = flows(f.l),
poolBefore = f.l.materialPools().current;
assert.equal(line.costParts.material, 166668);
assert.equal(returnBefore.amount, 83333);
assert.equal(f.l.detail(next).goodsCost, 83333);
move(f, lock.id, D);
assert.equal(f.l.one('SELECT same_day FROM price_lock_pool_returns WHERE id=?', returnBefore.id).same_day, 0);
assert.equal(f.l.detail(next).goodsCost, 83334);
assert.equal(f.l.detail(prefix).goodsCost, 33333);
assert.deepEqual(Pools.find(f.l, lock.id), reservation);
assert.deepEqual(f.l.rawOrder(id).lines[0], line);
assert.deepEqual(f.l.one('SELECT * FROM material_rolling_days WHERE date=?', P2), dayBefore);
move(f, lock.id, P);
assert.equal(f.l.one('SELECT same_day FROM price_lock_pool_returns WHERE id=?', returnBefore.id).same_day, 1);
assert.equal(f.l.detail(next).goodsCost, 83333);
assert.deepEqual(Pools.find(f.l, lock.id), reservation);
assert.deepEqual(f.l.rawOrder(id).lines[0], line);
const pool = f.l.materialPools().current;
for (const field of ['totalMg', 'totalAmount', 'usedMg', 'remainingMg', 'remainingCost'])
assert.equal(pool[field], poolBefore[field]);
assert.deepEqual(flows(f.l), actual);
assert.deepEqual(f.l.one('SELECT * FROM material_rolling_days WHERE date=?', P2), dayBefore);
});
test('同日余料已被后单使用时拒绝挪到跨日,目标冻结值和所有试算写入均完整回滚', t => {
const f = fixture(t);
f.buy('2.000', '2000', P);
f.enable(P);
const lock = f.lock('1.500', P);
f.deliver(lock.id, '0.500', P);
f.issue('1.000', P);
f.buy('1.000', '1000');
const before = facts(f.l);
assert.throws(
() => move(f, lock.id, D),
error => error.status === 409 && /余料已被其他订单使用/.test(error.message),
);
assert.equal(facts(f.l), before);
assert.equal(f.l.rollingHistorical, undefined);
assert.equal(f.l.rollingRebuilding, undefined);
});
test('余料挪到尚无记录的中间营业日时补齐冻结结转日,后续余额与原锁价成本守恒', t => {
const f = fixture(t);
f.buy('3.000', '3000', P2);
f.enable(P2);
const lock = f.lock('1.500', P2),
id = f.deliver(lock.id, '1.000', P2);
f.buy('1.000', '1000');
const snapshot = Pools.find(f.l, lock.id),
line = f.l.rawOrder(id).lines[0];
assert.equal(f.l.one('SELECT * FROM material_rolling_days WHERE date=?', P), undefined);
move(f, lock.id, P);
const intermediate = f.l.one('SELECT * FROM material_rolling_days WHERE date=?', P),
pool = Rolling.readPool(f.l, P, f.env, { internal: true });
assert.equal(intermediate.frozen, 1);
assert.equal(pool.totalMg, 2000);
assert.equal(pool.remainingCost, 200000);
assert.equal(f.l.materialPools().current.remainingMg, 3000);
assert.equal(f.l.materialPools().current.remainingCost, 300000);
assert.deepEqual(Pools.find(f.l, lock.id), snapshot);
assert.deepEqual(f.l.rawOrder(id).lines[0], line);
assert.equal(f.l.one('SELECT date FROM price_lock_pool_returns WHERE price_lock_id=?', lock.id).date, P);
});
test('历史释放和移日不自行授予权限,助理、未复核owner和无权成员均不能绕过', t => {
const f = fixture(t);
f.buy('2.000', '2000', P);
f.enable(P);
const lock = f.lock('1.500', P);
f.deliver(lock.id, '0.500');
const before = facts(f.l);
for (const fn of [
() => Pools.releaseForOrderEdit(f.l, lock.id, f.actors.owner, f.env),
() => Pools.moveDeliveryDate(f.l, lock.id, P, f.actors.owner, f.env),
() => f.historic(() => Pools.releaseForOrderEdit(f.l, lock.id, f.actors.assistant, f.env)),
])
assert.throws(fn, /冻结|复核/);
assert.throws(
() => f.historic(() => Pools.releaseForOrderEdit(f.l, lock.id, f.actors.assistant2, f.env)),
error => error.status === 404,
);
assert.equal(facts(f.l), before);
assert.equal(f.l.rollingHistorical, undefined);
});
test('池关系重建中途异常及外层试算保存点均还原全表与序号,权限标志随异常恢复', t => {
const f = fixture(t);
f.buy('0.800', '800', P, 'assistant');
f.buy('1.200', '1200', P);
f.enable(P);
const lock = f.lock('1.500', P);
f.deliver(lock.id, '1.000', P);
f.issue('0.500', P);
f.buy('1.000', '1000');
const before = facts(f.l),
audit = f.l.audit;
f.l.audit = function (entity, action, ...rest) {
audit.call(this, entity, action, ...rest);
if (action === '滚动日料池自动重算') throw new Error('合成池关系重建中断');
};
assert.throws(
() => f.historic(() => Pools.releaseForOrderEdit(f.l, lock.id, f.actors.owner, f.env)),
/合成池关系重建中断/,
);
assert.equal(facts(f.l), before);
assert.equal(f.l.rollingHistorical, undefined);
assert.equal(f.l.rollingRebuilding, undefined);
f.l.audit = audit;
for (const fn of [
() => Pools.releaseForOrderEdit(f.l, lock.id, f.actors.owner, f.env),
() => Pools.moveDeliveryDate(f.l, lock.id, D, f.actors.owner, f.env),
]) {
f.l.db.exec('SAVEPOINT synthetic_pool_edit_preview');
try {
f.historic(fn);
assert.notEqual(facts(f.l), before);
} finally {
f.l.db.exec('ROLLBACK TO synthetic_pool_edit_preview');
f.l.db.exec('RELEASE synthetic_pool_edit_preview');
}
assert.equal(facts(f.l), before);
assert.equal(f.l.rollingHistorical, undefined);
assert.equal(f.l.rollingRebuilding, undefined);
}
});