'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('../core/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', ]; const deposit = (f, grams = '1.5', memo = '袋A,客户暂存', member = 'assistant', key = randomUUID()) => { const p = { date: D, grams, memo, verified: true }; return f.run(p, () => f.l.createCustomerMaterial(p, f.actors[member]), member, key); }; const balance = (f, id) => f.l.customerMaterials({}, f.actors.owner).rows.find(r => r.id === id).remainingMg; function fromDeposit(id, weight = '1', quantity = '2') { return exchange({ member: 'assistant', old_source: 'deposit', deposit_id: id, deposit_weight: weight }, { quantity }); } test('共享寄存只记克重及备忘,不产生库存采购资金利润,幂等提交只登记一笔', t => { const f = fixture(t), before = contents(f.l, [ 'movements', 'material_purchases', 'orders', 'payments', 'expenses', 'journal', 'team_fund_cash', ]); const key = randomUUID(), a = deposit(f, '1.5', '袋A,暂存', 'assistant', key), b = deposit(f, '1.5', '袋A,暂存', 'assistant', key); assert.equal(a.id, b.id); assert.equal(balance(f, a.id), 1500); assert.equal( contents(f.l, ['movements', 'material_purchases', 'orders', 'payments', 'expenses', 'journal', 'team_fund_cash']), before, ); assert.equal(f.l.customerMaterials({}, f.actors.assistant2).rows[0].id, a.id); assert.equal(f.l.customerMaterials({ q: '袋A' }, f.actors.owner).remainingMg, 1500); assert.throws(() => deposit(f, '0'), /大于0/); }); test('寄存1.5克用1克,余0.5;修改用0.8余0.7,取消恢复1.5且不重复恢复', t => { const f = fixture(t); f.stock(); const d = deposit(f), r = f.create(fromDeposit(d.id)); assert.equal(balance(f, d.id), 500); assert.equal(r.oldMg, 1000); assert.equal(r.purchase_id, null); assert.equal(f.l.inventory().find(p => p.pocket === '回收旧料').mg, 1000); assert.equal(f.info(r.id).inputs.deposit_id, d.id); f.update(r.id, { deposit_weight: '0.8' }); assert.equal(balance(f, d.id), 700); assert.equal(f.l.inventory().find(p => p.pocket === '回收旧料').mg, 800); f.cancel(r.id); assert.equal(balance(f, d.id), 1500); assert.equal(f.l.inventory().find(p => p.pocket === '回收旧料').mg, 0); assert.throws(() => f.cancel(r.id), /已经取消/); assert.equal(balance(f, d.id), 1500); }); test('多件选同一笔寄存需汇总校验,超用和失败保存全部撤回', t => { const f = fixture(t); f.stock(); const d = deposit(f), row = fromDeposit(d.id), input = { ...row, old_source: undefined, exchange: { items: [row, row], discount: '0', rounding_mode: 'cent' } }; const before = contents(f.l); assert.throws(() => f.create(input), /寄存余料不足/); assert.equal(contents(f.l), before); row.deposit_weight = '0.5'; const made = f.create({ ...input, exchange: { ...input.exchange, items: [row, row] } }); assert.equal(balance(f, d.id), 500); assert.equal(f.info(made.id).inputs.exchange.items[1].deposit_weight, '0.500'); f.cancel(made.id); assert.equal(balance(f, d.id), 1500); assert.throws(() => f.create(fromDeposit(d.id, '1.5', '1')), /不能超过新货/); assert.equal(balance(f, d.id), 1500); }); test('历史修改须审批,申请不扣寄存,批准后才扣;其他成员可使用共享余额但不能看原单', t => { const f = fixture(t); f.stock(); const d = deposit(f), r = f.create(fromDeposit(d.id, '0.5')); const request = f.update(r.id, { deposit_weight: '1' }, 'assistant'); assert.equal(request.pending, true); assert.equal(balance(f, d.id), 1000); f.approve(request.request); assert.equal(balance(f, d.id), 500); const other = f.create({ ...fromDeposit(d.id, '0.5'), member: 'assistant2' }, 'assistant2'); assert.equal(balance(f, d.id), 0); assert.throws(() => f.info(r.id, 'assistant2'), /不存在|无权/); f.cancel(other.id); assert.equal(balance(f, d.id), 500); }); test('寄存HTTP接口需要登录,三人共享余额,重复提交同一操作号只登记一次', async t => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-customer-materials-')), l = new Ledger(':memory:'); const { createUser } = require('../server'); for (const [name, role, member] of [ ['合成老板', 'owner', 'owner'], ['合成助理甲', 'assistant', 'assistant'], ['合成助理乙', 'assistant', 'assistant2'], ]) createUser(l, name, role, 'synthetic-deposit-password', member); l.enableTeamMode(); const app = createApp({ mode: 'trial', port: 0, dataDir: dir, ledger: l, feishuConfig: { enabled: false } }); await new Promise(resolve => app.server.listen(0, '127.0.0.1', resolve)); t.after(async () => { await new Promise(resolve => { app.server.closeAllConnections(); app.server.close(resolve); }); l.close(); fs.rmSync(dir, { recursive: true, force: true }); }); const base = 'http://127.0.0.1:' + app.server.address().port; assert.equal((await fetch(base + '/api/customer-materials')).status, 401); const login = async name => { const r = await fetch(base + '/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'maimai-ledger', Origin: base }, body: JSON.stringify({ name, password: 'synthetic-deposit-password' }), }); assert.equal(r.status, 200); return r.headers.get('set-cookie').split(';')[0]; }; const cookie = await login('合成助理甲'), key = randomUUID(), body = { date: today(), grams: '1.5', memo: '合成寄存袋', verified: true }, post = () => fetch(base + '/api/customer-materials', { method: 'POST', headers: { Cookie: cookie, 'Content-Type': 'application/json', 'X-Requested-With': 'maimai-ledger', Origin: base, 'Idempotency-Key': key, }, body: JSON.stringify(body), }); const first = await (await post()).json(), again = await (await post()).json(); assert.equal(first.id, again.id); assert.equal(first.remainingMg, 1500); for (const name of ['合成老板', '合成助理甲', '合成助理乙']) { const response = await fetch(base + '/api/customer-materials', { headers: { Cookie: await login(name) } }), data = await response.json(); assert.equal(response.status, 200); assert.equal(data.rows.length, 1); assert.equal(data.remainingMg, 1500); assert.equal(data.rows[0].actor, '合成助理甲'); } }); test('置换余料1.439克暂存:只收入换货费用、不购料、不把客户余料加入自有库存,幂等不重复', t => { const f = fixture(t); f.stock(); const input = exchange( { old_lines: old('10'), surplus_mode: 'deposit', surplus_memo: '袋B', buy_rate: '', buy_total: '1100.40' }, { quantity: '8.561' }, ), key = randomUUID(); const r = f.run(input, () => f.l.createRecovery(input, f.actors.assistant), 'assistant', key), again = f.run(input, () => f.l.createRecovery(input, f.actors.assistant), 'assistant', key); assert.equal(r.id, again.id); assert.equal(r.depositMg, 1439); assert.equal(r.purchaseMg, 0); assert.equal(r.purchaseAmount, 0); assert.equal(r.purchase_id, null); assert.equal(r.netSettlement, r.receivable); assert.equal(f.l.inventory().find(p => p.pocket === '回收旧料').mg, 8561); const d = f.l.customerMaterials({}, f.actors.owner).rows[0]; assert.equal(d.remainingMg, 1439); assert.equal(d.sourceRecoveryId, r.id); assert.match(d.memo, /袋B/); assert.equal(f.l.rows('SELECT * FROM customer_material_origins').length, 1); assert.equal(f.info(r.id).inputs.surplus_mode, 'deposit'); const print = require('../domains/printing/recovery-printing').exchangeCustomerPrintDocument( f.l.publicRecovery(r.id, f.actors.owner), ); assert.match(print, /1\.439 克,暂不结算/); assert.doesNotMatch(print, /袋B/); }); test('余料寄存修改与撤回:同一寄存号调整,不重复;已用部分不可撤销,回退用料后允许取消', t => { const f = fixture(t); f.stock(); const r = f.create(exchange({ old_lines: old('3'), surplus_mode: 'deposit' }, { quantity: '1' })); let d = f.l.customerMaterials({}, f.actors.owner).rows[0]; assert.equal(balance(f, d.id), 2000); f.update(r.id, { old_lines: old('2.5') }); assert.equal(balance(f, d.id), 1500); assert.equal(f.l.customerMaterials({}, f.actors.owner).rows.length, 1); const use = f.create(fromDeposit(d.id, '1', '1')); assert.equal(balance(f, d.id), 500); const before = contents(f.l); assert.throws(() => f.cancel(r.id), /寄存余料已被置换使用/); assert.equal(contents(f.l), before); assert.throws(() => f.update(r.id, { old_lines: old('1.5') }), /寄存余料已被置换使用/); f.update(r.id, { old_lines: old('2.2') }); assert.equal(balance(f, d.id), 200); assert.equal(f.l.customerMaterials({}, f.actors.owner).rows[0].usedMg, 1000); f.cancel(use.id); assert.equal(balance(f, d.id), 1200); f.cancel(r.id); d = f.l.customerMaterials({}, f.actors.owner).rows[0]; assert.equal(d.remainingMg, 0); assert.equal(d.usedMg, 0); assert.equal(d.mg, 0); assert.equal(d.voided, true); assert.equal(f.l.inventory().find(p => p.pocket === '回收旧料').mg, 0); }); test('多商品可分别回收和寄存,修改回填隔离,寄存改回收后不遗留余额', t => { const f = fixture(t); f.stock(); const a = exchange({ old_lines: old('3'), surplus_mode: 'deposit' }, { quantity: '1' }), b = exchange({ old_lines: old('4'), buy_rate: '850' }, { quantity: '2' }); const r = f.create({ ...a, exchange: { items: [a, b], rounding_mode: 'cent', discount: '0' } }); assert.equal(r.depositMg, 2000); assert.equal(r.purchaseMg, 2000); assert.equal(r.purchaseAmount, 170000); assert.equal(r.surplusMg, 4000); assert.equal(f.l.inventory().find(p => p.pocket === '回收旧料').mg, 5000); const input = f.info(r.id).inputs; assert.equal(input.exchange.items[0].surplus_mode, 'deposit'); assert.equal(input.exchange.items[1].surplus_mode, undefined); const d = f.l.customerMaterials({}, f.actors.owner).rows[0]; input.exchange.items[0].surplus_mode = 'buy'; input.exchange.items[0].buy_rate = '850'; delete input.exchange.items[0].buy_total; f.update(r.id, input); assert.equal(balance(f, d.id), 0); assert.equal(f.l.recovery(r.id, f.actors.owner).purchaseMg, 4000); }); test('过去置换的余料寄存修改须审批,审批前余额不变,同意后同步调整', t => { const f = fixture(t); f.stock(); const r = f.create(exchange({ old_lines: old('3'), surplus_mode: 'deposit' }, { quantity: '1' })), d = f.l.customerMaterials({}, f.actors.owner).rows[0]; const request = f.update(r.id, { old_lines: old('2') }, 'assistant'); assert.equal(request.pending, true); assert.equal(balance(f, d.id), 2000); f.approve(request.request); assert.equal(balance(f, d.id), 1000); const cancel = f.cancel(r.id, {}, 'assistant'); assert.equal(cancel.pending, true); assert.equal(balance(f, d.id), 1000); f.approve(cancel.request); assert.equal(balance(f, d.id), 0); }); test('一份20克旧料换15克及3克新货,余2克寄存;修改统一补差且取消完整恢复', t => { const f = fixture(t); f.stock(); const product = (name, quantity, pocket, rate, cost, payer) => ({ name, quantity, pocket, labor_mode: 'gram', labor_rate: rate, cost_labor: { mode: 'gram', rate: cost }, cost_labor_payer: payer, }); const input = exchange( { old_lines: old('20'), surplus_mode: 'deposit' }, { products: [ product('足金手镯', '15', '现货', '25', '5', 'owner'), product('足金戒指', '3', '', '20', '3', 'assistant'), ], }, ), r = f.create(input); assert.equal(r.old_lines.length, 1); assert.equal(r.oldMg, 20000); assert.equal(r.newMg, 18000); assert.equal(r.depositMg, 2000); assert.equal(r.purchase_id, null); assert.equal(r.receivable, 61500); assert.equal(r.laborCost, 8400); assert.equal(r.profit, 53100); assert.equal(f.l.inventory().find(p => p.pocket === '现货').mg, 85000); assert.equal(f.l.inventory().find(p => p.pocket === '回收旧料').mg, 18000); const d = f.l.customerMaterials({}, f.actors.owner).rows[0]; assert.equal(balance(f, d.id), 2000); const saved = f.info(r.id).inputs; assert.equal(saved.exchange.products.length, 2); assert.equal(saved.exchange.products[1].cost_labor_payer, 'assistant'); assert.equal(saved.old_lines.length, 1); const p = { date: D, grams: '5', total: '4500', payer: 'owner' }; f.run(p, () => f.l.createMaterialPurchase(p, f.actors.owner)); saved.exchange.products[1].quantity = '7'; saved.exchange.cost_material = { mode: 'pool', poolId: D }; const edited = f.update(r.id, saved).recovery; assert.equal(edited.newMg, 22000); assert.equal(edited.differenceMg, 2000); assert.equal(edited.depositMg, 0); assert.equal(edited.materialCost, 180000); assert.equal(edited.goldAmount, 200000); assert.equal(balance(f, d.id), 0); assert.equal(f.l.materialPoolDetail(D).usedMg, 2000); assert.equal(f.l.inventory().find(p => p.pocket === '回收旧料').mg, 20000); f.cancel(r.id); assert.equal(f.l.materialPoolDetail(D).usedMg, 0); assert.equal(f.l.inventory().find(p => p.pocket === '现货').mg, 100000); assert.equal(f.l.inventory().find(p => p.pocket === '回收旧料').mg, 0); assert.equal(balance(f, d.id), 0); });