'use strict'; const { historicalAction } = require('./fixtures/legacy-cancellation.cjs'); const { test } = require('node:test'), assert = require('node:assert/strict'), { randomUUID } = require('node:crypto'); const fs = require('node:fs'), os = require('node:os'), path = require('node:path'); const { Ledger } = require('../ledger'), { createApp } = require('../server'), Calc = require('../public/calculations'); const D0 = '2026-10-16', D = '2026-10-17', D2 = '2026-10-18', D3 = '2026-10-19'; const owner = { id: 'edit-owner', name: '测试麦麦', role: 'owner' }, assistant = { id: 'edit-assistant', name: '测试助理', role: 'assistant' }; const golden = (extra = {}) => ({ name: '足金999', unit: 'g', quantity: '2', pocket: '现货', payer: 'owner', pricingMode: 'manual', sale: '2000', costParts: { material: '1700', labor: '20', accessories: '0', other: '0' }, ...extra, }); const orderInput = (extra = {}) => ({ date: D, customer: '测试客户', internal_note: '测试内部备注', salesperson: '测试开单人', note: '原备注', discount: '0', rounding_mode: 'yuan', payment_account: '助理微信', fee_items: [{ key: 'shipping', amount: '6', payer: 'assistant', note: '快递费' }], lines: [golden()], ...extra, }); const snapshots = ledger => ledger .rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name") .map(({ name }) => [name, ledger.rows('SELECT * FROM "' + name + '"')]); function fixture(t) { const l = new Ledger(':memory:'); t.after(() => l.close()); const run = (input, fn, actor = assistant, key = randomUUID()) => l.transact(key, actor, input, fn); run( { opening: true }, () => l.stock({ kind: 'opening', date: D0, pocket: '现货', grams: '20', note: '测试库存' }, owner), owner, ); run( { opening: '金料' }, () => l.stock({ kind: 'opening', date: D0, pocket: '金料', grams: '20', note: '测试库存' }, owner), owner, ); const issue = (input = orderInput()) => run(input, () => l.issueOrder(input, assistant)).id; const inputs = id => ({ ...l.orderEdit(id, assistant).inputs, revision: l.detail(id).revision, reason: '核实原凭据后更正录入', verified: true, }); const edit = (id, input = inputs(id), key = randomUUID(), actor = owner) => run({ id, input }, () => l.editOrder(id, input, actor), actor, key); const act = (id, kind, input = {}, actor = owner) => run( { id, kind, input }, () => historicalAction(l, id, kind, { date: D, note: '测试实际交款', ...input }, actor), actor, ); const buy = (date = D, grams = '10', total = '9000', payer = 'owner') => run({ date, grams, total, payer }, () => l.createMaterialPurchase({ date, grams, total, payer, note: '原采购' }, assistant), ); return { l, run, issue, inputs, edit, act, buy }; } function financialRows(l, id) { return Object.fromEntries( ['payments', 'expenses', 'settlements', 'movements', 'journal'].map(table => [ table, l.rows('SELECT * FROM ' + table + ' WHERE order_id=?', id), ]), ); } function consistent(l, id) { const order = l.detail(id); assert.equal(order.balance, 0); if (order.goodsCost !== null) { assert.equal(order.profit, order.total - order.goodsCost - order.directCost); assert.equal(Calc.orderCosts(order).total.total, order.goodsCost + order.directCost); assert.equal(l.orderBook({ from: D0, date: D3 }).rows.find(row => row.id === id).profit, order.profit); } return order; } test('普通已交付整单改克重金额成本付款人货盘与收款渠道,原身份和实际交款保持,库存利润差额守恒', t => { const { l, issue, inputs, edit, act } = fixture(t), id = issue(), before = l.detail(id), original = financialRows(l, id); act(id, 'settlement', { amount: (before.costDue / 100).toFixed(2), bucket: 'cost', direction: 'toOwner', verified: true, }); act(id, 'settlement', { amount: (before.profitDue / 100).toFixed(2), bucket: 'profit', direction: 'toOwner', verified: true, }); act(id, 'review', { revision: l.detail(id).revision }); const actualTransfers = l.rows('SELECT * FROM settlements WHERE order_id=?', id), input = inputs(id); input.customer = '新客户'; input.salesperson = '麦麦'; input.note = '更正备注'; input.payment_account = '麦麦支付宝'; input.discount = '2.34'; input.rounding_mode = 'cent'; input.lines = [ golden({ quantity: '3.001', pocket: '金料', sale: '3100.67', payer: 'assistant', costPayers: { material: 'assistant', labor: 'owner' }, costParts: { material: '2600.01', labor: '30.02', accessories: '4.03', other: '5.04' }, }), { name: '纯银925', unit: '件', quantity: '1', pocket: '', payer: 'owner', sale: '99.99', costParts: { material: '50', labor: '3', accessories: '0', other: '0' }, }, ]; input.fee_items[0].amount = '8.88'; input.fee_items[0].payer = 'owner'; const result = edit(id, input), after = consistent(l, id); assert.equal(result.id, id); assert.equal(result.order.id, id); assert.equal(l.rows('SELECT * FROM orders').length, 1); for (const key of ['id', 'number', 'paper_number', 'created']) assert.equal(after[key], before[key], key); assert.equal(after.status, 'delivered'); assert.equal(after.total, 319832); assert.equal(after.goodsCost, 269210); assert.equal(after.directCost, 888); assert.equal(after.profit, 49734); assert.equal(after.netReceived, 319832); assert.equal(after.ownerDirect, 319832); assert.equal(after.reviewed_revision, 0); assert.equal(after.revision, input.revision + 1); assert.deepEqual(l.rows('SELECT * FROM settlements WHERE order_id=?', id), actualTransfers); assert.equal(after.settlementDue, after.ownerCost + after.profit - 319832 - before.settlementDue); assert.equal(l.inventory().find(row => row.pocket === '现货').mg, 20000); assert.equal(l.inventory().find(row => row.pocket === '金料').mg, 16999); assert.equal(l.report(D).accounts.find(row => row.account === '助理微信').receipt, 0); assert.equal(l.report(D).accounts.find(row => row.account === '麦麦支付宝').receipt, 319832); for (const [table, rows] of Object.entries(original)) for (const row of rows) assert.deepEqual(l.one('SELECT * FROM ' + table + ' WHERE id=?', row.id), row, '原' + table + '不可改写'); assert.equal(l.one('SELECT revision FROM sync WHERE entity=?', 'order:' + id).revision, after.revision); assert.ok( after.audit.some( row => row.action === '整单账务修改' && row.actor === owner.name && row.detail.reason === input.reason, ), ); }); test('只改客户资料或原样重复保存不新增支付费用库存利润,既有收款更正渠道完整保留', t => { const { l, issue, inputs, edit, act } = fixture(t), id = issue(); act(id, 'correct', { type: 'payment', target: l.detail(id).payments[0].id, amount: '2000', account: '麦麦现金', reason: '原渠道录错', verified: true, }); assert.equal(l.rawOrder(id).payment_account, '助理微信'); assert.equal(inputs(id).payment_account, '麦麦现金'); const before = financialRows(l, id), input = inputs(id); input.customer = '只改姓名'; edit(id, input); assert.deepEqual(financialRows(l, id), before); assert.equal(l.detail(id).customer, '只改姓名'); edit(id, inputs(id)); edit(id, inputs(id)); assert.deepEqual(financialRows(l, id), before); consistent(l, id); }); test('旧单多渠道分笔实收在总额账户未改变时保留,明确换账户后只记所选渠道总额', t => { const { l, run, inputs, edit } = fixture(t), p = orderInput({ fee_items: [] }), id = run(p, () => l.saveOrder(p, assistant)).id; for (const [kind, input] of [ ['confirm', {}], ['receipt', { amount: '1200', account: '助理微信', verified: true }], ['receipt', { amount: '800', account: '麦麦支付宝', verified: true }], ['complete', { verified: true }], ]) run({ kind, input }, () => historicalAction(l, id, kind, { date: D, ...input }, assistant)); const before = financialRows(l, id), input = inputs(id); input.lines[0].costParts.labor = '21'; edit(id, input); assert.deepEqual(financialRows(l, id).payments, before.payments); assert.equal(l.report(D).accounts.find(row => row.account === '助理微信').receipt, 120000); assert.equal(l.report(D).accounts.find(row => row.account === '麦麦支付宝').receipt, 80000); const financial = l.detail(id), dateOnly = inputs(id); dateOnly.date = D2; edit(id, dateOnly); assert.equal(l.detail(id).ownerDirect, financial.ownerDirect); assert.equal(l.detail(id).settlementDue, financial.settlementDue); assert.equal(l.report(D2).accounts.find(row => row.account === '助理微信').receipt, 120000); assert.equal(l.report(D2).accounts.find(row => row.account === '麦麦支付宝').receipt, 80000); const next = inputs(id); next.payment_account = '助理现金'; edit(id, next); consistent(l, id); for (const account of ['助理微信', '麦麦支付宝']) assert.equal(l.report(D2).accounts.find(row => row.account === account).receipt, 0); assert.equal(l.report(D2).accounts.find(row => row.account === '助理现金').receipt, 200000); }); test('额外费用与多次更正后的有效支出完整预填,不因单据模板旧值丢失或重复,逐笔日期保留', t => { const { l, issue, inputs, edit, act } = fixture(t), charge = randomUUID(), id = issue( orderInput({ lines: [golden({ charges: [{ id: charge, name: '证书', amount: '10' }] })], fee_items: [ { key: 'shipping', amount: '6', payer: 'assistant', note: '快递费' }, { key: 'charge:' + charge, note: '证书', amount: '4', payer: 'owner' }, ], }), ); act(id, 'expense', { date: D2, amount: '3.21', payer: 'assistant', note: '额外包装' }); act(id, 'correct', { date: D2, type: 'expense', target: l.detail(id).expenses.find(row => row.note === '快递费').id, amount: '7.65', payer: 'owner', reason: '核实实际快递', verified: true, }); act(id, 'correct', { date: D3, type: 'expense', target: l.detail(id).expenses.find(row => row.amount === 765).id, amount: '5.43', payer: 'assistant', reason: '最终实付', verified: true, }); const before = financialRows(l, id), input = inputs(id); assert.equal( input.fee_items.reduce((total, item) => total + Math.round(Number(item.amount) * 100), 0), 1264, ); assert.ok(input.fee_items.some(item => item.amount === '3.21' && item.date === D2)); assert.ok(input.fee_items.some(item => item.amount === '5.43' && item.date === D3)); edit(id, input); assert.deepEqual(financialRows(l, id), before); assert.equal(consistent(l, id).directCost, 1264); const originalFeeDays = [D, D2, D3].map(date => l.report(date).expense), costOnly = inputs(id); costOnly.lines[0].costParts.material = '1701'; edit(id, costOnly); assert.deepEqual( [D, D2, D3].map(date => l.report(date).expense), originalFeeDays, '只改商品成本不能重排已确认的跨日费用', ); consistent(l, id); const change = inputs(id), extra = change.fee_items.find(item => item.amount === '3.21'); extra.amount = '9.87'; extra.payer = 'owner'; extra.date = D3; change.fee_items = change.fee_items.filter(item => item.amount !== '5.43'); change.fee_items.push({ key: 'manual:' + randomUUID(), note: '新增人工', amount: '2.22', payer: 'assistant', date: D2, }); edit(id, change); const after = consistent(l, id); assert.equal(after.directCost, 1609); assert.equal(Calc.orderCosts(after).byPayer.owner.paidFees, 1387); assert.equal(Calc.orderCosts(after).byPayer.assistant.paidFees, 222); const stable = financialRows(l, id); edit(id, inputs(id)); assert.deepEqual(financialRows(l, id), stable); assert.equal(l.report(D2).expense, 222); assert.equal(l.report(D3).expense, 987); }); test('跨日更正保留完整原单号,旧新日期财务和库存快照失效,原日期销售收款出库净额冲回', t => { const { l, run, issue, inputs, edit } = fixture(t), id = issue(), before = l.detail(id); for (const date of [D, D2, D3]) run({ close: date }, () => l.closeDay(date, owner, 'orderDate'), owner); const input = inputs(id); input.date = D2; input.lines[0].quantity = '3'; input.lines[0].sale = '3000'; input.lines[0].baseSale = '3000'; input.lines[0].costParts.material = '2600'; edit(id, input); assert.equal(l.detail(id).paper_number, before.paper_number); assert.equal(l.detail(id).number, before.number); assert.equal(l.detail(id).delivered_date, D2); assert.equal(l.report(D).sales, 0); assert.equal(l.report(D).goods, 0); assert.equal(l.report(D).expense, 0); assert.equal(l.report(D).accounts.find(row => row.account === '助理微信').receipt, 0); assert.equal(l.report(D2).sales, 300000); assert.equal(l.report(D2).profit, 37400); assert.equal(l.report(D2).accounts.find(row => row.account === '助理微信').receipt, 300000); assert.equal(l.report(D).delivered, 0); assert.equal(l.report(D2).delivered, 1); assert.equal(l.reportByOrderDate(D).sales, 0); assert.equal(l.reportByOrderDate(D2).sales, 300000); assert.equal(l.inventory(D).find(row => row.pocket === '现货').mg, 20000); assert.equal(l.inventory(D2).find(row => row.pocket === '现货').mg, 17000); for (const date of [D, D2, D3]) { assert.equal(l.inventorySnapshot(date).stale, true); assert.equal(l.one('SELECT stale FROM closes WHERE date=?', date).stale, 1); } assert.equal(l.reportByOrderDate(D).close.stale, true); assert.equal(l.reportByOrderDate(D2).close.stale, true); consistent(l, id); }); test('日料池增删重排换来源和手填互换复用行身份,关联订单成本一起重算且原采购结算不重记', t => { const { l, issue, inputs, edit, buy } = fixture(t); buy(D, '10', '9000', 'owner'); buy(D2, '10', '9500', 'assistant'); const pooled = (pool, quantity) => golden({ quantity, pocket: '', costMaterial: { mode: 'pool', poolId: pool } }); const id = issue(orderInput({ date: D2, fee_items: [], lines: [pooled(D, '1'), pooled(D, '2')] })), other = issue(orderInput({ date: D2, fee_items: [], lines: [pooled(D, '1')] })); const purchase = l.rows('SELECT * FROM material_purchases'), original = l.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY line_index', id); let input = inputs(id); input.lines = [ { name: '纯银925', unit: '件', quantity: '1', pocket: '', payer: 'assistant', sale: '100', costParts: { material: '50', labor: '0', accessories: '0', other: '0' }, }, pooled(D2, '1'), ]; edit(id, input); assert.equal(l.materialPoolDetail(D).usedMg, 1000); assert.equal(l.materialPoolDetail(D2).usedMg, 1000); assert.equal(l.detail(id).goodsCost, 102000); consistent(l, id); consistent(l, other); input = inputs(id); input.lines = [pooled(D, '0.5'), pooled(D2, '1.5'), pooled(D, '0.5')]; edit(id, input); assert.equal(l.materialPoolDetail(D).usedMg, 2000); assert.equal(l.materialPoolDetail(D2).usedMg, 1500); assert.equal(l.detail(id).goodsCost, 238500); consistent(l, id); consistent(l, other); const usages = l.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY line_index', id); assert.equal(usages.length, 3); assert.equal(usages[0].id, original[0].id); assert.equal(usages[1].id, original[1].id); assert.ok(usages.every(row => row.active === 1)); assert.deepEqual(l.rows('SELECT * FROM material_purchases'), purchase); assert.equal(l.rows('SELECT * FROM material_pool_settlements').length, 0); assert.ok(l.rows('SELECT * FROM material_pool_events WHERE order_id=?', id).some(row => row.kind === '整单修改释放')); assert.ok(l.rows('SELECT * FROM material_pool_events WHERE order_id=?', id).some(row => row.kind === '整单修改消耗')); const current = snapshots(l), stable = financialRows(l, id); edit(id, inputs(id)); assert.deepEqual(financialRows(l, id), stable); assert.equal(l.rows('SELECT * FROM material_pool_usages WHERE order_id=?', id).length, 3); assert.equal( l.rows('SELECT * FROM material_pool_events').length, current.find(([name]) => name === 'material_pool_events')[1].length, ); }); test('整单变更造成日料池缺口时关联单均待补,缩减后自动恢复成本利润和付款人分摊', t => { const { l, issue, inputs, edit, buy } = fixture(t); buy(D, '5', '4500', 'assistant'); const pooled = quantity => golden({ quantity, pocket: '', costMaterial: { mode: 'pool', poolId: D }, costParts: { material: '', labor: '0', accessories: '0', other: '0' }, }); const id = issue(orderInput({ lines: [pooled('3')], fee_items: [] })), other = issue(orderInput({ lines: [pooled('1')], fee_items: [] })), otherPayment = l.rows('SELECT * FROM payments WHERE order_id=?', other); let input = inputs(id); input.lines[0].quantity = '5'; edit(id, input); assert.equal(l.materialPoolDetail(D).shortageMg, 1000); assert.equal(l.detail(id).profit, null); assert.equal(l.detail(other).profit, null); assert.equal(l.report(D).profit, null); input = inputs(id); input.lines[0].quantity = '2'; edit(id, input); assert.equal(l.materialPoolDetail(D).usedMg, 3000); assert.equal(l.materialPoolDetail(D).consumedCost, 270000); assert.equal(l.detail(id).goodsCost, 180000); assert.equal(l.detail(other).goodsCost, 90000); assert.equal(consistent(l, id).profit, 20000); assert.equal(consistent(l, other).profit, 110000); assert.deepEqual(l.rows('SELECT * FROM payments WHERE order_id=?', other), otherPayment); assert.equal(l.one('SELECT SUM(goods) AS amount FROM journal').amount, 270000); assert.equal(Calc.orderCosts(l.detail(id)).byPayer.assistant.goods, 180000); }); test('修改操作幂等、乐观并发冲突、非法金额克重原因和确认拒绝时全库原状保持', t => { const { l, issue, inputs, edit } = fixture(t), id = issue(), input = inputs(id), key = randomUUID(); input.lines[0].sale = '2100'; input.lines[0].baseSale = '2100'; const first = edit(id, input, key); assert.equal(JSON.stringify(edit(id, input, key)), JSON.stringify(first)); assert.equal(l.rows('SELECT * FROM orders').length, 1); const before = snapshots(l); assert.throws(() => edit(id, { ...input, reason: '另一操作' }, key), /已用于其他内容/); assert.deepEqual(snapshots(l), before); assert.throws( () => edit(id, input), error => error.status === 409 && /新变动/.test(error.message), ); assert.deepEqual(snapshots(l), before); for (const change of [ p => (p.reason = ''), p => (p.verified = false), p => (p.revision = String(p.revision)), p => (p.lines[0].quantity = '2.0001'), p => (p.lines[0].costParts.material = '1.001'), p => (p.lines[0].costParts.material = '-1'), p => (p.lines[0].quantity = '0'), p => (p.payment_account = '银行卡'), p => delete p.fee_items, p => (p.number = '新单号'), p => (p.fee_items[0].expense_id = randomUUID()), ]) { const bad = inputs(id); change(bad); assert.throws(() => edit(id, bad)); assert.deepEqual(snapshots(l), before); } }); test('负库存与后置故障回滚订单费用收款池占用他单重算和所有快照,同样保护直接调用', t => { const { l, issue, inputs, edit, buy } = fixture(t); buy(D, '5', '4500', 'assistant'); const id = issue(), before = snapshots(l); const bad = inputs(id); bad.lines[0].quantity = '99'; bad.lines[0].sale = '9000'; bad.fee_items[0].amount = '99'; assert.throws(() => edit(id, bad), /库存不足/); assert.deepEqual(snapshots(l), before); const earlier = inputs(id); earlier.date = '2026-10-15'; assert.throws(() => edit(id, earlier), /2026-10-15库存不足/); assert.deepEqual(snapshots(l), before); const other = issue( orderInput({ lines: [golden({ pocket: '', costMaterial: { mode: 'pool', poolId: D } })], fee_items: [] }), ); const input = inputs(id); input.lines[0].costMaterial = { mode: 'pool', poolId: D }; input.lines[0].quantity = '4'; input.lines[0].sale = '4000'; input.fee_items[0].amount = '9'; const current = snapshots(l), journal = l.journal; l.journal = function (...args) { if (args[0] === id) throw new Error('模拟末尾写入失败'); return journal.apply(this, args); }; assert.throws(() => edit(id, input), /模拟末尾/); assert.deepEqual(snapshots(l), current); assert.throws(() => l.editOrder(id, input, owner), /模拟末尾/); assert.deepEqual(snapshots(l), current); l.journal = journal; assert.equal(l.materialPoolDetail(D).usedMg, 2000); consistent(l, other); }); test('取消退货仅改资料,锁价销售条件不能改,资料更正不恢复销售或重记锁价实收采购', t => { const { l, run, issue, edit, inputs, act } = fixture(t), returned = issue(); act(returned, 'return', { reason: '已退', verified: true }); const p = orderInput(), cancelled = run(p, () => l.saveOrder(p, assistant)).id; act(cancelled, 'cancel', { reason: '已取消' }); const lockInput = { date: D, customer: '锁价客户', internal_note: '测试内部备注', salesperson: '合成开单人', line: { name: '足金999', quantity: '1', goldPrice: '1000', laborRate: '0', laborMode: 'gram' }, payment: { amount: '1000', account: '助理微信', verified: true }, material: { rate: '900', payer: 'assistant', verified: true }, }; const lock = run(lockInput, () => l.createPriceLock(lockInput, assistant)); const delivery = { date: D2, revision: 1, verified: true, line: { quantity: '1', laborRate: '0', laborMode: 'gram', payer: 'owner', costParts: { labor: '0', accessories: '0', other: '0' }, }, inventory: { pocket: '现货', original: 'receive' }, fee_items: [], }; const locked = run(delivery, () => l.deliverPriceLock(lock.id, delivery, assistant)).id; for (const id of [returned, cancelled, locked]) { const info = l.orderEdit(id, assistant), before = financialRows(l, id), events = l.rows('SELECT * FROM price_lock_events'), status = l.detail(id).status; assert.equal(info.financialEditable, id === locked); if (id !== locked) assert.ok(info.reason); assert.equal(info.eligible, true); edit(id, { revision: info.revision, reason: '只改客户资料', verified: true, customer: '资料更正', internal_note: '测试内部备注', salesperson: '麦麦', note: '资料备注', }); assert.equal(l.detail(id).customer, '资料更正'); assert.equal(l.detail(id).status, status); assert.deepEqual(financialRows(l, id), before); assert.deepEqual(l.rows('SELECT * FROM price_lock_events'), events); if (id === locked) { assert.match(l.detail(id).note, /资料备注;锁价单 SJ/); assert.match(l.detail(id).note, /按原锁定金价 1000\.00元\/克结算$/); assert.equal(l.orderEdit(id, assistant).inputs.note, '资料备注'); } const previous = snapshots(l), bad = inputs(id); bad.lines[0].quantity = '2'; assert.throws(() => edit(id, bad), /仅支持/); assert.deepEqual(snapshots(l), previous); assert.throws( () => edit(id, { revision: l.detail(id).revision, reason: '禁止改总额', verified: true, total: 123 }), /仅支持/, ); assert.deepEqual(snapshots(l), previous); edit(id, inputs(id)); assert.deepEqual(financialRows(l, id), before); if (id === locked) assert.equal(l.detail(id).note.split('锁价单 ').length, 2); } }); test('修改后仍能退货退款与结算,不重复库存或成本,原交款按最新应结差额继续抵减', t => { const { l, run, issue, inputs, edit, act } = fixture(t), id = issue(), input = inputs(id); input.lines[0].quantity = '3'; input.lines[0].sale = '3000'; input.lines[0].baseSale = '3000'; input.lines[0].costParts.material = '2700'; edit(id, input); const order = consistent(l, id); act(id, 'settlement', { amount: (order.costDue / 100).toFixed(2), bucket: 'cost', direction: 'toOwner', verified: true, }); act(id, 'settlement', { amount: (order.profitDue / 100).toFixed(2), bucket: 'profit', direction: 'toOwner', verified: true, }); assert.equal(l.detail(id).settlementDue, 0); act(id, 'return', { date: D2, reason: '退回修改后的实物', verified: true }); act(id, 'refund', { date: D2, amount: '3000', account: '助理微信', verified: true }); assert.equal(l.inventory().find(row => row.pocket === '现货').mg, 20000); assert.equal(l.detail(id).profit, -600); assert.equal(l.detail(id).netReceived, 0); assert.equal(l.detail(id).settlementDue, -300000); const backdated = issue(orderInput({ date: D3, fee_items: [] })), corrected = inputs(backdated); corrected.date = D; edit(backdated, corrected); assert.equal(l.report(D3).sales, 0); act(backdated, 'return', { date: D2, reason: '修改后按真实日期退回', verified: true }); act(backdated, 'refund', { date: D2, amount: '2000', account: '助理微信', verified: true }); assert.equal(l.detail(backdated).status, 'returned'); assert.equal(l.detail(backdated).netReceived, 0); assert.equal(l.detail(backdated).profit, 0); const pending = orderInput({ fee_items: [] }), sameDay = run(pending, () => l.saveOrder(pending, assistant)).id; act(sameDay, 'confirm'); act(sameDay, 'receipt', { amount: '2000', account: '助理微信', verified: true }); act(sameDay, 'complete', { date: D3, verified: true }); act(sameDay, 'return', { date: D3, reason: '同日交付退回', verified: true }); assert.throws( () => act(sameDay, 'refund', { date: D2, amount: '2000', account: '助理微信', verified: true }), /早于交付|早于退货/, ); }); test('HTTP整单修改受登录CSRF保护,同操作号并发只更正一次,跨请求版本冲突并重开临时库保持', async t => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-order-edit-')), 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, key = randomUUID(), origin = base) => fetch(base + route, { method: data ? 'POST' : 'GET', headers: { Cookie: cookie, ...(data ? { 'Content-Type': 'application/json', Origin: origin, 'X-Requested-With': 'maimai-ledger', 'Idempotency-Key': key, } : {}), }, ...(data ? { body: JSON.stringify(data) } : {}), }); const id = app.ledger.one('SELECT id FROM orders LIMIT 1').id, route = '/api/orders/' + id + '/edit'; assert.equal((await call(route)).status, 401); const login = await call('/api/demo-login', { role: 'owner' }); cookie = login.headers.get('set-cookie').split(';')[0]; const get = await (await call(route)).json(); assert.equal(get.financialEditable, true); assert.equal(typeof get.revision, 'number'); const input = { ...get.inputs, internal_note: '测试内部备注', revision: get.revision, reason: 'HTTP核实更正', verified: true, }; input.lines[0].quantity = '1.100'; input.lines[0].sale = '1300'; input.lines[0].baseSale = '1300'; input.payment_account = '助理支付宝'; assert.equal((await call(route, input, randomUUID(), 'https://invalid.example')).status, 403); const key = randomUUID(), responses = await Promise.all([call(route, input, key), call(route, input, key)]); assert.deepEqual( responses.map(response => response.status), [200, 200], ); const a = await responses[0].json(), b = await responses[1].json(); assert.deepEqual(a, b); assert.equal(a.order.total, 130000); assert.equal(a.order.netReceived, 130000); assert.equal(a.order.id, id); assert.equal((await call(route, input)).status, 409); assert.equal(app.ledger.rows('SELECT * FROM orders').length, 1); const reloaded = new Ledger(path.join(dir, 'ledger.sqlite')); try { assert.equal(reloaded.detail(id).total, 130000); assert.equal(reloaded.detail(id).netReceived, 130000); assert.equal(reloaded.inventory().find(row => row.pocket === '现货').mg, 48900); assert.ok(reloaded.detail(id).audit.some(row => row.action === '整单账务修改')); } finally { reloaded.close(); } });