'use strict';
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 = vm.createContext({
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('
]*>([\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(/