'use strict'; const { test } = require('node:test'), assert = require('node:assert/strict'), { randomUUID } = require('node:crypto'), fs = require('node:fs'), os = require('node:os'), path = require('node:path'); const { Ledger, today } = require('../ledger'), { createApp } = require('../server'); const D = '2026-10-20', D2 = '2026-10-21', old = (grams = '10', purity = '100') => [{ name: '合成旧料', incoming_weight: grams, melted_weight: grams, purity }]; const direct = (extra = {}) => ({ mode: 'direct', date: D, customer: '合成回收客户', salesperson: '合成经办', old_lines: old(), buy_rate: '900', payer: 'owner', payment_account: '麦麦微信', verified: true, ...extra, }); const exchange = (extra = {}, line = {}) => direct({ mode: 'exchange', old_lines: old('20'), exchange: { name: '足金合成新货', quantity: '30', pocket: '现货', gold_price: '1000', labor_rate: '20', labor_mode: 'gram', depreciation_rate: '10', cost_material: { mode: 'gram', rate: '900' }, cost_labor: { mode: 'gram', rate: '5' }, cost_payer: 'owner', discount: '0', rounding_mode: 'cent', ...line, }, ...extra, }); function fixture(t) { const l = new Ledger(':memory:'), actors = {}; t.after(() => l.close()); for (const member of ['owner', 'assistant', 'assistant2']) { const actor = { id: randomUUID(), name: '合成' + member, role: member === 'owner' ? 'owner' : 'assistant' }; actors[member] = actor; l.run('INSERT INTO users VALUES (?,?,?,?,?)', actor.id, actor.name, actor.role, 'synthetic-salt', 'synthetic-hash'); l.bindMemberUser(actor.id, member); } l.enableTeamMode(); const run = (body, fn, member = 'owner', key = randomUUID()) => l.scope(actors[member], () => l.transact(key, actors[member], body, fn)); const create = (body = direct(), member = 'assistant') => run(body, () => l.createRecovery(body, actors[member]), member); const info = (id, member = 'owner') => l.recoveryEdit(id, actors[member]); const update = (id, extra = {}, member = 'owner', key = randomUUID()) => { const value = { ...info(id, member).inputs, revision: info(id, member).revision, reason: '合成更正原因', ...extra }; return run({ id, value }, () => l.updateRecovery(id, value, actors[member]), member, key); }; const cancel = (id, extra = {}, member = 'owner') => { const value = { revision: info(id, member).revision, reason: '合成录错取消', verified: true, ...extra }; return run({ id, value }, () => l.cancelRecovery(id, value, actors[member]), member); }; const approve = (request, extra = {}, key = randomUUID()) => { const value = { revision: request.revision, verified: true, ...extra }; return run({ id: request.id, value }, () => l.approveRecoveryChange(request.id, value, actors.owner), 'owner', key); }; const reject = request => run({ reject: request.id }, () => l.rejectRecoveryChange(request.id, { revision: request.revision, note: '合成驳回' }, actors.owner), ); const stock = (date = D) => run({ date }, () => l.stock({ date, kind: 'opening', pocket: '现货', grams: '100', note: '合成库存' }, actors.owner), ); const funds = () => l.teamFunds({ from: D, to: today() }, actors.owner), report = date => l.asActor(actors.owner).reportFor({ date, basis: 'orderDate' }, actors.owner); return { l, actors, run, create, info, update, cancel, approve, reject, stock, funds, report }; } const contents = ( l, tables = l.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(r => r.name), ) => JSON.stringify(tables.map(table => [table, l.rows('SELECT * FROM "' + table + '"')])); const financial = [ 'recoveries', 'material_purchases', 'recovery_purchase_sources', 'material_pool_usages', 'payments', 'expenses', 'journal', 'movements', 'team_fund_sources', 'team_fund_entries', 'team_fund_cash', 'closes', 'inventory_snapshots', ]; test('逐件置换独立补金和余料,保存修改取消均守恒', t => { const f = fixture(t); f.stock(); const a = exchange( { old_lines: old('10'), old_pocket: '找金' }, { quantity: '15', gold_price: '1000', cost_material: { mode: 'gram', rate: '800' } }, ), b = exchange( { old_lines: old('20'), buy_rate: '850' }, { quantity: '12', pocket: '', gold_price: '1100', labor_rate: '30', depreciation_rate: '5', cost_labor: { mode: 'total', amount: '60' }, cost_labor_payer: 'assistant2', }, ); const input = { ...a, member: 'assistant', exchange: { items: [a, b], charges: [], fee_items: [], discount: '0', rounding_mode: 'cent' }, }; const result = f.create(input); assert.equal(result.differenceMg, 5000); assert.equal(result.surplusMg, 8000); assert.equal(result.goldAmount, 500000); assert.equal(result.laborAmount, 66000); assert.equal(result.depreciationAmount, 16000); assert.equal(result.purchaseAmount, 680000); assert.equal(result.netSettlement, -98000); assert.equal(result.materialCost, 400000); assert.equal(result.laborCost, 13500); assert.equal(f.l.detail(result.order_id).lines.length, 2); assert.equal(f.l.inventory().find(p => p.pocket === '找金').mg, 10000); assert.equal(f.l.inventory().find(p => p.pocket === '现货').mg, 85000); const saved = f.info(result.id).inputs; assert.equal(saved.exchange.items[1].exchange.depreciation_rate, '5.00'); assert.equal(saved.exchange.items[1].exchange.pocket, ''); saved.exchange.items[0].exchange.gold_price = '1200'; const edited = f.update(result.id, saved); assert.equal(edited.recovery.netSettlement, 2000); assert.equal(f.l.inventory().find(p => p.pocket === '现货').mg, 85000); f.cancel(result.id); assert.equal(f.l.inventory().find(p => p.pocket === '现货').mg, 100000); assert.equal(f.l.inventory().find(p => p.pocket === '找金').mg, 0); const pub = f.l.publicRecovery(result.id, f.actors.owner); assert.equal(pub.exchange_items.length, 2); assert.equal(JSON.stringify(pub).includes('costMaterial'), false); }); test('逐件共享料池必须合并试算,同一笔余料不能被两件重复使用', t => { const f = fixture(t); f.stock(); const p = { date: D, grams: '5', total: '4500', payer: 'owner' }; f.run(p, () => f.l.createMaterialPurchase(p, f.actors.owner)); const row = exchange( { old_lines: old('2') }, { quantity: '5', cost_material: { mode: 'pool', poolId: D }, cost_labor: { mode: 'total', amount: '0' } }, ), input = { ...row, member: 'assistant', exchange: { items: [row, row], discount: '0', rounding_mode: 'cent' } }; const preview = f.l.recoveryQuote(input, f.actors.owner); assert.equal(preview.differenceMg, 6000); assert.equal(preview.materialCost, null); assert.equal(preview.profit, null); const created = f.create(input); assert.equal(created.materialCost, null); assert.equal( f.l.rows('SELECT SUM(mg) AS mg FROM material_pool_usages WHERE order_id=? AND active=1', created.order_id)[0].mg, 6000, ); f.cancel(created.id); assert.equal(f.l.materialPoolDetail(D).usedMg, 0); }); test('逐件独立料源保留个人优先、公用补足及手填成本,打印只输出销售公式', t => { const f = fixture(t); f.stock(); f.create(direct({ old_lines: old('2'), buy_rate: '800', member: 'assistant' })); const p = { date: D, grams: '4', total: '3600', payer: 'owner' }; f.run(p, () => f.l.createMaterialPurchase(p, f.actors.owner)); const a = exchange( { old_lines: old('2') }, { quantity: '5', cost_material: { mode: 'pool', poolId: D }, cost_labor: { mode: 'total', amount: '0' } }, ), b = exchange( { old_lines: old('1') }, { quantity: '4', gold_price: '1100', cost_material: { mode: 'gram', rate: '1000' }, cost_material_payer: 'assistant2', cost_labor: { mode: 'total', amount: '0' }, }, ); const made = f.create({ ...a, member: 'assistant', exchange: { items: [a, b], charges: [], fee_items: [], discount: '0', rounding_mode: 'cent' }, }); assert.equal(made.materialCost, 550000); const order = f.l.detail(made.order_id); assert.equal(order.lines[0].costParts.material, 250000); assert.equal(order.lines[1].costParts.material, 300000); assert.equal(order.lines[1].costPayers.material, 'assistant2'); assert.equal( f.l.rows('SELECT SUM(mg) AS mg FROM material_pool_usages WHERE order_id=? AND active=1', made.order_id)[0].mg, 3000, ); const pub = f.l.publicRecovery(made.id, f.actors.owner), html = require('../recovery-printing').exchangeCustomerPrintDocument(pub, {}); assert.match(html, /1,?100.00/); assert.doesNotMatch(JSON.stringify(pub), /costMaterial|costPayers|materialCost|profit|料池/); assert.match(html, /商品2/); const original = f.info(made.id).inputs; assert.equal(original.exchange.items[1].exchange.cost_material_payer, 'assistant2'); original.exchange.items[1].exchange.gold_price = '1150'; const pending = f.update(made.id, original, 'assistant'); assert.equal(pending.pending, true); assert.equal(f.l.detail(made.order_id).total, 651000); f.approve(pending.request); assert.equal(f.l.detail(made.order_id).total, 666000); }); test('整单只计一次信用卡费用和取整,金额不能漏掉必填客户', t => { const f = fixture(t); f.stock(); const row = exchange( { old_lines: old('1') }, { quantity: '1.001', gold_price: '999.99', labor_rate: '0', depreciation_rate: '0', cost_labor: { mode: 'total', amount: '0' }, }, ), input = { ...row, payment_account: '麦麦信用卡', exchange: { items: [row, row], discount: '0', rounding_mode: 'yuan' }, }; const made = f.create(input); assert.equal(made.receivable, 200); assert.equal(made.cardFee, 1); assert.equal(f.l.detail(made.order_id).directCost, 1); assert.throws(() => f.create({ ...input, customer: '' }), /客户/); });