'use strict'; const { createBrowserContext } = require('./fixtures/browser-context.cjs'); const test = require('node:test'), assert = require('node:assert/strict'), fs = require('node:fs'), path = require('node:path'), vm = require('node:vm'); const { randomUUID } = require('node:crypto'), Calc = require('../public/calculations'); const D = '2026-10-22', ID = '11111111-1111-4111-8111-111111111111'; const line = (extra = {}) => ({ name: '足金999', code: '合成货号', unit: 'g', quantity: 620, pocket: '现货', payer: 'owner', pricingMode: 'auto', goldPrice: 92700, laborRate: 4500, laborMode: 'gram', pieces: 1, baseSale: 60264, sale: 75264, charges: [{ name: '附加工艺', amount: 15000 }], priceNote: '原单报价说明', cost: 56544, costParts: { material: 55614, labor: 930, accessories: 0, other: 0 }, costPayers: { material: 'owner', labor: 'assistant' }, costMaterial: { mode: 'gram', rate: 89700 }, costLabor: { mode: 'gram', rate: 1500 }, ...extra, }); const order = (extra = {}) => ({ id: ID, revision: 3, reviewed_revision: 3, number: 'XS20261022001', paper_number: '20261022001', date: D, status: 'delivered', customer: '合成客户', salesperson: '助理', payment_account: '助理微信', total: 75300, rounding_mode: 'yuan', rounding_adjustment: 36, discount: 0, goodsCost: 56544, knownGoodsCost: 56544, directCost: 600, profit: 18156, materialCostPending: false, ownerCost: 55614, netReceived: 75300, balance: 0, costTransferred: 0, profitTransferred: 0, ownerDirect: 0, settlementDue: 73770, costDue: 55614, profitDue: 18156, lines: [line()], pendingFees: [], fee_items: [{ key: 'box', note: '零元包装', amount: 0, payer: 'owner', status: 'recorded' }], payments: [{ id: 'receipt', date: D, kind: 'receipt', amount: 75300, account: '助理微信', reference: '' }], expenses: [{ id: 'shipping', date: D, amount: 600, payer: 'assistant', note: '快递费' }], settlements: [], corrections: [], audit: [], note: '合成备注', ...extra, }); function freeze(value) { if (value && typeof value === 'object') { Object.values(value).forEach(freeze); Object.freeze(value); } return value; } function render(saved = order(), role = 'owner') { const nodes = new Map([['#order-content', { innerHTML: '' }]]), calls = []; const noCalculator = () => { throw new Error('已保存订单不得走原始录入计算器'); }; const context = createBrowserContext({ console, LedgerCalc: { ...Calc, calculate: noCalculator, sale: noCalculator, orderTotal: noCalculator, purchaseCosts: noCalculator, }, crypto: { randomUUID }, URLSearchParams, setInterval() {}, setTimeout() {}, clearTimeout() {}, document: { querySelector: selector => nodes.get(selector) || null, querySelectorAll: () => [], addEventListener() {}, }, window: { scrollTo() {} }, localStorage: { getItem() { return null; }, setItem() { throw new Error('查看详情不得写入草稿'); }, removeItem() {}, }, sessionStorage: { getItem() { return null; }, setItem() {}, }, __saved: freeze(saved), __calls: calls, }); const run = code => vm.runInContext(code, context); for (const file of ['price-locks-ui.js', 'material-pools-ui.js', 'app.js']) run(fs.readFileSync(path.join(__dirname, '../public', file), 'utf8').replace(/\ninit\(\);\s*$/, '')); const before = JSON.stringify(saved); run( `session={user:{id:'detail-test',name:'${role === 'owner' ? '麦麦' : '助理'}',role:'${role}'}};state={user:session.user,today:'2026-10-23',pockets:['现货','金料']};tab='orders';currentOrder=__saved;api=async function(url,data){__calls.push({url,data});throw new Error('详情渲染不得请求写接口');};renderDetail();`, ); assert.equal(JSON.stringify(saved), before, '打开详情不能改动已保存数据'); assert.equal(calls.length, 0); return { html: nodes.get('#order-content').innerHTML, run }; } function panel(html, label) { const match = html.match(new RegExp(']*aria-label="' + label + '"[^>]*>([\\s\\S]*?)')); assert.ok(match, '应显示 ' + label); return match[1]; } function text(html) { return html .replace(/<[^>]*>/g, '') .replace(/\s+/g, ' ') .trim(); } const withoutFees = { expenses: [], fee_items: [], directCost: 0 }; const zeroLine = (extra = {}) => line({ cost: 0, costParts: { material: 0, labor: 0, accessories: 0, other: 0 }, costMaterial: { mode: 'total' }, costLabor: { mode: 'total' }, ...extra, }); test('录入时间固定北京时间和24小时到分钟,跨日与缺失时间不依赖设备时区', () => { const { run } = render(); for (const [created, expected] of [ ['2026-10-22T07:08:59.999Z', '2026-10-22 15:08'], ['2026-10-22T16:07:59.999Z', '2026-10-23 00:07'], ['2026-10-23T00:07:00+08:00', '2026-10-23 00:07'], ['2026-12-31T23:59:59Z', '2027-01-01 07:59'], [undefined, '未记录'], [null, '未记录'], ['', '未记录'], ['2026-10-22', '未记录'], ['2026-10-22T07:08:00', '未记录'], ['invalid', '未记录'], ['2026-02-30T07:08:00Z', '未记录'], ['2026-10-22T24:00:00Z', '未记录'], ]) assert.equal(run('orderEntryTime(' + JSON.stringify(created) + ')'), expected, String(created)); }); test('详情业务日期与首次录入时间分开,旧草稿、补齐旧单和锁价销售均不伪称开单时间', () => { const created = '2026-10-23T01:06:59Z'; for (const extra of [ {}, { status: 'draft' }, { price_lock_id: 'synthetic-lock' }, { audit: [{ action: '生成已交付单据', actor: '合成开单人', created: '2026-10-24T02:30:00Z', detail: {} }] }, ]) { const { html } = render(order({ created, ...extra })); assert.match(html, /业务日期 2026-10-22/); assert.match(html, /
录入时间(北京时间):2026-10-23 09:06<\/div>/); assert.doesNotMatch(html, /开单时间/); } assert.match(render(order({ created: D })).html, /录入时间(北京时间):未记录/); }); test('打开单据即显示截图中的销售计算、附加收费、整单取整和实际利润,只有一份成本明细', () => { const { html } = render(), sales = text(panel(html, '销售计算')), costs = panel(html, '成本明细与付款人'), profit = text(panel(html, '实际订单利润')); assert.match(sales, /0\.620g ×(金价 927\.00元\/克 + 工费 45\.00元\/克) = ¥602\.64/); assert.match(sales, /+ 附加工艺 ¥150\.00/); assert.match(sales, /本行合计¥752\.64/); assert.match(sales, /¥752\.64 → ¥753(\+0\.36元)/); assert.match(text(costs), /¥556\.14 + ¥9\.30 + ¥6\.00 = ¥571\.44/); assert.match(profit, /成交金额 ¥753\.00 − 成本合计 ¥571\.44 = 实际订单利润 ¥181\.56/); assert.equal((costs.match(/料费成本/g) || []).length, 1); assert.doesNotMatch(html, /商品与成本|按付款人汇总成本|零元包装|配件成本|其他货品成本/); assert.match(html, /
与娜娜的结算/); assert.match(html, /收退款与费用记录/); assert.match(html, /商品来源与原始说明/); }); test('详情审批印章仅认可当前已复核版本,待审批与历史批准不冒充整单已审批', () => { const seal = html => html.includes('class="order-review-seal"'); for (const role of ['owner', 'assistant']) { const html = render(order(), role).html; assert.equal(seal(html), true); assert.match(html, /已审批/); assert.match(html, /店主已复核/); assert.match(html, /

合成客户<\/h2>/); } for (const extra of [ { reviewed_revision: 2 }, { reviewed_revision: 0 }, { revision: 0, reviewed_revision: 0 }, { revision: -1, reviewed_revision: -1 }, { revision: 1.5, reviewed_revision: 1.5 }, { revision: 3, reviewed_revision: '3' }, { changePending: { status: 'pending' } }, { cancellationPending: { status: 'pending' } }, { reviewed_revision: 2, changeApproved: { status: 'approved' } }, { reviewed_revision: 2, cancellationApproved: { status: 'approved', direct: true, requester_name: '助理' } }, { revision: 4, reviewed_revision: 3, audit: [{ action: 'expense', actor: '助理', created: D + 'T10:00:00Z', detail: { reason: '当天直接补费用' } }], }, ]) assert.equal(seal(render(order(extra)).html), false, JSON.stringify(extra)); }); test('件工费使用保存的件数,不能误乘克重;一件与多件均清楚', () => { for (const pieces of [1, 3]) { const base = 108000 + pieces * 5000, l = zeroLine({ quantity: 1200, goldPrice: 90000, laborMode: 'piece', laborRate: 5000, pieces, baseSale: base, sale: base, charges: [], }); const sales = text( panel( render( order({ ...withoutFees, lines: [l], total: base, rounding_mode: 'cent', rounding_adjustment: 0, goodsCost: 0, profit: base, }), ).html, '销售计算', ), ); assert.ok(sales.includes(`1.200g × 金价 900.00元/克 + ${pieces}件 × 件工费 50.00元/件`)); assert.ok(sales.includes('¥' + (base / 100).toLocaleString('zh-CN', { minimumFractionDigits: 2 }))); assert.doesNotMatch(sales, /1\.200g ×(/); } }); test('手填基础金额是本行总额,按件数量不再乘一次;历史无计价元数据也不编造公式', () => { for (const pricingMode of ['manual', undefined]) { const l = zeroLine({ pricingMode, unit: '件', quantity: 3, baseSale: 12345, sale: 13345, charges: [{ name: '证书', amount: 1000 }], priceNote: '手填总额说明', }); const sales = text( panel( render( order({ ...withoutFees, lines: [l], total: 13345, rounding_mode: 'cent', rounding_adjustment: 0, goodsCost: 0, profit: 13345, }), ).html, '销售计算', ), ); assert.match(sales, /直接填基础金额 ¥123\.45/); assert.match(sales, /手填总额说明/); assert.match(sales, /+ 证书 ¥10\.00/); assert.match(sales, /本行合计¥133\.45/); assert.doesNotMatch(sales, /×|金价 927/); } }); test('多商品先合并附加费与整单优惠,再做一次整单取整;分模式保持原成交到分', () => { const second = zeroLine({ name: '纯银925', pricingMode: 'manual', unit: '件', quantity: 2, baseSale: 20000, sale: 20000, charges: [], }), lines = [line(), second]; const rounded = order({ lines, discount: 101, total: 95200, rounding_adjustment: 37, profit: 38056 }); const sales = text(panel(render(rounded).html, '销售计算')); assert.match(sales, /销售小计¥952\.64/); assert.match(sales, /- 整单优惠¥1\.01/); assert.match(sales, /¥951\.63 → ¥952(\+0\.37元)/); const cents = text( panel( render(order({ ...rounded, rounding_mode: 'cent', rounding_adjustment: 0, total: 95163, profit: 38019 })).html, '销售计算', ), ); assert.doesNotMatch(cents, /四舍五入/); assert.match(cents, /成交金额¥951\.63/); }); test('原始销售金额与单位均来自保存的整数,显示不会再次运行录入计算器', () => { const saved = order({ ...withoutFees, lines: [zeroLine({ quantity: 1, goldPrice: 100050, laborRate: 0, baseSale: 100, sale: 100, charges: [] })], total: 100, rounding_mode: 'cent', rounding_adjustment: 0, goodsCost: 0, profit: 100, }); const sales = text(panel(render(saved).html, '销售计算')); assert.match(sales, /0\.001g ×(金价 1,000\.50元\/克 + 工费 0\.00元\/克) = ¥1\.00/); }); test('已核实的全零成本与缺失成本明确区分,零费用和零预估项目均省略', () => { const zero = order({ ...withoutFees, lines: [zeroLine()], goodsCost: 0, profit: 75300, fee_items: [{ key: 'box', note: '零元包装', amount: 0, payer: 'owner', status: 'recorded' }], pendingFees: [{ key: 'other', note: '零元预估', amount: 0, payer: 'assistant' }], }); const html = render(zero).html, costs = panel(html, '成本明细与付款人'); assert.match(costs, /已核实成本为 ¥0\.00/); assert.doesNotMatch(costs, /待补齐|零元包装|零元预估|进货工费|配件成本|其他货品成本/); assert.match(text(panel(html, '实际订单利润')), /¥753\.00 − 成本合计 ¥0\.00 = 实际订单利润 ¥753\.00/); const missing = order({ ...withoutFees, lines: [ line({ cost: null, costParts: { material: null, labor: 0, accessories: 0, other: 0 }, costMaterial: { mode: 'pool', poolId: D }, materialPool: { averageRate: null, allocations: [] }, }), ], goodsCost: null, knownGoodsCost: 0, materialCostPending: true, profit: null, settlementDue: null, }); const missingHTML = render(missing).html, missingCosts = panel(missingHTML, '成本明细与付款人'); assert.match(missingCosts, /待补齐/); assert.match(missingCosts, /待补采购后分摊/); assert.match(missingCosts, /已知成本/); assert.match(missingCosts, /补足当日购料/); assert.doesNotMatch(missingCosts, /已核实成本为/); assert.match(panel(missingHTML, '实际订单利润'), /待核算/); assert.doesNotMatch(missingHTML, /NaN/); assert.doesNotMatch(missingHTML, /data-action="show-settlement"/); }); test('付款人小计只加有效已记账成本,零付款人省略,缺成本的非零小计标已知', () => { const subtotals = html => html.match(/

]*>([\s\S]*?)<\/p>/)?.[1] || ''; const normal = text(subtotals(render().html)); assert.match(normal, /付款人合计麦麦 ¥556\.14娜娜 ¥15\.30/); assert.doesNotMatch(normal, /已知/); const missing = order({ goodsCost: null, knownGoodsCost: 930, profit: null, lines: [line({ cost: null, costParts: { material: null, labor: 930, accessories: 0, other: 0 } })], }); const partial = text(subtotals(render(missing).html)); assert.match(partial, /付款人合计(已知)娜娜 ¥15\.30/); assert.doesNotMatch(partial, /麦麦/); const returned = text(subtotals(render(order({ status: 'returned', profit: -600 })).html)); assert.equal(returned, '付款人合计娜娜 ¥6.00'); assert.equal(subtotals(render(order({ ...withoutFees, lines: [zeroLine()], goodsCost: 0, profit: 75300 })).html), ''); }); test('未入账费用单列,空值保留待补,已填估算不混入真实成本或实际利润', () => { const saved = order({ status: 'confirmed', profit: 0, pendingFees: [ { key: 'one', note: '待核快递', amount: null, payer: 'assistant' }, { key: 'two', note: '待核编绳', amount: 300, payer: 'owner' }, { key: 'zero', note: '零估算', amount: 0, payer: 'owner' }, ], }); const html = render(saved).html, costs = panel(html, '成本明细与付款人'); assert.match(costs, /以下 2 项费用尚未入账,不计入成本合计和实际利润/); assert.match(costs, /待核快递/); assert.match(costs, /待核编绳/); assert.match(costs, /待补齐/); assert.doesNotMatch(costs, /零估算/); assert.match(text(costs), /¥556\.14 + ¥9\.30 + ¥6\.00 = ¥571\.44/); assert.match(panel(html, '实际订单利润'), /尚未完成销售记账/); }); test('日购料按整行实际耗用金额呈现,付款人分摊不冒充整行克重乘均价', () => { const pooled = line({ quantity: 2000, goldPrice: 100000, laborRate: 10000, baseSale: 220000, sale: 220000, charges: [], cost: 190000, costParts: { material: 190000, labor: 0, accessories: 0, other: 0 }, costMaterial: { mode: 'pool', poolId: D }, materialPool: { revision: 4, averageRate: 95000, allocations: [ { payer: 'owner', amount: 80000 }, { payer: 'assistant', amount: 110000 }, ], }, }); const html = render( order({ ...withoutFees, lines: [pooled], goodsCost: 190000, total: 220000, rounding_mode: 'cent', rounding_adjustment: 0, profit: 30000, }), ).html, costs = panel(html, '成本明细与付款人'); assert.equal((costs.match(/料费成本/g) || []).length, 1); assert.match(costs, /耗用 2\.000g · 加权均价约 950\.00元\/克;按实际购料分摊/); assert.match(costs, /麦麦 ¥800\.00
娜娜 ¥1,100\.00/); assert.match(costs, /class="number">¥1,900\.00/); assert.doesNotMatch(costs, /2\.000g ×|= ¥800\.00|= ¥1,100\.00/); assert.match(costs, /麦麦 ¥800\.00<\/b><\/span>娜娜 ¥1,100\.00/); }); test('加权均价取整与累计分币差额保留实际金额,不由展示均价重算料费', () => { const pooled = zeroLine({ quantity: 1001, cost: 33367, costParts: { material: 33367, labor: 0, accessories: 0, other: 0 }, costMaterial: { mode: 'pool', poolId: D }, materialPool: { averageRate: 33333, allocations: [ { payer: 'owner', amount: 16683 }, { payer: 'assistant', amount: 16684 }, ], }, }); const costs = panel( render(order({ ...withoutFees, lines: [pooled], goodsCost: 33367, profit: 41933 })).html, '成本明细与付款人', ); assert.match(costs, /均价约 333\.33元\/克/); assert.match(costs, /¥333\.67/); assert.match(costs, /麦麦 ¥166\.83
娜娜 ¥166\.84/); assert.doesNotMatch(costs, /¥333\.66/); }); test('锁价原料与补重分段保留真实克重、单价、付款人及料费合计', () => { const locked = line({ quantity: 3200, baseSale: 320000, sale: 320000, charges: [], cost: 273000, costParts: { material: 273000, labor: 0, accessories: 0, other: 0 }, costMaterial: { mode: 'total' }, materialAllocations: [ { source: 'original', payer: 'owner', quantity: 3000, rate: 85000, amount: 255000 }, { source: 'extra', payer: 'assistant', quantity: 200, rate: 90000, amount: 18000 }, ], }); const costs = panel( render( order({ ...withoutFees, price_lock_id: 'lock', lines: [locked], goodsCost: 273000, total: 320000, rounding_mode: 'cent', rounding_adjustment: 0, profit: 47000, }), ).html, '成本明细与付款人', ); assert.match(costs, /原锁料费/); assert.match(costs, /3\.000g × 850\.00元\/克/); assert.match(costs, /补重料费/); assert.match(costs, /0\.200g × 900\.00元\/克/); assert.match(costs, /¥2,550\.00 + ¥180\.00 = ¥2,730\.00/); assert.match(costs, /麦麦/); assert.match(costs, /娜娜/); }); test('退货与取消显示冲回后的净额,原料费收起保留且不混入成本合计', () => { for (const status of ['returned', 'cancelled']) { const html = render(order({ status, profit: -600, netReceived: 0 })).html, costs = panel(html, '成本明细与付款人'), title = status === 'returned' ? '退货后净额' : '取消后净额'; assert.match(text(panel(html, '销售计算')), /原销售已冲回/); assert.match(text(panel(html, '销售计算')), /原成交金额¥753/); assert.match(costs, /

原货品成本(已冲回,不计当前成本)/); const active = costs.split('
')[0]; assert.doesNotMatch(active, /料费成本|进货工费/); assert.match(active, /¥6\.00 = ¥6\.00/); assert.ok(text(panel(html, title)).includes(`销售净额 ¥0.00 − 保留成本 ¥6.00 = ${title} ¥-6.00`)); assert.doesNotMatch(html, /

实际订单利润/); } }); test('审批作废与草稿不显示正常成交利润,原流水与核对入口仍可查', () => { const cancelled = order({ status: 'cancelled', cancellationApproved: { id: 'approved' }, profit: 0, directCost: 0, netReceived: 0, expenses: [ { id: 'expense', date: D, amount: 600, payer: 'assistant', note: '原快递' }, { id: 'reverse', date: D, amount: -600, payer: 'assistant', note: '更正冲回:取消审批作废;重复' }, ], corrections: [{ type: 'expense', target: 'expense' }], }); const voidHTML = render(cancelled).html; assert.match(voidHTML, /原成交金额(已作废)/); assert.match(voidHTML, /已撤销的金额不计入本单成本/); assert.match(voidHTML, /作废冲回费用/); assert.match(voidHTML, /作废后净额/); assert.doesNotMatch(voidHTML, /

实际订单利润/); const draftHTML = render(order({ status: 'draft', profit: 0 })).html; assert.match(panel(draftHTML, '销售计算'), /报价合计/); assert.match(panel(draftHTML, '实际订单利润'), /尚未完成销售记账/); assert.doesNotMatch(panel(draftHTML, '实际订单利润'), /= 实际订单利润/); }); test('有效负费用不因零项精简被隐藏,更正冲回仍只留在历史流水', () => { const saved = order({ directCost: 400, profit: 18356, expenses: [ { id: 'shipping', date: D, amount: 600, payer: 'assistant', note: '快递费' }, { id: 'credit', date: D, amount: -200, payer: 'owner', note: '实际费用返还' }, ], }); const html = render(saved).html, costs = panel(html, '成本明细与付款人'); assert.match(costs, /实际费用返还/); assert.match(costs, /¥-2\.00/); assert.match(costs, /¥569\.44/); assert.match(panel(html, '实际订单利润'), /¥183\.56/); const corrected = order({ directCost: 800, profit: 17956, expenses: [ { id: 'old', date: D, amount: 600, payer: 'assistant', note: '原费用' }, { id: 'rev', date: D, amount: -600, payer: 'assistant', note: '更正冲回:改为8元' }, { id: 'new', date: D, amount: 800, payer: 'owner', note: '更正补记:实际8元' }, ], corrections: [{ type: 'expense', target: 'old' }], }); const correctedHTML = render(corrected).html, correctedCosts = panel(correctedHTML, '成本明细与付款人'); assert.doesNotMatch(correctedCosts, /原费用|更正冲回/); assert.match(correctedCosts, /更正补记:实际8元/); assert.match(correctedHTML, /更正冲回:改为8元/); }); test('金额与分项不吻合时使用权威合计和已记账利润,避免展示错误等式', () => { const saved = order({ goodsCost: 60000, profit: 12345 }), html = render(saved).html; assert.match(text(panel(html, '成本明细与付款人')), /¥600\.00 + ¥6\.00 = ¥606\.00/); const profit = text(panel(html, '实际订单利润')); assert.match(profit, /¥123\.45/); assert.match(profit, /利润沿用已记账金额/); assert.doesNotMatch(profit, /= 实际订单利润/); }); test('名称、备注和来源转义,助理保留申请动作且读取不会触发写操作', () => { const html = render( order({ lines: [line({ name: '', priceNote: '', pocket: '<货盘>' })], note: '客户备注', }), 'assistant', ).html; assert.doesNotMatch(html, /客户备注/); assert.match(html, /<img src=x onerror=1>/); assert.match(html, /<货盘>/); assert.match(html, /<b>客户备注<\/b>/); assert.match(html, />申请修改<\/button>/); assert.match(html, />申请补记费用<\/button>/); assert.match(html, />申请整单退货<\/button>/); assert.match(html, /data-action="print"/); }); test('内部备注在客户名旁只显示一次并转义换行,不进入客户销售计算区', () => { const note = html => { const match = html.match(/]*aria-label="内部备注(客户不可见)"[^>]*>([\s\S]*?)<\/aside>/); assert.ok(match); return match[1]; }; const { html } = render(order({ internal_note: '内部尺寸跟进\n' }), 'assistant'), internal = note(html); assert.equal((html.match(/class="detail-internal-note"/g) || []).length, 1); assert.ok(html.indexOf('detail-internal-note') > html.indexOf('order-detail-title')); assert.ok(html.indexOf('detail-internal-note') < html.indexOf('order-detail-identifiers')); assert.match(internal, /内部尺寸跟进
<img src=x onerror=1>/); assert.doesNotMatch(internal, /