'use strict'; const test = require('node:test'), assert = require('node:assert/strict'), fs = require('node:fs'), os = require('node:os'), path = require('node:path'), vm = require('node:vm'); const { randomUUID } = require('node:crypto'); const Presets = require('../public/order-templates'), Fees = require('../public/fee-estimates'), Calc = require('../public/calculations'); const { Ledger, today } = require('../ledger'), { createApp } = require('../server'); const actor = { id: 'templates-owner', name: '模板测试麦麦', role: 'owner' }, helper = { id: 'templates-assistant', name: '模板测试助理', role: 'assistant' }; const chargeId = '12345678-1234-1234-1234-123456789abc', manualId = '87654321-4321-4321-4321-cba987654321'; function draft(extra = {}) { return { id: 'old-order-id', number: 'old-system-number', paper_number: 'old-paper-number', date: '2026-10-15', fees_date: '2026-10-16', customer: '不得继承的客户', salesperson: '开单助理', payment_account: '麦麦支付宝', discount: '0.00', note: '客户可见备注', rounding_mode: 'cent', revision: 9, status: 'delivered', received: 98000, payments: [{ id: 'old-payment' }], price_lock_id: 'old-lock', lines: [ { name: '足金999', nameType: '足金999', unit: 'g', quantity: '2.200', pocket: '金料', payer: 'assistant', pricingMode: 'auto', goldPrice: '940.00', laborMode: 'gram', laborRate: '45.00', pieces: '1', sale: '2177.00', baseSale: '2167.00', priceNote: '', costParts: { material: '1980.00', labor: '44.00', accessories: '0', other: '0.00' }, costPayers: { material: 'owner', labor: 'assistant' }, costMaterial: { mode: 'gram', rate: '900.00' }, costLabor: { mode: 'gram', rate: '20.00' }, charges: [{ id: chargeId, name: '包装', amount: '10.00' }], materialAllocations: [{ id: 'old-allocation', amount: 9 }], materialPool: { amount: 198000, status: 'covered' }, }, ], fee_items: [ { key: 'shipping', note: '快递费', amount: '0', payer: 'assistant', edited: true, status: 'recorded' }, { key: 'charge:' + chargeId, note: '包装', sourceName: '包装', amount: '0.00', payer: 'owner', edited: true, status: 'recorded', }, { key: 'manual:' + manualId, note: '手填费用', amount: '', payer: 'assistant', edited: true }, ], ...extra, }; } function financialSnapshot(ledger) { const tables = [ 'orders', 'payments', 'expenses', 'journal', 'movements', 'settlements', 'sync', 'closes', 'inventory_snapshots', 'price_locks', 'material_purchases', 'material_pools', 'material_pool_usages', 'material_pool_settlements', ]; return { tables: Object.fromEntries( tables .filter(name => ledger.one("SELECT name FROM sqlite_master WHERE type='table' AND name=?", name)) .map(name => [name, ledger.rows('SELECT * FROM ' + name)]), ), meta: ledger.rows('SELECT * FROM meta ORDER BY key'), }; } function fixture(t) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-templates-')), file = path.join(dir, 'ledger.sqlite'), ledger = new Ledger(file); t.after(() => { try { ledger.close(); } catch {} fs.rmSync(dir, { recursive: true, force: true }); }); const run = (payload, fn, key = randomUUID(), user = actor) => ledger.transact(key, user, payload, fn); return { ledger, dir, file, run }; } test('表单单位白名单保留报价、成本、付款人、空项和0,不继承客户、日期、单号、收付款及旧料分摊', () => { const source = draft(), before = JSON.stringify(source), preset = Presets.fromDraft(source), result = Presets.apply(preset, { today: '2026-10-22' }); assert.equal(JSON.stringify(source), before); assert.equal(preset.lines[0].quantity, '2.200'); assert.equal(preset.lines[0].goldPrice, '940.00'); assert.equal(preset.lines[0].costMaterial.rate, '900.00'); assert.deepEqual(preset.lines[0].costPayers, { material: 'owner', labor: 'assistant' }); assert.equal(preset.payment_account, '麦麦支付宝'); assert.equal(preset.salesperson, '开单助理'); assert.equal(preset.note, '客户可见备注'); assert.equal(preset.discount, '0.00'); for (const key of [ 'id', 'number', 'paper_number', 'paper_date', 'customer', 'date', 'fees_date', 'revision', 'status', 'payments', 'received', 'price_lock_id', 'copy_kind', 'rounding_mode', ]) assert.equal(Object.hasOwn(preset, key), false, key); for (const key of ['materialAllocations', 'materialPool', 'id']) assert.equal(Object.hasOwn(preset.lines[0], key), false, key); for (const original of [ 'old-order-id', 'old-payment', 'old-lock', 'old-allocation', '不得继承的客户', chargeId, manualId, ]) assert.ok(!JSON.stringify(preset).includes(original), original); assert.equal(result.customer, ''); assert.equal(result.date, '2026-10-22'); assert.equal(result.fees_date, '2026-10-22'); assert.equal(result.rounding_mode, 'yuan'); assert.equal(result.fee_auto_initialized, true); const shipping = result.fee_items.find(row => row.key === 'shipping'), packaging = result.fee_items.find(row => row.key === 'charge:' + result.lines[0].charges[0].id), other = result.fee_items.find(row => row.note === '手填费用'); assert.equal(shipping.amount, '0'); assert.equal(packaging.amount, '0.00'); assert.equal(packaging.payer, 'owner'); assert.equal(other.amount, ''); assert.ok(result.fee_items.every(row => row.status === 'estimated')); result.lines[0].charges[0].name = '证书'; assert.equal(Fees.sync(result.fee_items, result.lines).find(row => row.key === packaging.key).amount, '0.00'); }); test('允许未填完的模板,银饰和按件表单安全保留,按克报价和成本随新克重重算', () => { const incomplete = Presets.fromDraft({ lines: [ { name: '定制款', unit: '件', quantity: '', pricingMode: 'manual', baseSale: '0', costParts: { material: '', labor: '0', accessories: '0', other: '0' }, costPayers: { material: '', labor: 'assistant' }, }, ], }); assert.equal(incomplete.lines[0].quantity, ''); assert.equal(incomplete.lines[0].baseSale, '0'); assert.equal(incomplete.lines[0].costParts.material, ''); assert.equal(incomplete.lines[0].costPayers.material, ''); assert.equal(incomplete.lines[0].pocket, ''); const blank = Presets.apply(Presets.fromDraft({ lines: [{}] }), { today: today(), salesperson: '当前助理' }); assert.equal(blank.salesperson, '当前助理'); assert.equal(blank.lines[0].quantity, ''); const result = Presets.apply(Presets.fromDraft(draft()), { today: today() }); result.lines[0].quantity = '3.000'; assert.equal(Calc.sale(result.lines[0]).sale, 296500); assert.equal(Calc.purchaseCosts(result.lines[0]).parts.material, 270000); assert.equal(Calc.purchaseCosts(result.lines[0]).parts.labor, 6000); const silver = Presets.fromDraft({ lines: [{ name: '纯银925', unit: 'g', pocket: '现货', cost: '0', sale: '0' }] }); assert.equal(silver.lines[0].pocket, ''); assert.equal(silver.lines[0].cost, '0'); }); test('日购料模板始终跟随本次日期,重读料价,不保留旧池日期、耗用快照或分摊', () => { const source = draft(); source.lines[0].costMaterial = { mode: 'pool', poolId: '2026-10-10', rate: 90123 }; source.lines[0].materialPoolDraft = { poolId: '2026-10-10', defaultDate: false, manual: { mode: 'gram', rate: '900', total: '1980', originalTotal: '1980', payer: 'assistant' }, }; const preset = Presets.fromDraft(source); assert.deepEqual(preset.lines[0].costMaterial, { mode: 'pool' }); assert.equal(preset.lines[0].costParts.material, ''); assert.ok(!JSON.stringify(preset).includes('2026-10-10')); for (const date of ['2026-10-22', '2026-10-23']) { const result = Presets.apply(preset, { today: date }); assert.deepEqual(result.lines[0].costMaterial, { mode: 'pool', poolId: date }); assert.equal(result.lines[0].materialPoolDraft.defaultDate, true); assert.equal(result.lines[0].materialPoolDraft.poolId, date); assert.equal(result.lines[0].materialPoolDraft.manual.rate, '900'); assert.equal(result.lines[0].materialPoolDraft.manual.payer, 'assistant'); assert.ok(!('materialPool' in result.lines[0])); } }); test('模板验证拒绝非法金额、选项、重复标识和过大输入;不把无效日期变成今天', () => { for (const input of [ null, { lines: [] }, { lines: Array(61).fill({}) }, { lines: [{ unit: 'kg' }] }, { lines: [{ quantity: '1.0001' }] }, { lines: [{ goldPrice: '-1' }] }, { lines: [{ goldPrice: { amount: '2' } }] }, { lines: [{ sale: '1000000001' }] }, { lines: [ { charges: [ { id: chargeId, name: '证书' }, { id: chargeId, name: '包装' }, ], }, ], }, { lines: [{}], payment_account: '第三方' }, { lines: [{}], note: '长'.repeat(241) }, { lines: [{}], fee_items: [{ key: 'old-expense-id', amount: '0' }] }, ]) assert.throws(() => Presets.fromDraft(input)); for (const day of [undefined, '2026-02-30', '2026-1-1']) assert.throws(() => Presets.apply({ lines: [{}] }, { today: day }), /日期/); }); test('保存、更新、删除、重复提交及套用模板不改变任何业务账,重开数据库预设仍在', t => { const { ledger, file, run } = fixture(t), baseline = financialSnapshot(ledger), input = { name: '常用手链 ', preset: draft() }, key = randomUUID(); const saved = run(input, () => ledger.saveOrderTemplate(null, input, actor), key), again = run(input, () => ledger.saveOrderTemplate(null, input, actor), key); assert.deepEqual(saved, again); assert.equal(ledger.orderTemplates().rows.length, 1); const stored = ledger.orderTemplate(saved.id); assert.equal(stored.name, input.name); assert.equal(stored.preset.lines[0].goldPrice, '940.00'); Presets.apply(stored.preset, { today: today() }); assert.deepEqual(financialSnapshot(ledger), baseline); const reopened = new Ledger(file); assert.deepEqual(reopened.orderTemplate(saved.id), stored); reopened.close(); const change = { name: '新名字', preset: { lines: [{ sale: '0', cost: '0' }] }, revision: 1 }; const updated = run(change, () => ledger.saveOrderTemplate(saved.id, change, helper), randomUUID(), helper); assert.equal(updated.revision, 2); assert.equal(ledger.orderTemplate(saved.id).preset.lines[0].sale, '0'); assert.throws( () => run(change, () => ledger.saveOrderTemplate(saved.id, change, actor)), error => error.status === 409, ); assert.throws( () => run({ revision: 1 }, () => ledger.deleteOrderTemplate(saved.id, { revision: 1 }, actor)), error => error.status === 409, ); const del = { revision: 2 }, deleteKey = randomUUID(), removed = run(del, () => ledger.deleteOrderTemplate(saved.id, del, helper), deleteKey, helper); assert.equal(removed.deleted, true); assert.deepEqual( run(del, () => ledger.deleteOrderTemplate(saved.id, del, helper), deleteKey, helper), removed, ); assert.throws( () => ledger.orderTemplate(saved.id), error => error.status === 404, ); assert.deepEqual(ledger.orderTemplates().rows, []); assert.deepEqual(financialSnapshot(ledger), baseline); assert.deepEqual( ledger.rows("SELECT action FROM audit WHERE entity LIKE 'order-template:%'").map(row => row.action), ['保存开单模板', '更新开单模板', '删除开单模板'], ); }); test('模板名称重复和无效修订被拒绝,错误不留下模板或业务数据', t => { const { ledger, run } = fixture(t), input = { name: '普通模板', preset: { lines: [{}] } }; const saved = run(input, () => ledger.saveOrderTemplate(null, input, actor)); assert.throws( () => run(input, () => ledger.saveOrderTemplate(null, input, helper)), error => error.status === 409, ); for (const revision of [0, '1', null]) assert.throws( () => run({ revision }, () => ledger.saveOrderTemplate(saved.id, { ...input, revision }, actor)), /版本/, ); for (const name of ['', {}, '长'.repeat(61)]) assert.throws(() => run({ name }, () => ledger.saveOrderTemplate(null, { ...input, name }, actor)), /名称/); assert.equal(ledger.orderTemplates().rows.length, 1); assert.equal(ledger.rows('SELECT * FROM orders').length, 0); }); test('下拉框转义模板名称,不将名称解释为HTML', () => { const app = fs.readFileSync(path.join(__dirname, '../public/app.js'), 'utf8'), ui = fs.readFileSync(path.join(__dirname, '../public/order-templates-ui.js'), 'utf8'); const context = vm.createContext({ document: { addEventListener() {} }, session: { user: { id: 'u' } }, console }); vm.runInContext( app.match(/^const e ?=[\s\S]*?;$/m)[0] + '\n' + app.match(/^const button ?=[\s\S]*?;$/m)[0] + '\n' + ui, context, ); const name = '">&'; vm.runInContext( 'orderTemplateUser="u";orderTemplateSelection="id";orderTemplateRows=' + JSON.stringify([{ id: 'id', name, revision: 1 }]) + ';', context, ); const html = vm.runInContext('orderTemplateControls()', context); assert.ok(!html.includes('')); assert.ok(html.includes('<img')); assert.ok(html.includes('&')); }); test('HTTP私有模板需要登录、CSRF、幂等操作号,老板可代录归属,版本冲突及删除可恢复', async t => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-template-http-')), app = createApp({ mode: 'demo', dataDir: dir, port: 0 }); 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, input, key = randomUUID(), extra = {}) => fetch(base + route, { method: input ? 'POST' : 'GET', headers: { Cookie: cookie, ...(input ? { 'Content-Type': 'application/json', Origin: base, 'X-Requested-With': 'maimai-ledger', 'Idempotency-Key': key, } : {}), ...extra, }, ...(input ? { body: JSON.stringify(input) } : {}), }); assert.equal((await call('/api/order-templates')).status, 401); cookie = (await call('/api/demo-login', { role: 'owner' })).headers.get('set-cookie').split(';')[0]; const baseline = financialSnapshot(app.ledger), input = { name: 'HTTP常用模板', member: 'assistant', preset: draft() }; assert.equal( (await call('/api/order-templates', input, randomUUID(), { Origin: 'https://evil.example' })).status, 403, ); assert.equal((await call('/api/order-templates', input, '')).status, 400); const key = randomUUID(), responses = await Promise.all([call('/api/order-templates', input, key), call('/api/order-templates', input, key)]); assert.deepEqual( responses.map(row => row.status), [200, 200], ); const [saved, again] = await Promise.all(responses.map(row => row.json())); assert.deepEqual(saved, again); const ownerList = await (await call('/api/order-templates')).json(); assert.equal(ownerList.rows.length, 1); assert.ok(!('preset' in ownerList.rows[0])); cookie = (await call('/api/demo-login', { role: 'assistant' })).headers.get('set-cookie').split(';')[0]; const stored = await (await call('/api/order-templates/' + saved.id)).json(); assert.equal(stored.preset.lines[0].quantity, '2.200'); assert.ok(!('customer' in stored.preset)); assert.equal((await (await call('/api/order-templates')).json()).rows[0].id, saved.id); const change = { name: '助理更新', revision: 1, preset: { lines: [{ name: '纯银925', cost: '0', sale: '0', quantity: '' }] }, }, changeKey = randomUUID(), url = '/api/order-templates/' + saved.id + '/update'; assert.equal((await call(url, change, changeKey)).status, 200); assert.equal((await call(url, change, changeKey)).status, 200); assert.equal((await call(url, change)).status, 409); const competing = await Promise.all([ call(url, { ...change, name: '并发修改甲', revision: 2 }), call(url, { ...change, name: '并发修改乙', revision: 2 }), ]); assert.deepEqual(competing.map(response => response.status).sort(), [200, 409]); assert.equal((await call('/api/order-templates/' + saved.id + '/delete', { revision: 1 })).status, 409); const deleteKey = randomUUID(), deletedUrl = '/api/order-templates/' + saved.id + '/delete'; assert.equal((await call(deletedUrl, { revision: 3 }, deleteKey)).status, 200); assert.equal((await call(deletedUrl, { revision: 3 }, deleteKey)).status, 200); assert.equal((await call('/api/order-templates/' + saved.id)).status, 404); assert.equal((await call('/order-templates.js')).status, 200); assert.equal((await call('/order-templates-ui.js')).status, 200); assert.deepEqual(financialSnapshot(app.ledger), baseline); });