Files
weiguang-jewelry-ledger/新账系统/test/pair-inventory-ui.test.js
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

439 lines
17 KiB
JavaScript
Raw Normal View History

'use strict';
const { createBrowserContext } = require('./fixtures/browser-context.cjs');
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
vm = require('node:vm'),
{ randomUUID } = require('node:crypto');
const D = '2026-11-08',
PAIR = 'pocket-from-live-catalog',
PLAIN = '现货';
function node(extra = {}) {
return {
innerHTML: '',
textContent: '',
value: '',
checked: false,
hidden: false,
disabled: false,
required: false,
dataset: {},
classList: { toggle() {} },
setAttribute() {},
scrollIntoView() {},
querySelector() {
return null;
},
querySelectorAll() {
return [];
},
closest() {
return null;
},
...extra,
};
}
function harness() {
const nodes = new Map(),
events = {},
writes = [];
for (const id of [
'main',
'stock-error',
'stock-submit',
'price-lock-error',
'pocket-manager-error',
'detail-error',
'detail-form',
'order-cancellation-error',
])
nodes.set('#' + id, node());
const context = createBrowserContext({
console,
URLSearchParams,
crypto: { randomUUID },
setTimeout() {},
clearTimeout() {},
setInterval() {},
window: {
scrollTo() {},
confirm() {
return true;
},
},
document: {
querySelector: s => nodes.get(s) || null,
querySelectorAll: () => [],
addEventListener(type, fn) {
(events[type] ??= []).push(fn);
},
},
FormData: class {
constructor(form) {
return Object.entries(form.values || {});
}
},
localStorage: {
getItem() {
return null;
},
setItem() {},
removeItem() {},
},
sessionStorage: {
getItem() {
return null;
},
setItem() {},
},
__writes: writes,
});
const run = code => vm.runInContext(code, context),
json = code => JSON.parse(JSON.stringify(run(code)));
for (const file of [
'calculations.js',
'fee-estimates.js',
'credit-card-fees.js',
'order-copy.js',
'order-templates.js',
'price-locks-ui.js',
'order-edit-ui.js',
'order-changes-ui.js',
'order-cancellations-ui.js',
'inventory-changes-ui.js',
'recoveries-ui.js',
'recovery-changes-ui.js',
'pockets-ui.js',
'app.js',
])
run(fs.readFileSync(require.resolve('../public/' + file), 'utf8').replace(/\ninit\(\);\s*$/, ''));
run(
`state={user:{id:'synthetic-owner',name:'合成麦麦',role:'owner',member:'owner'},today:'${D}',pockets:['${PLAIN}','${PAIR}'],pocketCatalog:[{key:'${PLAIN}',name:'普通盘',active:true,revision:1},{key:'${PAIR}',name:'任意新名字',active:true,countUnit:'pair',revision:4}],accounts:['麦麦微信'],orders:[]};session={user:state.user};tab='stock';toast=()=>{};mutate=async(url,data)=>{__writes.push({url,data});return {id:'synthetic-result'};};refresh=async()=>{};`,
);
function form(values = {}, extra = {}) {
const fields = Object.fromEntries(
Object.entries(values).map(([name, value]) => {
const label = node();
return [
name,
node({
name,
value: typeof value === 'boolean' ? 'on' : String(value ?? ''),
checked: value === true,
closest: selector => (!selector || selector === 'label' ? label : null),
}),
];
}),
);
const result = node({
values,
elements: fields,
querySelector(selector) {
const name = selector.match(/\[name="([^"]+)"\]/)?.[1];
return fields[name] || null;
},
querySelectorAll(selector) {
return selector === 'input,select' ? Object.values(fields) : [];
},
...extra,
});
result.fields = fields;
return result;
}
return {
context,
run,
json,
nodes,
writes,
form,
async submit(form) {
for (const fn of events.submit || []) await fn({ target: form, preventDefault() {} });
},
};
}
function ordinaryLine(extra = {}) {
return {
name: '足金999',
unit: 'g',
quantity: '2.000',
pocket: PAIR,
stockCount: '2',
pricingMode: 'manual',
baseSale: '2000',
sale: '2000',
pieces: '9',
cost: '1800',
charges: [],
...extra,
};
}
test('计数只读catalog配置,改名不改范围;正整数与工费pieces独立,旧值保持未知', () => {
const h = harness();
assert.equal(h.run(`pocketCountsEnabled('${PAIR}')`), true);
assert.equal(h.run(`pocketCountsEnabled('耳钉')`), false);
const html = h.run(`lineHTML({name:'足金999',unit:'g',pocket:'${PAIR}',quantity:'2',stockCount:3,pieces:9})`);
assert.match(html, /name="stockCount" value="3"/);
assert.match(html, /name="pieces" value="9"/);
assert.match(html, /出库数量(对)/);
h.context.__draft = {
customer: '合成客户',
internal_note: '测试内部备注',
salesperson: '合成麦麦',
date: D,
fee_items: [],
discount: '0',
lines: [ordinaryLine()],
};
assert.doesNotThrow(() => h.run('validateIssueDraft(__draft)'));
for (const value of ['', 0, -1, '1.5', '1e2', '1000000001']) {
h.context.__draft.lines[0].stockCount = value;
assert.throws(() => h.run('validateIssueDraft(__draft)'), /出库数量(对).*整数/);
}
h.context.__draft.lines[0].stockCount = null;
h.run(`orderEditEntry={originalInputs:{lines:[{pocket:'${PAIR}',quantity:'2.000',stockCount:null}]}};`);
h.nodes.set('#order-form', { dataset: { orderEdit: 'true' } });
assert.doesNotThrow(() => h.run('validateIssueDraft(__draft)'));
assert.equal(h.run('__draft.lines[0].stockCount'), null);
h.context.__draft.lines[0].quantity = '3';
assert.throws(() => h.run('validateIssueDraft(__draft)'), /出库数量(对)/);
});
test('订单收集只将启用货盘的独立对数发出,切换普通货盘保留工费件数且不误扣对数', () => {
const h = harness(),
row = h.form(
{ nameType: '足金999', unit: 'g', quantity: '2', pocket: PAIR, stockCount: '3', pieces: '8' },
{ dataset: { legacy: 'true' } },
);
h.context.__row = row;
assert.equal(h.json('collectLine(__row)').stockCount, '3');
row.fields.pocket.value = PLAIN;
const plain = h.json('collectLine(__row)');
assert.equal(plain.stockCount, undefined);
assert.equal(plain.pieces, '8');
row.fields.pocket.value = PAIR;
row.fields.stockCount.value = '';
assert.equal(h.json('collectLine(__row)').stockCount, null);
const label = row.fields.stockCount.closest();
h.run(`syncStockCountField(__row,{pocket:'${PAIR}'})`);
assert.equal(label.hidden, false);
assert.equal(row.fields.stockCount.required, true);
h.run(`syncStockCountField(__row,{pocket:'${PLAIN}'})`);
assert.equal(label.hidden, true);
assert.equal(row.fields.stockCount.disabled, true);
});
test('owner启用对数必须盘点整数并确认,更新沿原稳定key与版本,不带克重', async () => {
const h = harness();
h.run(
`pocketManagerRows=[{key:'${PAIR}',name:'已存在的盘',active:true,countUnit:null,revision:7}];finishPocketManagementSave=async()=>{};`,
);
const form = h.form(
{ name: '改名后', enableCounts: true, initialCount: '12', countVerified: true },
{ id: 'rename', dataset: { pocketKey: PAIR } },
);
h.context.__form = form;
await h.run('submitPocketManagement(__form)');
assert.equal(h.writes.length, 1);
assert.deepEqual(JSON.parse(JSON.stringify(h.writes[0].data)), {
name: '改名后',
revision: 7,
countUnit: 'pair',
initialCount: 12,
countVerified: true,
});
assert.equal(h.writes[0].url, '/api/pockets/' + PAIR + '/update');
assert.equal(h.writes[0].data.grams, undefined);
for (const invalid of ['', '1.5', '-1']) {
h.writes.length = 0;
form.fields.initialCount.value = invalid;
await h.run('submitPocketManagement(__form)');
assert.equal(h.writes.length, 0);
}
form.fields.initialCount.value = '0';
form.fields.countVerified.checked = false;
await h.run('submitPocketManagement(__form)');
assert.equal(h.writes.length, 0);
assert.doesNotMatch(h.run(`pocketCountSettingsHTML({countUnit:'pair'})`), /name="enableCounts"/);
});
test('手动增减、平移及只调对数携带count,非整数阻断,助理没有对数调整入口', async () => {
const h = harness();
for (const values of [
{ kind: 'increase', grams: '3.000', stockCount: '2', pocket: PAIR },
{ kind: 'decrease', grams: '1.000', stockCount: '1', pocket: PAIR },
{ kind: 'transfer', grams: '1.000', stockCount: '1', pocket: PLAIN, to: PAIR },
{ kind: 'adjustment', grams: '0', stockCount: '-2', pocket: PAIR },
]) {
const form = h.form({ ...values, date: D, note: '' }, { id: 'stock-form' });
await h.submit(form);
assert.equal(h.writes.at(-1).data.stockCount, Number(values.stockCount));
}
const before = h.writes.length;
await h.submit(
h.form({ kind: 'increase', grams: '2', stockCount: '1.5', pocket: PAIR, date: D }, { id: 'stock-form' }),
);
assert.equal(h.writes.length, before);
h.run(`state.user.role='assistant';`);
assert.doesNotMatch(h.run('stockEntryForm()'), /value="adjustment"/);
await h.submit(
h.form({ kind: 'adjustment', grams: '0', stockCount: '2', pocket: PAIR, date: D }, { id: 'stock-form' }),
);
assert.equal(h.writes.length, before);
});
test('零克重对数流水仍显示并可按增减筛选,库存和旧快照缺数显示未记录', () => {
const h = harness();
const html = h.run(
`stockCards({current:[{pocket:'${PLAIN}',mg:0},{pocket:'${PAIR}',mg:12500,countUnit:'pair',count:6,reservedCount:0,availableCount:6}],yesterdayDate:'2026-11-07',yesterday:{date:'2026-11-07',inventory:[{pocket:'${PAIR}',mg:12000}]}})`,
);
assert.match(html, /12\.500/);
assert.match(html, />6对</);
assert.match(html, /未记录对数/);
assert.doesNotMatch(html, />0对</);
const movements = h.run(
`stockMovementRows([{id:'only-count',date:'${D}',pocket:'${PAIR}',mg:0,stockCount:-2,kind:'adjustment',actor:'合成',manual:true,current:true,status:'active'}])`,
);
assert.match(movements, /0\.000g/);
assert.match(movements, /-2对/);
assert.equal(h.run(`inventoryMovementMatches({mg:0,stockCount:-2,manual:true,kind:'adjustment'},'decrease')`), true);
const summary = h.run(
`inventoryChangeFacts({kind:'increase',date:'${D}',pocket:'${PAIR}',grams:'2.000',stockCount:2},'申请值')`,
);
assert.match(summary, /2对/);
});
test('退货按实际去向收集实际对数,未知旧单不从工费件数推导,退普通盘不增加对数', () => {
const h = harness(),
form = h.form({ 'return-0': PAIR, 'returnCount-0': '3' });
h.context.__form = form;
assert.deepEqual(h.json(`readReturnCounts(__form,['${PAIR}'])`), [3]);
form.fields['returnCount-0'].value = '';
assert.throws(() => h.run(`readReturnCounts(__form,['${PAIR}'])`), /实际退回数量(对)/);
assert.deepEqual(h.json(`readReturnCounts(__form,['${PLAIN}'])`), [null]);
h.run('currentOrder={lines:[{stockCount:2}]};');
form.dataset.kind = 'return';
h.run('syncReturnCounts(__form)');
assert.equal(form.fields['returnCount-0'].readOnly, true);
assert.equal(form.fields['returnCount-0'].value, '2');
form.fields['returnCount-0'].value = '3';
assert.throws(() => h.run(`readReturnCounts(__form,['${PAIR}'])`), /原出库的2对一致/);
assert.equal(h.run('stockCountText(null)'), '未记录对数');
assert.equal(h.run('stockCountValue("0",{zero:true})'), 0);
});
test('模板对数独立保存与套用,未知历史保持未填,不从pieces补1', () => {
const h = harness();
h.context.__draft = { lines: [ordinaryLine()], fee_items: [], discount: '0' };
const saved = h.json(`OrderTemplates.fromDraft(__draft,{pocketKeys:['${PAIR}','${PLAIN}']})`);
assert.equal(saved.lines[0].stockCount, '2');
assert.equal(saved.lines[0].pieces, '9');
h.context.__preset = saved;
assert.equal(
h.json(`OrderTemplates.apply(__preset,{today:'${D}',pocketKeys:['${PAIR}','${PLAIN}']})`).lines[0].stockCount,
'2',
);
h.context.__draft.lines[0].stockCount = null;
assert.equal(h.json(`OrderTemplates.fromDraft(__draft,{pocketKeys:['${PAIR}']})`).lines[0].stockCount, undefined);
h.context.__draft.lines[0].stockCount = '0';
assert.throws(() => h.run(`OrderTemplates.fromDraft(__draft,{pocketKeys:['${PAIR}']})`), /正整数/);
});
test('置换新货发送stockCount并校验,未知历史只改财务保留null,新货详情与更正显示对数', () => {
const h = harness();
h.run("state.pockets.push('回收旧料');");
h.context.__draft = h.json(
`({...recoveryDefaults('exchange'),customer:'合成客户',incoming_weight:'2',melted_weight:'2',purity:'100',new_quantity:'3',stockCount:'2',pocket:'${PAIR}',gold_price:'1000',labor_rate:'0',buy_rate:'0',material_source:'manual',material_rate:'900',cost_labor_value:'0',verified:true})`,
);
const input = h.json('recoveryInput(__draft)');
assert.equal(input.exchange.stockCount, '2');
h.context.__input = input;
assert.doesNotThrow(() => h.run('validateRecoveryInput(__input)'));
h.context.__input.exchange.stockCount = null;
assert.throws(() => h.run('validateRecoveryInput(__input)'), /新货出库数量(对)/);
h.run(`recoveryEditEntry={data:{inputs:{exchange:{stockCount:null,pocket:'${PAIR}',quantity:'3'}}}};`);
h.nodes.set('#recovery-form', { dataset: { recoveryEdit: 'true' } });
assert.doesNotThrow(() => h.run('validateRecoveryInput(__input)'));
const form = h.run('recoveryFormHTML(__draft)');
assert.match(form, /name="stockCount" value="2"/);
assert.doesNotMatch(form, /name="stockCount" value="1"/);
});
test('历史改删和取消显示清点基准说明,未勾选不提交,不将未知数显示为0', () => {
const h = harness(),
info = { requiresLegacyCountVerified: true, legacyCountNotice: '已盘点基准保留,请另做当天调整' };
h.context.__info = info;
assert.match(h.run('legacyCountConfirmationHTML(__info)'), /name="legacyCountVerified"/);
const form = h.form({ legacyCountVerified: false });
h.context.__form = form;
assert.throws(() => h.run('requireLegacyCountConfirmation(__form,__info)'), /勾选/);
form.fields.legacyCountVerified.checked = true;
assert.deepEqual(h.json('requireLegacyCountConfirmation(__form,__info)'), { legacyCountVerified: true });
h.context.__detail = { values: { kind: 'increase', date: D, pocket: PAIR, grams: '2', stockCount: null }, ...info };
const html = h.run(`inventoryChangeFormHTML(__detail,'synthetic-id','delete')`);
assert.match(html, /已盘点基准保留/);
assert.match(html, /name="legacyCountVerified"/);
assert.match(html, /未记录对数/);
const edit = h.form({
kind: 'increase',
date: D,
pocket: PAIR,
grams: '2',
stockCount: '',
note: '更正备注',
reason: '',
});
h.context.__edit = edit;
h.run(
`inventoryChangeEntry={detail:{values:{kind:'increase',date:'${D}',pocket:'${PAIR}',to:'',grams:'2',stockCount:null}}};`,
);
assert.equal(h.json('inventoryChangeInput(__edit)').stockCount, null);
});
test('锁价交付分别收集出库对数和成品来源,重量入库选项不能冒充成品入库', () => {
const h = harness(),
line = h.form({ pocket: PAIR, stockCount: '2', pieces: '8' }, { dataset: { legacy: 'true' } }),
root = h.form(
{
original_stock: 'receive',
extra_stock: 'receive',
count_source: 'stocked',
extra_rate: '900',
extra_payer: 'owner',
extra_verified: true,
},
{ dataset: { lineId: 'lock-line' } },
),
form = h.form(
{
date: D,
delivery_note: '',
discount: '0',
settlement_amount: '0',
settlement_verified: true,
delivery_verified: true,
},
{ dataset: { revision: '4' } },
);
root.querySelector = selector =>
selector === '.line-item' ? line : root.fields[selector.match(/\[name="([^"]+)"\]/)?.[1]] || null;
form.querySelectorAll = selector => (selector === '[data-price-lock-delivery-item]' ? [root] : []);
h.nodes.set('#price-lock-delivery-form', form);
h.context.__line = ordinaryLine({ stockCount: '2', pieces: '8' });
h.run(
`currentPriceLock={id:'lock-id',lines:[{id:'lock-line'}]};collectLine=()=>__line;readFeeRows=()=>[];readPaymentAccount=()=> '麦麦微信';readCreditCardPayer=()=> 'owner';`,
);
let value = h.json('collectPriceLockDelivery()');
assert.equal(value.lines[0].stockCount, '2');
assert.equal(value.lines[0].pieces, '8');
assert.equal(value.lines[0].inventory.countSource, 'stocked');
assert.equal(value.lines[0].inventory.original, 'receive');
root.fields.count_source.value = 'receive';
value = h.json('collectPriceLockDelivery()');
assert.equal(value.lines[0].inventory.countSource, 'receive');
const html = h.run('priceLockDeliveryInventoryHTML({},{})');
assert.match(html, /name="count_source"/);
assert.match(html, /已在货盘/);
assert.match(html, /本次新入库/);
});