'use strict'; const { test } = require('node:test'), assert = require('node:assert/strict'), fs = require('node:fs'), os = require('node:os'), path = require('node:path'), { randomUUID } = require('node:crypto'); const Calc = require('../public/calculations'), { Ledger } = require('../core/ledger'), { receipt } = require('../domains/printing/printing'), { createApp } = require('../server'); const actor = { id: 'material-test', name: '测试麦麦', role: 'owner' }, date = '2026-10-16', nextDate = '2026-10-17'; const parts = (extra = {}) => ({ material: '9999', labor: '0', accessories: '0', other: '0', ...extra }); const line = (extra = {}) => ({ name: '足金999', unit: 'g', quantity: '2', pocket: '', payer: 'owner', pricingMode: 'manual', baseSale: '2200', costParts: parts(), costMaterial: { mode: 'gram', rate: '900' }, costLabor: { mode: 'total' }, ...extra, }); const yuan = value => (value == null ? '' : (value / 100).toFixed(2)); function editLine(saved) { return { ...saved, quantity: saved.unit === 'g' ? (saved.quantity / 1000).toFixed(3) : String(saved.quantity), baseSale: yuan(saved.baseSale), costParts: Object.fromEntries(Object.entries(saved.costParts).map(([key, value]) => [key, yuan(value)])), costMaterial: saved.costMaterial?.mode === 'gram' ? { mode: 'gram', rate: yuan(saved.costMaterial.rate) } : saved.costMaterial, costLabor: saved.costLabor?.mode === 'gram' ? { mode: 'gram', rate: yuan(saved.costLabor.rate) } : saved.costLabor, }; } function fixture(t) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-material-cost-')), filename = path.join(dir, 'ledger.sqlite'), l = new Ledger(filename); t.after(() => { l.close(); fs.rmSync(dir, { recursive: true, force: true }); }); const run = (payload, fn) => l.transact(randomUUID(), actor, payload, fn); const order = (extra = {}, issue = false) => { const input = { date, customer: '合成客户', internal_note: '测试内部备注', salesperson: '合成开单人', discount: '0', lines: [line()], fee_items: [], ...extra, }; return run(input, () => (issue ? l.issueOrder(input, actor) : l.saveOrder(input, actor))).id; }; const act = (id, action, extra = {}) => { const input = { date, ...extra }; return run({ id, action, input }, () => l.action(id, action, input, actor)); }; return { l, dir, filename, run, order, act }; } test('每克料价按克重计算料费总成本,2克×900元为1800元,2.2克×940元为2068元', () => { const a = Calc.purchaseCosts(line()); assert.equal(a.parts.material, 180000); assert.equal(a.total, 180000); assert.deepEqual(a.costMaterial, { mode: 'gram', rate: 90000 }); const b = Calc.purchaseCosts(line({ quantity: '2.2', costMaterial: { mode: 'gram', rate: '940' } })); assert.equal(b.parts.material, 206800); assert.equal(b.total, 206800); assert.equal(Calc.purchaseCosts(line({ quantity: '3' })).parts.material, 270000); const combined = Calc.purchaseCosts( line({ quantity: '2.2', costMaterial: { mode: 'gram', rate: '940' }, costLabor: { mode: 'gram', rate: '20' } }), ); assert.equal(combined.parts.material, 206800); assert.equal(combined.parts.labor, 4400); assert.equal(combined.total, 211200); const total = Calc.purchaseCosts( line({ quantity: '3', costMaterial: { mode: 'total', rate: '900' }, costParts: parts({ material: '1800', labor: '7' }), costLabor: { mode: 'gram', rate: '20' }, }), ); assert.equal(total.parts.material, 180000); assert.equal(total.parts.labor, 6000); assert.deepEqual(total.costMaterial, { mode: 'total' }); }); test('料价与工费分别精确取整到分,空白不当作0,已计算总额不受客户端总额影响', () => { assert.equal( Calc.purchaseCosts(line({ quantity: '0.001', costMaterial: { mode: 'gram', rate: '5' } })).parts.material, 1, ); assert.equal( Calc.purchaseCosts(line({ quantity: '0.001', costMaterial: { mode: 'gram', rate: '4' } })).parts.material, 0, ); const both = Calc.purchaseCosts( line({ quantity: '0.001', costMaterial: { mode: 'gram', rate: '5' }, costLabor: { mode: 'gram', rate: '5' } }), ); assert.equal(both.total, 2); assert.equal( Calc.purchaseCosts(line({ quantity: '123.456', costMaterial: { mode: 'gram', rate: '789.01' } })).parts.material, 9740802, ); assert.equal( Calc.purchaseCosts(line({ quantity: '99999.999', costMaterial: { mode: 'gram', rate: '9999.99' } })).parts.material, 99999899000, ); for (const rate of ['', null, undefined]) { const result = Calc.purchaseCosts(line({ costMaterial: { mode: 'gram', rate } })); assert.equal(result.parts.material, null); assert.equal(result.total, null); assert.equal(result.costMaterial.rate, null); } const zero = Calc.purchaseCosts( line({ costMaterial: { mode: 'gram', rate: '0' }, costParts: parts({ material: '-9' }) }), ); assert.equal(zero.parts.material, 0); assert.equal(zero.total, 0); }); test('每克料价拒绝按件、非法克重、负数、多余精度及超限总额;按件只接受总额', () => { for (const extra of [ { unit: '件' }, { quantity: '0' }, { quantity: '-2' }, { quantity: '2.0001' }, { costMaterial: { mode: 'gram', rate: '-1' } }, { costMaterial: { mode: 'gram', rate: '940.001' } }, { costMaterial: { mode: 'gram', rate: 'abc' } }, { costMaterial: { mode: 'bad' } }, { quantity: '100000', costMaterial: { mode: 'gram', rate: '100000' } }, ]) assert.throws(() => Calc.purchaseCosts(line(extra))); for (const rate of ['', null, '0']) assert.throws(() => Calc.purchaseCosts(line({ unit: '件', costMaterial: { mode: 'gram', rate } })), /按件/); const total = Calc.purchaseCosts( line({ unit: '件', quantity: '2', costMaterial: { mode: 'total' }, costParts: parts({ material: '1800' }) }), ); assert.equal(total.parts.material, 180000); assert.throws( () => Calc.purchaseCosts(line({ costMaterial: { mode: 'total' }, costParts: parts({ material: '-1' }) })), /非负/, ); }); test('保存、读回和重复编辑只算一次,改变克重才更新料费总额', t => { const { l, filename, order } = fixture(t), id = order(); assert.equal(l.detail(id).goodsCost, 180000); assert.equal(l.detail(id).lines[0].costParts.material, 180000); assert.deepEqual(l.detail(id).lines[0].costMaterial, { mode: 'gram', rate: 90000 }); for (let i = 0; i < 2; i++) { const saved = l.detail(id); order({ id, revision: saved.revision, lines: [editLine(saved.lines[0])] }); assert.equal(l.detail(id).goodsCost, 180000); } const saved = l.detail(id); order({ id, revision: saved.revision, lines: [{ ...editLine(saved.lines[0]), quantity: '2.2' }] }); assert.equal(l.detail(id).goodsCost, 198000); const stored = l.one('SELECT lines FROM orders WHERE id=?', id).lines, reloaded = new Ledger(filename); try { assert.equal(reloaded.detail(id).goodsCost, 198000); assert.equal(reloaded.one('SELECT lines FROM orders WHERE id=?', id).lines, stored); } finally { reloaded.close(); } }); test('旧草稿、旧按件接口和旧版未分项订单保留既有总额,读取与库存登记不改历史成本', t => { const { l, order, run } = fixture(t), id = order({ lines: [line({ costMaterial: undefined, costParts: parts({ material: '1800' }) })] }); const stored = l.rawOrder(id).lines; delete stored[0].costMaterial; l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(stored), id); const original = l.one('SELECT lines FROM orders WHERE id=?', id).lines; assert.equal(l.detail(id).goodsCost, 180000); assert.equal(Calc.orderCosts(l.detail(id)).rows.find(row => row.name === '料费成本').calculation, null); run({}, () => l.stock({ kind: 'increase', date, pocket: '现货', grams: '3.000', note: '合成库存调整' }, actor)); assert.equal(l.one('SELECT lines FROM orders WHERE id=?', id).lines, original); const saved = l.detail(id); order({ id, revision: saved.revision, lines: [editLine(saved.lines[0])] }); assert.equal(l.detail(id).goodsCost, 180000); assert.deepEqual(l.detail(id).lines[0].costMaterial, { mode: 'total' }); const piece = order({ lines: [line({ unit: '件', quantity: '2', costMaterial: undefined, costParts: parts({ material: '1800' }) })], }); assert.equal(l.detail(piece).goodsCost, 180000); const legacy = order({ lines: [line({ costParts: undefined, costMaterial: undefined, cost: '1800' })] }); assert.equal(l.detail(legacy).goodsCost, 180000); assert.ok(!('costMaterial' in l.detail(legacy).lines[0])); }); test('交付前补录支持每克料价并由服务端重算,旧版总额接口仍可用,缺失与非法输入完整回滚', t => { const { l, order, act } = fixture(t), id = order({ lines: [line({ costMaterial: { mode: 'gram', rate: '' } })] }); act(id, 'confirm'); assert.equal(l.detail(id).goodsCost, null); act(id, 'cost', { costs: [ { parts: parts({ material: '1', labor: '9999' }), costMaterial: { mode: 'gram', rate: '900' }, costLabor: { mode: 'gram', rate: '20' }, }, ], }); let saved = l.detail(id); assert.equal(saved.goodsCost, 184000); assert.equal(saved.lines[0].costParts.material, 180000); assert.equal(saved.lines[0].costParts.labor, 4000); for (const rate of ['', '-1', '900.001']) { const before = l.one('SELECT lines,revision FROM orders WHERE id=?', id); assert.throws(() => act(id, 'cost', { costs: [{ parts: parts(), costMaterial: { mode: 'gram', rate } }] })); assert.deepEqual(l.one('SELECT lines,revision FROM orders WHERE id=?', id), before); } act(id, 'cost', { costs: [{ material: '1810', labor: '10', accessories: '0', other: '0' }] }); saved = l.detail(id); assert.equal(saved.goodsCost, 182000); assert.deepEqual(saved.lines[0].costMaterial, { mode: 'total' }); act(id, 'cost', { costs: [{ parts: parts(), costMaterial: { mode: 'gram', rate: '900' }, costLabor: { mode: 'total' } }], }); assert.equal(l.detail(id).goodsCost, 180000); }); test('料费成本明细包含每克计算依据,利润、结算及订单簿使用一次计算后的总额', t => { const { l, order } = fixture(t), id = order( { lines: [ line({ quantity: '2.2', baseSale: '2300', costMaterial: { mode: 'gram', rate: '940' }, costLabor: { mode: 'gram', rate: '20' }, }), ], }, true, ), o = l.detail(id); assert.equal(o.goodsCost, 211200); assert.equal(o.profit, 18800); assert.equal(o.ownerCost, 211200); assert.equal(o.costDue, 211200); assert.equal(o.settlementDue, 230000); const costs = Calc.orderCosts(o), material = costs.rows.find(row => row.name === '料费成本'); assert.equal(material.amount, 206800); assert.deepEqual(material.calculation, { rate: 94000, quantity: 2200 }); assert.equal(costs.total.total, 211200); const book = l.orderBook({ date }), row = book.rows.find(row => row.id === id); assert.equal(row.material, 206800); assert.equal(row.laborAndFees, 4400); assert.equal(row.totalCost, 211200); assert.equal(row.profit, 18800); assert.deepEqual(row.costItems.find(item => item.component === 'material').calculation, { rate: 94000, quantity: 2200, }); const before = l.one('SELECT lines FROM orders WHERE id=?', id).lines; Calc.orderCosts(l.detail(id)); l.publicOrder(id); l.orderBook({ date }); assert.equal(l.one('SELECT lines FROM orders WHERE id=?', id).lines, before); }); test('交付成本锁定,后续库存采购不重估原单,跨日退货与返款按原成本冲回', t => { const { l, order, act, run } = fixture(t), id = order({}, true), before = l.one('SELECT lines FROM orders WHERE id=?', id).lines; assert.throws( () => act(id, 'cost', { costs: [{ parts: parts(), costMaterial: { mode: 'gram', rate: '1' } }] }), /锁定/, ); run({}, () => l.stock( { kind: 'purchase', date: nextDate, pocket: '现货', grams: '2', cost: '4000', note: '后续采购高价料' }, actor, ), ); assert.equal(l.detail(id).goodsCost, 180000); assert.equal(l.one('SELECT lines FROM orders WHERE id=?', id).lines, before); act(id, 'settlement', { bucket: 'cost', amount: '1800', direction: 'toOwner', note: '合成货款交款', verified: true }); act(id, 'settlement', { bucket: 'profit', amount: '400', direction: 'toOwner', note: '合成利润交款', verified: true, }); assert.equal(l.detail(id).settlementDue, 0); act(id, 'return', { date: nextDate, reason: '合成退货', verified: true }); let returned = l.detail(id); assert.equal(returned.goodsCost, 180000); assert.equal(returned.profit, 0); assert.equal(returned.costDue, -180000); assert.equal(returned.profitDue, -40000); assert.equal(l.report(nextDate).profit, -40000); assert.equal(l.one('SELECT lines FROM orders WHERE id=?', id).lines, before); act(id, 'refund', { date: nextDate, amount: '2200', account: '助理微信', verified: true }); act(id, 'settlement', { date: nextDate, bucket: 'cost', amount: '1800', direction: 'toAssistant', note: '返还原成本', verified: true, }); act(id, 'settlement', { date: nextDate, bucket: 'profit', amount: '400', direction: 'toAssistant', note: '返还原利润', verified: true, }); returned = l.detail(id); assert.equal(returned.netReceived, 0); assert.equal(returned.settlementDue, 0); assert.equal(l.orderBook({ from: date, date: nextDate }).rows.find(row => row.id === id).material, 0); }); test('HTTP内部字段保存每克料价,客户公开接口与打印页隔离成本元数据和金额', async t => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-material-http-')), app = createApp({ mode: 'demo', dataDir: dir, 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); }); app.ledger.close(); fs.rmSync(dir, { recursive: true, force: true }); }); const base = 'http://127.0.0.1:' + app.server.address().port; let cookie = ''; const call = (route, data) => fetch(base + route, { method: data ? 'POST' : 'GET', headers: { Cookie: cookie, ...(data ? { 'Content-Type': 'application/json', Origin: base, 'X-Requested-With': 'maimai-ledger', 'Idempotency-Key': randomUUID(), } : {}), }, ...(data ? { body: JSON.stringify(data) } : {}), }); const login = await call('/api/demo-login', { role: 'assistant' }); assert.equal(login.status, 200); cookie = login.headers.get('set-cookie').split(';')[0]; const result = await call('/api/orders/issue', { date, customer: '合成客户', internal_note: '测试内部备注', salesperson: '合成开单人', lines: [line({ costMaterial: { mode: 'gram', rate: '913.27' } })], }); assert.equal(result.status, 200); const { id } = await result.json(); const internal = await (await call('/api/orders/' + id)).json(); assert.equal(internal.lines[0].costParts.material, 182654); assert.deepEqual(internal.lines[0].costMaterial, { mode: 'gram', rate: 91327 }); assert.equal(internal.profit, 37346); const publicResponse = await call('/api/orders/' + id + '/public'); assert.equal(publicResponse.status, 200); const customer = await publicResponse.json(), json = JSON.stringify(customer); for (const key of ['costMaterial', 'costParts', 'costLabor', 'payer', 'profit', 'costDue']) assert.ok(!json.includes('"' + key + '"')); const printResponse = await call('/print/' + id); assert.equal(printResponse.status, 200); const html = await printResponse.text(); assert.doesNotMatch(html, /id="confirm-document-print"/); assert.match(html, /id="retry-document-print"/); assert.equal(html.replace(/