'use strict'; const { test } = require('node:test'), assert = require('node:assert/strict'); const { randomUUID } = require('node:crypto'), fs = require('node:fs'), os = require('node:os'), path = require('node:path'), vm = require('node:vm'); const { Ledger } = require('../core/ledger'), Calc = require('../public/calculations'), { receipt, uppercaseMoney } = require('../domains/printing/printing'), { createApp } = require('../server'); const actor = { id: 'round-owner', name: '测试麦麦', role: 'owner' }, D = '2026-10-16', D2 = '2026-10-17'; const item = (extra = {}) => ({ name: '合成商品', unit: '件', quantity: '1', pocket: '', payer: 'owner', cost: '9.99', sale: '12.60', ...extra, }); const input = (extra = {}) => ({ date: D, customer: '合成客户', internal_note: '测试内部备注', salesperson: '合成开单人', payment_account: '助理微信', discount: '0', lines: [item()], fee_items: [], ...extra, }); function fixture(t) { const ledger = new Ledger(':memory:'); t.after(() => ledger.close()); const run = (value, fn, key = randomUUID()) => ledger.transact(key, actor, value, fn); const save = (value = input(), issue = false, key = randomUUID()) => run(value, () => (issue ? ledger.issueOrder(value, actor) : ledger.saveOrder(value, actor)), key).id; const action = (id, kind, extra = {}) => { const value = { date: D, ...extra }; return run({ id, kind, value }, () => ledger.action(id, kind, value, actor)); }; return { ledger, run, save, action }; } const contents = ledger => JSON.stringify( ledger .rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name") .map(({ name }) => [name, ledger.rows('SELECT * FROM "' + name + '"')]), ); test('整单共享算法按.49/.50/.99取整,整元不变,差额符号准确且旧cent保留分', () => { for (const [raw, total, adjustment] of [ [12949, 12900, -49], [12950, 13000, 50], [12999, 13000, 1], [350660, 350700, 40], [350640, 350600, -40], [13000, 13000, 0], [50, 100, 50], [100000000000, 100000000000, 0], ]) { assert.deepEqual(Calc.orderTotal([raw]), { subtotal: raw, discount: 0, unroundedTotal: raw, total, rounding_mode: 'yuan', rounding_adjustment: adjustment, }); assert.equal(Calc.orderTotal([raw], 0, 'cent').total, raw); assert.equal(Calc.orderTotal([raw], 0, 'cent').rounding_adjustment, 0); } assert.equal(Calc.orderTotal([1], 0, 'cent').total, 1); }); test('跨商品和附加收费先按分合计,减优惠后整单只取整一次,单行金额始终不取整', t => { const f = fixture(t), lines = [ item({ sale: '11.49', cost: '1.11', charges: [{ name: '附加一', amount: '0.01' }] }), item({ sale: '12.49', cost: '1.11', charges: [{ name: '附加二', amount: '0.01' }] }), ]; for (const [discount, total, adjustment] of [ ['0', 2400, 0], ['0.51', 2300, -49], ['0.50', 2400, 50], ['0.01', 2400, 1], ]) { const id = f.save(input({ lines, discount }), true), o = f.ledger.detail(id); assert.deepEqual( o.lines.map(line => line.sale), [1150, 1250], ); assert.deepEqual( o.lines.map(line => line.baseSale), [1149, 1249], ); assert.equal(o.total, total); assert.equal(o.rounding_adjustment, adjustment); assert.equal(o.discount, Calc.cents(discount)); assert.equal(o.goodsCost, 222); assert.equal(o.profit, total - 222); assert.equal(o.expenses.length, 0); } const plain = f.save(input({ lines: lines.map(({ charges, ...line }) => line) }), true); assert.equal(f.ledger.detail(plain).total, 2400); assert.equal(f.ledger.detail(plain).rounding_adjustment, 2); }); test('浏览器与服务器加载同一整数算法,输入分精度销售与成本时结果一致', () => { const context = vm.createContext({}); vm.runInContext(fs.readFileSync(path.join(__dirname, '../public/calculations.js'), 'utf8'), context); const browser = context.LedgerCalc; for (const args of [ [[12949]], [[12950]], [[12999]], [[1150, 1250], 51, 'yuan'], [[1150, 1250], 50, 'yuan'], [[12949], 0, 'cent'], [[50], 0, 'yuan'], ]) assert.deepEqual(JSON.parse(JSON.stringify(browser.orderTotal(...args))), Calc.orderTotal(...args)); const line = { unit: 'g', quantity: '3.56', pricingMode: 'auto', goldPrice: '940', laborRate: '45', laborMode: 'gram', costParts: { material: '0', labor: '0', accessories: '0', other: '0' }, costMaterial: { mode: 'gram', rate: '902' }, costLabor: { mode: 'gram', rate: '27' }, }; assert.equal(browser.sale(line).sale, 350660); assert.equal(browser.orderTotal([browser.sale(line).sale]).total, 350700); assert.equal(browser.purchaseCosts(line).total, 330724); }); test('非法、优惠后非正、取整后0及超范围金额拒绝,服务器失败不占号、不留半笔', t => { for (const amounts of [ [], Array(61).fill(100), ['100'], [null], [undefined], [-1], [1.1], [NaN], [Infinity], [true], [100000000001], [100000000000, 1], ]) assert.throws(() => Calc.orderTotal(amounts)); for (const discount of [-1, 0.1, '0', null, NaN, Infinity, 100000000001]) assert.throws(() => Calc.orderTotal([100], discount)); for (const mode of ['', null, 'other', false]) assert.throws(() => Calc.orderTotal([100], 0, mode)); for (const amounts of [[0], [1], [49]]) assert.throws(() => Calc.orderTotal(amounts), /大于0/); assert.throws(() => Calc.orderTotal([100], 100), /大于0/); assert.throws(() => Calc.orderTotal([100], 101), /大于0/); const f = fixture(t), before = contents(f.ledger), paper = f.ledger.paperNumber(D); for (const value of [ input({ lines: [item({ sale: '0.49' })] }), input({ discount: '12.60' }), input({ discount: '12.11' }), input({ rounding_mode: null }), input({ rounding_mode: 'invalid' }), input({ lines: [item({ sale: '1000000000' }), item({ sale: '0.01' })] }), ]) { assert.throws(() => f.save(value, true)); assert.equal(contents(f.ledger), before); assert.equal(f.ledger.paperNumber(D), paper); } }); test('新API省略取整字段仍按元,实收利润结算报表统一total,内部成本与库存保留原精度且幂等', t => { const f = fixture(t); f.run({ stock: true }, () => f.ledger.stock({ kind: 'opening', date: D, pocket: '现货', grams: '10', note: '合成库存' }, actor), ); const value = input({ total: 1, rounding_adjustment: 999, lines: [ item({ unit: 'g', quantity: '3.56', pocket: '现货', pricingMode: 'auto', goldPrice: '940', laborRate: '45', laborMode: 'gram', costParts: { material: '0', labor: '0', accessories: '0', other: '0' }, costMaterial: { mode: 'gram', rate: '902' }, costLabor: { mode: 'gram', rate: '27' }, costPayers: { material: 'owner', labor: 'assistant' }, }), ], fee_items: [{ key: 'shipping', amount: '6', payer: 'assistant' }], }); const key = randomUUID(), id = f.save(value, true, key); assert.equal(f.save(value, true, key), id); const o = f.ledger.detail(id); assert.equal(o.rounding_mode, 'yuan'); assert.equal(o.total, 350700); assert.equal(o.rounding_adjustment, 40); assert.equal(o.discount, 0); assert.equal(o.lines[0].sale, 350660); assert.equal(o.goodsCost, 330724); assert.equal(o.directCost, 600); assert.equal(o.profit, 19376); assert.equal(o.received, 350700); assert.equal(o.balance, 0); assert.equal(o.ownerCost, 321112); assert.equal(o.costDue, 321112); assert.equal(o.settlementDue, 340488); assert.equal(o.payments.length, 1); assert.equal(o.expenses.length, 1); assert.equal(f.ledger.rows('SELECT * FROM journal').length, 1); assert.equal(f.ledger.rows("SELECT * FROM movements WHERE kind='sale'").length, 1); assert.equal(f.ledger.inventory()[0].mg, 6440); const book = f.ledger.orderBook({ date: D }), report = f.ledger.reportByOrderDate(D); assert.equal(book.summary.sale, 350700); assert.equal(book.summary.profit, 19376); assert.equal(report.receiptsByOrderDate.receipt, 350700); assert.equal(report.profit, 19376); assert.equal(report.payerCosts.assistant.total, 10212); f.action(id, 'settlement', { amount: '3211.12', bucket: 'cost', direction: 'toOwner', note: '合成实际货款交付', verified: true, }); f.action(id, 'settlement', { amount: '193.76', bucket: 'profit', direction: 'toOwner', note: '合成利润交付', verified: true, }); assert.equal(f.ledger.detail(id).settlementDue, 0); }); test('整元订单退货退款使用原保存total,利润仅冲回原销售成本,售后和实际费用不取整', t => { const f = fixture(t), id = f.save( input({ lines: [item({ sale: '12.60', cost: '9.99' })], fee_items: [{ key: 'shipping', amount: '0.49', payer: 'assistant' }], }), true, ); assert.equal(f.ledger.detail(id).profit, 252); f.action(id, 'return', { date: D2, reason: '合成退货', verified: true }); assert.equal(f.ledger.detail(id).balance, -1300); assert.equal(f.ledger.detail(id).profit, -49); assert.throws( () => f.action(id, 'refund', { date: D2, amount: '13.01', account: '助理微信', verified: true }), /超过/, ); f.action(id, 'refund', { date: D2, amount: '13', account: '助理微信', verified: true }); assert.equal(f.ledger.detail(id).netReceived, 0); assert.equal(f.ledger.detail(id).profit, -49); assert.equal(f.ledger.report(D2).sales, -1300); assert.equal(f.ledger.report(D2).profit, -301); f.run({ after: true }, () => f.ledger.saveAfterSale( { date: D2, project: '合成售后', customer: '合成客户', amount: '0.49', payer: 'owner' }, actor, ), ); assert.equal(f.ledger.reportByOrderDate(D2).profit, -49); }); test('打印保留行金额及保存优惠,整数合计大小写一致,取整差额不混入优惠或成本', t => { const f = fixture(t); for (const [sale, discount, total, adjustment, upper] of [ ['12.60', '0.00', 1300, 40, '壹拾叁元整'], ['12.40', '0.00', 1200, -40, '壹拾贰元整'], ['12.80', '0.20', 1300, 40, '壹拾叁元整'], ['12.60', '0.20', 1200, -40, '壹拾贰元整'], ]) { const id = f.save(input({ discount, lines: [item({ sale, cost: '9.99' })] }), true), p = f.ledger.publicOrder(id); assert.equal(p.total, total); assert.equal(p.rounding_mode, 'yuan'); assert.equal(p.rounding_adjustment, adjustment); for (const mode of ['full', 'overlay']) { const html = receipt(p, {}, mode); assert.ok(html.includes('' + sale + '')); assert.ok(html.includes('¥' + total / 100 + '')); assert.ok(html.includes(upper)); assert.ok(html.includes('整单金额四舍五入到元')); assert.ok(!html.includes('+0.40元')); assert.ok(!html.includes('-0.40元')); assert.equal((html.match(/