Files
weiguang-jewelry-ledger/新账系统/test/order-after-sale-core.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

535 lines
20 KiB
JavaScript

'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
{ randomUUID } = require('node:crypto');
const { Ledger, today } = require('../ledger');
const Rolling = require('../rolling-material-pools'),
After = require('../order-after-sales');
const D = today(),
P = new Date(Date.parse(D + 'T00:00:00Z') - 86400000).toISOString().slice(0, 10),
actor = { id: 'synthetic-after-core-owner', name: '合成售后经办', role: 'owner' };
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 + '" ORDER BY rowid')]),
);
function fixture(t) {
const l = new Ledger(':memory:');
t.after(() => l.close());
const run = (payload, fn, key = randomUUID()) => l.transact(key, actor, payload, fn);
run({}, () => l.stock({ kind: 'opening', date: P, pocket: '现货', grams: '10', note: '合成期初' }, actor));
const issue = (extra = {}, line = {}) => {
const input = {
date: P,
customer: '合成售后客户',
salesperson: '合成经办',
payment_account: '麦麦微信',
discount: '0',
lines: [
{
name: '足金合成项链',
code: 'A',
unit: 'g',
quantity: '2',
pocket: '现货',
payer: 'owner',
costParts: { material: '1200', labor: '50', accessories: '0', other: '0' },
costMaterial: { mode: 'total' },
costLabor: { mode: 'total' },
sale: '1419',
...line,
},
],
fee_items: [{ key: 'shipping', amount: '10', payer: 'owner', note: '原发货运费' }],
...extra,
};
return run(input, () => l.issueOrder(input, actor)).id;
};
const after = (id, extra = {}, row = {}) => {
const input = {
date: D,
revision: l.detail(id).revision,
verified: true,
reason: '合成实物退回',
afterSale: {
lines: [{ lineIndex: 0, quantity: '2', pocket: '回收旧料', disposition: 'scrap', ...row }],
refund: { amount: '1300', account: '麦麦微信', payer: 'owner' },
deductionReason: '实际扣除费用',
expenses: [],
...extra,
},
};
return run(input, () => l.action(id, 'return', input, actor));
};
const buy = (grams = '2', amount = '1200', date = D) =>
run({}, () => l.createMaterialPurchase({ date, grams, total: amount, payer: 'owner', note: '合成购料' }, actor));
return { l, run, issue, after, buy };
}
test('整单回旧料按实际退款计算最终59元,原日159元利润和原销售行保持,售后只调-100元', t => {
const f = fixture(t),
id = f.issue(),
original = f.l.detail(id),
journal = f.l.rows('SELECT * FROM journal WHERE order_id=?', id),
purchases = f.l.rows('SELECT * FROM material_purchases');
const result = f.after(id),
order = f.l.detail(id);
assert.equal(original.profit, 15900);
assert.equal(result.summary.retainedAmount, 11900);
assert.equal(result.summary.profit, 5900);
assert.equal(result.summary.profitAdjustment, -10000);
assert.equal(order.profit, 5900);
assert.equal(order.balance, 0);
assert.equal(order.status, 'returned');
assert.deepEqual(order.lines, original.lines);
assert.deepEqual(f.l.rows('SELECT * FROM journal WHERE order_id=? AND date=?', id, P), journal);
assert.equal(f.l.one('SELECT SUM(profit) AS p FROM journal WHERE order_id=? AND date=?', id, D).p, -10000);
assert.equal(f.l.materialPoolDetail(D).totalMg, 2000);
assert.equal(f.l.materialPoolDetail(D).totalAmount, 120000);
assert.deepEqual(f.l.rows('SELECT * FROM material_purchases'), purchases);
const before = contents(f.l);
assert.throws(() => f.after(id), /已完成|不能重复/);
assert.throws(
() =>
f.run({}, () => f.l.action(id, 'refund', { date: D, amount: '119', account: '麦麦微信', verified: true }, actor)),
/扣留款/,
);
assert.equal(contents(f.l), before);
});
test('完好现货保留50元工费,下次显式批次销售自动继承且只能整批使用,再售后产生新批次', t => {
const f = fixture(t),
id = f.issue();
f.after(id, {}, { pocket: '现货', disposition: 'stock' });
const source = f.l.detail(id);
assert.equal(source.profit, 10900);
assert.equal(source.orderAfterSale.summary.profitAdjustment, -5000);
const lot = f.l.returnedStockLots({}, actor).lots[0];
assert.equal(lot.laborCost, 5000);
assert.equal(lot.remainingMg, 2000);
const resale = f.issue(
{ date: D, fee_items: [] },
{
returnedStockId: lot.id,
costMaterial: { mode: 'pool', poolId: D },
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
sale: '1400',
},
),
order = f.l.detail(resale);
assert.equal(order.lines[0].costParts.labor, 5000);
assert.equal(order.goodsCost, 125000);
assert.equal(order.profit, 15000);
assert.equal(f.l.returnedStockLots({}, actor).lots.length, 0);
const before = contents(f.l);
assert.throws(
() =>
f.issue(
{ date: D, fee_items: [] },
{
returnedStockId: lot.id,
costMaterial: { mode: 'pool', poolId: D },
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
},
),
/已被其他/,
);
assert.equal(contents(f.l), before);
f.after(
resale,
{ refund: { amount: '1300', account: '麦麦微信', payer: 'owner' } },
{ pocket: '现货', disposition: 'stock' },
);
const next = f.l.returnedStockLots({}, actor).lots;
assert.equal(next.length, 1);
assert.notEqual(next[0].id, lot.id);
assert.equal(next[0].laborCost, 5000);
});
test('少退0.1克按原1200元的比例回1140元,60元金料损耗及旧料工费均保留为损失', t => {
const f = fixture(t),
id = f.issue(),
result = f.after(id, {}, { quantity: '1.900' }),
row = result.summary.lines[0];
assert.equal(row.materialReturnedCost, 114000);
assert.equal(row.materialLoss, 6000);
assert.equal(row.costLoss, 11000);
assert.equal(result.summary.profit, -100);
assert.equal(result.summary.profitAdjustment, -16000);
assert.equal(f.l.materialPoolDetail(D).totalMg, 1900);
assert.equal(f.l.materialPoolDetail(D).totalAmount, 114000);
assert.equal(f.l.inventory().find(row => row.pocket === '回收旧料').mg, 1900);
});
test('退款、费用、回料、对数、批次及审计末端异常全部原子回滚;同操作号重试不重复', t => {
const f = fixture(t),
id = f.issue(),
before = contents(f.l),
audit = f.l.audit;
f.l.audit = function (entity, action, ...args) {
if (action === '订单退货退款售后') throw new Error('合成末端异常');
return audit.call(this, entity, action, ...args);
};
assert.throws(
() =>
f.after(
id,
{ expenses: [{ amount: '8', payer: 'owner', note: '退件邮费' }] },
{ pocket: '现货', disposition: 'stock' },
),
/合成末端/,
);
assert.equal(contents(f.l), before);
f.l.audit = audit;
const input = {
date: D,
revision: f.l.detail(id).revision,
verified: true,
reason: '合成幂等',
afterSale: {
lines: [{ lineIndex: 0, quantity: '2', pocket: '回收旧料', disposition: 'scrap' }],
refund: { amount: '1300', account: '麦麦微信', payer: 'owner' },
deductionReason: '实际扣费',
expenses: [],
},
},
key = randomUUID();
const first = f.run(input, () => f.l.action(id, 'return', input, actor), key),
after = contents(f.l),
second = f.run(
input,
() => {
throw new Error('不应重做');
},
key,
);
assert.deepEqual(second, first);
assert.equal(contents(f.l), after);
});
test('同日池料售后保留原耗用成本,后续采购只重估余料和新销售,不回写已确认售后', t => {
const f = fixture(t);
f.buy('10', '6000');
const id = f.issue(
{ date: D, fee_items: [] },
{
costMaterial: { mode: 'pool', poolId: D },
costParts: { material: '', labor: '50', accessories: '0', other: '0' },
},
),
before = f.l.detail(id);
f.after(id, {}, { quantity: '1.900' });
const sale = f.l.detail(id),
record = sale.orderAfterSale;
f.buy('10', '10000');
assert.deepEqual(f.l.detail(id).lines, before.lines);
assert.deepEqual(f.l.detail(id).orderAfterSale, record);
assert.equal(f.l.detail(id).profit, sale.profit);
const pool = f.l.materialPoolDetail(D);
assert.equal(pool.totalMg, 21900);
assert.equal(pool.usedMg, 2000);
assert.equal(pool.consumedCost, 120000);
assert.equal(pool.remainingMg, 19900);
assert.equal(pool.remainingCost, 1594000);
const next = f.issue(
{ date: D, fee_items: [] },
{
costMaterial: { mode: 'pool', poolId: D },
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
sale: '2000',
},
),
actual = f.l.detail(next).lines[0].costParts.material;
assert.equal(actual, After.ratio(1594000, 2000, 19900));
assert.equal(f.l.detail(id).profit, sale.profit);
});
test('按对成品只恢复实际退回对数,回旧料不恢复成品对数', t => {
const f = fixture(t);
f.run({}, () =>
f.l.updatePocket(
'现货',
{ revision: f.l.pocket('现货').revision, countUnit: 'pair', initialCount: 10, countVerified: true },
actor,
),
);
const first = f.issue({ date: D }, { stockCount: 2 });
assert.equal(f.l.inventory().find(row => row.pocket === '现货').count, 8);
f.after(first, {}, { quantity: '1', pocket: '现货', disposition: 'stock', stockCount: 1 });
assert.equal(f.l.inventory().find(row => row.pocket === '现货').count, 9);
assert.equal(f.l.detail(first).orderAfterSale.summary.laborRestockedCost, 2500);
const second = f.issue({ date: D }, { stockCount: 2 });
f.after(second, {}, { pocket: '回收旧料', disposition: 'scrap' });
assert.equal(f.l.inventory().find(row => row.pocket === '现货').count, 7);
assert.equal(
f.l
.rows("SELECT id FROM movements WHERE order_id=? AND kind='return'", second)
.map(row => f.l.movementStockCount(row.id))[0],
null,
);
});
test('极小跨公私来源不能丢分厘,同来源零毫克片段可以归并且整数守恒', () => {
const line = {
quantity: 4,
costParts: { material: 400 },
materialPool: {
materialSources: [
{
kind: 'public',
member: null,
quantity: 1,
amount: 100,
allocations: [{ payer: 'owner', amount: 100 }],
batches: [],
},
{
kind: 'personal_recovery',
member: 'assistant',
quantity: 3,
amount: 300,
allocations: [{ payer: 'assistant', amount: 300 }],
batches: [],
},
],
},
};
assert.throws(() => After.returnedSources(line, 1), /克重过小/);
line.materialPool.materialSources[1].kind = 'public';
line.materialPool.materialSources[1].member = null;
const parts = After.returnedSources(line, 1);
assert.equal(
parts.reduce((n, row) => n + row.quantity, 0),
1,
);
assert.equal(
parts.reduce((n, row) => n + row.amount, 0),
100,
);
assert.equal(
parts.flatMap(row => row.allocations).reduce((n, row) => n + row.amount, 0),
100,
);
});
test('跨日滚动按原已确认成本比例回料,历史采购更正不改原日售后结论,重建不重复成本', t => {
const f = fixture(t),
purchase = f.buy('10', '6000', P),
env = { ...f.l.businessEnv(), today: () => P },
preview = Rolling.previewEnable(f.l, { date: P }, actor, env);
f.run({}, () => Rolling.enable(f.l, { date: P, revision: preview.revision, verified: true }, actor, env));
const id = Rolling.withHistorical(f.l, () =>
f.issue(
{},
{
costMaterial: { mode: 'pool', poolId: P },
costParts: { material: '', labor: '50', accessories: '0', other: '0' },
},
),
),
oldLines = f.l.detail(id).lines,
oldJournal = f.l.rows('SELECT * FROM journal WHERE order_id=? AND date=?', id, P);
f.after(id, {}, { quantity: '1.900', pocket: '现货', disposition: 'stock' });
const record = f.l.detail(id).orderAfterSale;
let pool = f.l.materialPoolDetail(D);
assert.equal(pool.opening.mg, 8000);
assert.equal(pool.opening.amount, 480000);
assert.equal(pool.totalMg, 9900);
assert.equal(pool.totalAmount, 594000);
assert.equal(pool.todayReturns.count, 1);
const edit = { revision: 1, date: P, grams: '10', total: '6200', payer: 'owner', note: '合成历史采购核实' };
f.run(edit, () =>
Rolling.withHistorical(f.l, () => {
f.l.editMaterialPurchase(purchase.id, edit, actor);
Rolling.rebuildFrom(f.l, P, actor, f.l.businessEnv());
return { id };
}),
);
pool = f.l.materialPoolDetail(D);
assert.equal(pool.opening.amount, 500000);
assert.equal(pool.totalAmount, 614000);
assert.equal(pool.todayReturns.amount, 114000);
assert.equal(pool.todayReturns.count, 1);
assert.equal(f.l.rows('SELECT * FROM material_rolling_returns WHERE order_id=?', id).length, 1);
assert.equal(f.l.rows('SELECT * FROM material_purchases').length, 1);
assert.deepEqual(f.l.detail(id).lines, oldLines);
assert.deepEqual(f.l.detail(id).orderAfterSale, record);
assert.deepEqual(f.l.rows('SELECT * FROM journal WHERE order_id=? AND date=?', id, P), oldJournal);
const before = contents(f.l),
invalid = { ...edit, revision: 2, total: '500' };
assert.throws(
() =>
f.run(invalid, () =>
Rolling.withHistorical(f.l, () => {
f.l.editMaterialPurchase(purchase.id, invalid, actor);
Rolling.rebuildFrom(f.l, P, actor, f.l.businessEnv());
return { id };
}),
),
/售后.*来源|已售后原单/,
);
assert.equal(contents(f.l), before);
});
test('旧独立日池售后回料只结转一次,显式启用滚动及反复读取不重复采购、原耗用或退款', t => {
const f = fixture(t),
id = f.issue(),
input = {
date: P,
revision: f.l.detail(id).revision,
verified: true,
reason: '合成历史退回',
afterSale: {
lines: [{ lineIndex: 0, quantity: '2', pocket: '现货', disposition: 'stock' }],
refund: { amount: '1300', account: '麦麦微信', payer: 'owner' },
deductionReason: '实际扣费',
expenses: [],
},
};
f.run(input, () => f.l.action(id, 'return', input, actor));
const old = f.l.detail(id),
lot = f.l.returnedStockLots({}, actor).lots[0];
assert.equal(lot.effectivePoolId, P);
assert.equal(f.l.materialPools({ date: P }).rows[0].totalMg, 2000);
const originalPayments = f.l.rows('SELECT * FROM payments'),
preview = f.l.rollingMaterialPreview({}, actor);
assert.equal(preview.canEnable, true);
assert.equal(preview.opening.mg, 2000);
assert.equal(preview.opening.amount, 120000);
f.run({}, () => f.l.enableRollingMaterial({ date: D, revision: preview.revision, verified: true }, actor));
assert.equal(f.l.materialPoolDetail(D).remainingMg, 2000);
assert.equal(f.l.materialPoolDetail(D).remainingCost, 120000);
assert.equal(f.l.returnedStockLots({}, actor).lots[0].effectivePoolId, D);
assert.deepEqual(f.l.rows('SELECT * FROM payments'), originalPayments);
assert.equal(f.l.rows('SELECT * FROM material_purchases').length, 0);
assert.deepEqual(f.l.detail(id), old);
const before = contents(f.l);
f.l.materialPools();
f.l.materialPoolDetail(P);
f.l.materialPoolDetail(D);
assert.equal(contents(f.l), before);
});
test('同一退回批次的两个草稿,首单确认后第二单不能再占用,退回原单扣留款双方结算闭环', t => {
const f = fixture(t),
id = f.issue();
f.after(id, {}, { pocket: '现货', disposition: 'stock' });
assert.equal(f.l.detail(id).settlementDue, 0);
const lot = f.l.returnedStockLots({}, actor).lots[0];
const make = () => {
const data = {
date: D,
customer: '合成批次预定',
salesperson: '合成经办',
discount: '0',
lines: [
{
name: lot.name,
code: lot.code,
unit: 'g',
quantity: '2',
pocket: lot.pocket,
payer: 'owner',
returnedStockId: lot.id,
costMaterial: { mode: 'pool', poolId: lot.effectivePoolId },
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
sale: '1400',
},
],
fee_items: [],
};
return f.run(data, () => f.l.saveOrder(data, actor)).id;
};
const first = make(),
second = make();
f.run({}, () => f.l.action(first, 'confirm', { date: D }, actor));
const before = contents(f.l);
assert.throws(() => f.run({}, () => f.l.action(second, 'confirm', { date: D }, actor)), /已被其他/);
assert.equal(contents(f.l), before);
});
test('混合个人回收料和公共料按原比例返还各自来源,再消耗时原批次不重复计已用量', t => {
const f = fixture(t),
actors = {
owner: actor,
assistant: { id: 'synthetic-core-assistant', name: '合成助理', role: 'assistant' },
assistant2: { id: 'synthetic-core-assistant2', name: '合成助理2', role: 'assistant' },
};
for (const [member, value] of Object.entries(actors)) {
f.l.run(
'INSERT INTO users VALUES (?,?,?,?,?)',
value.id,
value.name,
value.role,
'synthetic-salt',
'synthetic-hash',
);
f.l.bindMemberUser(value.id, member);
}
f.l.enableTeamMode();
const run = (input, fn) => f.l.scope(actor, () => f.run(input, fn));
const recoveryInput = {
mode: 'direct',
date: D,
member: 'assistant',
customer: '合成私料客户',
salesperson: '合成经办',
old_lines: [{ name: '足金旧料', incoming_weight: '2', melted_weight: '2', purity: '100' }],
buy_rate: '800',
payer: 'assistant',
payment_account: '助理微信',
verified: true,
};
const recovery = run(recoveryInput, () => f.l.createRecovery(recoveryInput, actor));
f.buy('2', '2000');
const preview = f.l.rollingMaterialPreview({}, actor);
run({}, () => f.l.enableRollingMaterial({ date: D, revision: preview.revision, verified: true }, actor));
const id = f.issue(
{ date: D, member: 'assistant' },
{
quantity: '3',
sale: '3500',
costMaterial: { mode: 'pool', poolId: D },
costParts: { material: '', labor: '50', accessories: '0', other: '0' },
},
),
original = f.l.detail(id);
assert.equal(original.lines[0].costParts.material, 260000);
const cash = f.l.rows('SELECT * FROM team_fund_cash WHERE kind=?', 'outlay'),
purchases = f.l.rows('SELECT * FROM material_purchases');
f.after(id, { refund: { amount: '3000', account: '麦麦微信', payer: 'owner' } }, { quantity: '2.700' });
const row = f.l.detail(id).orderAfterSale.lines[0];
assert.deepEqual(
row.materialSources.map(source => [source.kind, source.member, source.quantity, source.amount]),
[
['personal_recovery', 'assistant', 1800, 144000],
['public', null, 900, 90000],
],
);
assert.equal(row.materialReturnedCost, 234000);
assert.equal(f.l.detail(id).profit, 18000);
const pool = f.l.materialPoolDetail(D);
assert.equal(pool.remainingMg, 1900);
assert.equal(pool.remainingCost, 190000);
assert.equal(pool.personalPools.assistant.remainingMg, 1800);
assert.equal(pool.personalPools.assistant.remainingCost, 144000);
assert.deepEqual(f.l.rows('SELECT * FROM material_purchases'), purchases);
assert.deepEqual(f.l.rows('SELECT * FROM team_fund_cash WHERE kind=?', 'outlay'), cash);
const RM = require('../recovery-material');
assert.equal(RM.purchaseStatus(f.l, recovery.purchase_id).usedMg, 200);
const next = f.issue(
{ date: D, member: 'assistant', fee_items: [] },
{
quantity: '1.800',
sale: '2000',
costMaterial: { mode: 'pool', poolId: D },
costParts: { material: '', labor: '0', accessories: '0', other: '0' },
},
);
assert.equal(f.l.detail(next).lines[0].costParts.material, 144000);
assert.equal(RM.purchaseStatus(f.l, recovery.purchase_id).usedMg, 2000);
assert.equal(f.l.materialPoolDetail(D).personalPools.assistant.remainingMg, 0);
assert.equal(f.l.materialPoolDetail(D).remainingMg, 1900);
const before = contents(f.l),
cancel = {
revision: f.l.recoveryEdit(recovery.id, actor).revision,
reason: '合成已售后来源作废核验',
verified: true,
};
assert.throws(
() => run(cancel, () => f.l.cancelRecovery(recovery.id, cancel, actor)),
/已售后原单.*金料来源|售后.*原采购/,
);
assert.equal(contents(f.l), before);
});