'use strict';
const { test } = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
path = require('node:path'),
vm = require('node:vm'),
{ randomUUID } = require('node:crypto');
const Calc = require('../public/calculations'),
Card = require('../public/credit-card-fees'),
{ Ledger } = require('../core/ledger'),
{ createUser } = require('../server');
const D = '2026-10-25';
function harness(member = 'owner') {
const nodes = new Map(),
saved = new Map(),
handlers = {},
posts = [],
user = {
id: 'synthetic-' + member,
name: member === 'owner' ? '合成麦麦' : '合成张',
label: member === 'owner' ? '麦麦' : member === 'assistant' ? '助理1' : '助理2',
member,
role: member === 'owner' ? 'owner' : 'assistant',
};
const context = vm.createContext({
console,
URLSearchParams,
LedgerCalc: Calc,
CreditCardFees: Card,
crypto: { randomUUID },
setTimeout() {
return 1;
},
clearTimeout() {},
setInterval() {},
window: { scrollTo() {}, open() {} },
document: {
querySelector: q => nodes.get(q) || null,
querySelectorAll: () => [],
addEventListener: (type, fn) => (handlers[type] ??= []).push(fn),
},
FormData: class {
constructor(form) {
return Object.entries(form.values || {});
}
},
localStorage: {
getItem: k => saved.get(k) || null,
setItem: (k, v) => saved.set(k, String(v)),
removeItem: k => saved.delete(k),
},
sessionStorage: {
getItem() {
return null;
},
setItem() {},
},
__user: user,
__posts: posts,
});
const run = code => vm.runInContext(code, context),
json = code => JSON.parse(JSON.stringify(run(code)));
for (const file of ['material-pools-ui.js', 'recoveries-ui.js', 'app.js'])
run(fs.readFileSync(path.join(__dirname, '../public', file), 'utf8').replace(/\ninit\(\);\s*$/, ''));
run(
`session={user:__user,mode:'demo'};state={user:__user,members:[{member:'owner'},{member:'assistant'},{member:'assistant2'}],today:'${D}',accounts:['麦麦微信','麦麦支付宝','麦麦现金','麦麦信用卡','助理微信','助理支付宝','助理现金','助理2微信','助理2支付宝','助理2现金'],pockets:['现货','金料','找金','回收旧料','君宝汇']};tab='recoveries';toast=function(){};showPending=function(){};api=async function(url,data,key){__posts.push({url,data,key});return {saved:true};};`,
);
function draft(values = {}) {
context.__values = values;
return json('({...recoveryDefaults(),...__values})');
}
function input(values = {}, options = {}) {
context.__draft = draft(values);
context.__options = options;
return json('recoveryInput(__draft,__options)');
}
function calculate(value) {
context.__input = value;
return json('recoveryCalculate(__input)');
}
function form(values = {}) {
const data = draft(values),
elements = Object.fromEntries(
Object.entries(data).map(([name, value]) => [
name,
{ value: String(value), checked: name === 'verified' && value === true, dataset: {} },
]),
);
elements.namedItem = name => elements[name];
return {
elements,
dataset: Object.fromEntries(
['buy_total_manual', 'depreciation_manual', 'melted_manual'].map(key => [key, String(data[key] === true)]),
),
};
}
return { run, json, context, nodes, saved, handlers, posts, user, draft, input, calculate, form };
}
const base = {
customer: '合成客户',
incoming_weight: '20',
melted_weight: '20',
purity: '100',
buy_rate: '900',
verified: true,
};
const swap = {
...base,
mode: 'exchange',
new_quantity: '30',
gold_price: '1000',
labor_rate: '20',
material_source: 'manual',
material_rate: '900',
cost_labor_value: '5',
};
test('旧料入库选择保存草稿与payload,找金不受self限制,计对入库和新货出库各填各的', () => {
const h = harness();
h.run(
`state.pockets.push('合成对数盘');state.pocketCatalog=[{key:'找金',name:'找金
',active:true,self:false},{key:'合成对数盘',name:'合成对数盘',active:true,self:true,countUnit:'pair',countSince:'${D}'}];`,
);
assert.equal(h.draft().old_pocket, '回收旧料');
const input = h.input({ ...swap, old_pocket: '找金', old_stock_count: '99' });
assert.equal(input.old_pocket, '找金');
assert.equal(input.old_stock_count, undefined);
assert.equal(input.exchange.pocket, '现货');
h.context.__input = input;
assert.doesNotThrow(() => h.run('validateRecoveryInput(__input)'));
const counted = h.input({
...swap,
old_pocket: '合成对数盘',
old_stock_count: '3',
pocket: '合成对数盘',
stockCount: '2',
});
assert.equal(counted.old_stock_count, '3');
assert.equal(counted.exchange.stockCount, '2');
h.context.__input = counted;
assert.doesNotThrow(() => h.run('validateRecoveryInput(__input)'));
counted.old_stock_count = null;
assert.throws(() => h.run('validateRecoveryInput(__input)'), /旧料入库数量/);
h.context.__draft = h.draft({ ...base, old_pocket: '找金' });
const html = h.run('recoveryFormHTML(__draft)');
assert.match(html, /旧料入库货盘/);
assert.match(html, /name="old_pocket"/);
assert.match(html, /name="old_stock_count"/);
assert.match(html, /找金<img src=x>/);
assert.doesNotMatch(html, /找金
{
const h = harness();
h.context.__draft = h.draft();
const html = h.run('recoveryFormHTML(__draft)');
for (const text of [
'直接回收',
'置换',
'客户称呼/代号',
'来料重量',
'熔后重量',
'成色(%)',
'折后重量',
'内部成本',
'保存后自动编号',
])
assert.ok(html.includes(text));
assert.match(html, /