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

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

308 lines
13 KiB
JavaScript
Raw Normal View History

'use strict';
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
vm = require('node:vm'),
crypto = require('node:crypto');
const D = '2026-11-08';
const catalog = () => [
{ key: '现货', name: '店内现货', active: true, self: true, builtin: true, revision: 2 },
{ key: 'pocket-custom', name: '新货盘', active: true, self: true, builtin: false, revision: 1 },
{ key: '金料', name: '原金料盘', active: false, self: true, builtin: true, revision: 3 },
{ key: '君宝汇', name: '供应商A', active: false, self: false, builtin: true, revision: 2 },
];
function node(extra = {}) {
return {
innerHTML: '',
textContent: '',
value: '',
disabled: false,
hidden: false,
dataset: {},
isConnected: true,
classList: {
contains() {
return false;
},
toggle() {},
},
setAttribute(name, value) {
this[name] = value;
},
querySelector() {
return null;
},
querySelectorAll() {
return [];
},
closest() {
return null;
},
...extra,
};
}
function harness(role = 'owner') {
const nodes = new Map(),
handlers = {},
calls = [],
toasts = [],
storage = new Map();
for (const id of ['main', 'pocket-manager-content', 'pocket-manager-error', 'pocket-manager'])
nodes.set('#' + id, node());
const context = vm.createContext({
console,
crypto,
URLSearchParams,
setInterval() {},
setTimeout() {},
clearTimeout() {},
window: { scrollTo() {} },
localStorage: {
getItem: key => storage.get(key) || null,
setItem: (key, value) => storage.set(key, value),
removeItem: key => storage.delete(key),
},
document: {
querySelector: query => nodes.get(query) || null,
querySelectorAll() {
return [];
},
addEventListener(type, handler) {
(handlers[type] ??= []).push(handler);
},
},
__role: role,
__catalog: catalog(),
__calls: calls,
__toasts: toasts,
});
const run = code => vm.runInContext(code, context),
json = code => JSON.parse(JSON.stringify(run(code)));
for (const file of ['pockets-ui.js', 'app.js'])
run(fs.readFileSync(require.resolve('../public/' + file), 'utf8').replace(/\ninit\(\);\s*$/, ''));
context.__api = async () => ({ catalog: catalog(), pockets: ['现货', 'pocket-custom'], canManage: true });
run(
`state={user:{id:'synthetic-${role}',role:__role,member:__role},today:'${D}',pockets:['现货','pocket-custom'],pocketCatalog:__catalog,orders:[]};session={user:state.user};tab='stock';toast=(message,error=false)=>__toasts.push({message,error});api=async(url,data,key)=>{__calls.push({url,data,key});return await __api(url,data,key);};refresh=async()=>{__calls.push({refresh:true});};renderStock=async()=>{__calls.push({renderStock:true});};`,
);
return {
context,
run,
json,
nodes,
calls,
toasts,
storage,
form(name, extra = {}) {
const fields = { name: node({ value: name }) },
form = node({
id: 'pocket-create-form',
fields,
querySelector: query => (query === '[name="name"]' ? fields.name : null),
...extra,
});
context.__form = form;
return form;
},
async click(action, extra = {}) {
const button = node({ dataset: { action, ...extra } });
for (const handler of handlers.click || [])
await handler({ target: { closest: selector => (selector === 'button' ? button : null) } });
},
};
}
test('库存页内有管理入口,助理只使用启用货盘,不能伪造管理按钮或提交', async () => {
const owner = harness();
assert.match(owner.run('stockHeading({canReview:true})'), /管理货盘/);
assert.match(owner.run('pocketManagerPanel()'), /新增货盘按自有库存管理/);
for (const role of ['assistant', 'assistant2']) {
const h = harness(role);
assert.equal(h.run('pocketManagerPanel()'), '');
assert.doesNotMatch(h.run('stockHeading({canReview:false})'), /管理货盘/);
assert.match(h.run('stockEntryForm()'), /value="pocket-custom"/);
assert.doesNotMatch(h.run('stockEntryForm()'), /value="金料"|value="君宝汇"/);
h.form('不可创建');
await h.run('submitPocketManagement(__form)');
await h.click('pocket-manager-status', { pocketKey: '现货', active: 'false' });
assert.equal(h.calls.length, 0);
assert.match(h.toasts.at(-1).message, /店主账号/);
}
});
test('新增和改名只发送名称与原版本,表单、流水和订单显示名映射而值仍为稳定key', async () => {
const h = harness();
h.run('pocketManagerRows=state.pocketCatalog;');
h.form(' 新供应商 ');
await h.run('submitPocketManagement(__form)');
let call = h.calls.find(row => row.data);
assert.equal(call.url, '/api/pockets');
assert.deepEqual(JSON.parse(JSON.stringify(call.data)), { name: '新供应商' });
assert.ok(call.key);
h.calls.length = 0;
h.form('改名后', { id: 'rename', dataset: { pocketKey: '现货' } });
await h.run('submitPocketManagement(__form)');
call = h.calls.find(row => row.data);
assert.equal(call.url, '/api/pockets/' + encodeURIComponent('现货') + '/update');
assert.deepEqual(JSON.parse(JSON.stringify(call.data)), { name: '改名后', revision: 2 });
assert.match(h.run('stockEntryForm()'), /<option value="现货" selected>店内现货/);
assert.match(
h.run(`stockMovementRows([{id:'x',date:'${D}',pocket:'现货',mg:1000,kind:'increase',actor:'合成'}])`),
/>店内现货</,
);
assert.match(h.run(`orderLinePocketHTML({status:'delivered'},{pocket:'现货'})`), /出货货盘:店内现货/);
});
test('停用和启用沿用原key与版本,已有余额在库存页明确显示且历史筛选继续可选', async () => {
const h = harness();
h.run('pocketManagerRows=state.pocketCatalog;');
await h.click('pocket-manager-status', { pocketKey: '现货', active: 'false' });
let call = h.calls.find(row => row.data);
assert.equal(call.data.active, false);
assert.equal(call.data.revision, 2);
assert.match(call.url, /%E7%8E%B0%E8%B4%A7\/update$/);
h.calls.length = 0;
await h.click('pocket-manager-status', { pocketKey: '金料', active: 'true' });
call = h.calls.find(row => row.data);
assert.deepEqual(JSON.parse(JSON.stringify(call.data)), { revision: 3, active: true });
const html = h.run(`stockLegacyInventory({legacyInventory:[{pocket:'金料',mg:12345,reserved:1000}]})`);
assert.match(html, /原金料盘/);
assert.match(html, /已停用/);
assert.match(html, /12\.345g/);
assert.match(html, /旧单占用 1\.000g/);
assert.match(JSON.stringify(h.json('orderBookPocketOptions()')), /原金料盘(已停用 · 历史)/);
});
test('新增校验空名、控制字符和40字上限,服务端重名拒绝保留输入且没有新待恢复操作', async () => {
for (const name of [' ', 'x\u0000y', '长'.repeat(41)]) {
const h = harness();
h.form(name);
await h.run('submitPocketManagement(__form)');
assert.equal(h.calls.length, 0);
assert.match(h.nodes.get('#pocket-manager-error').innerHTML, /1~40字/);
}
const h = harness(),
form = h.form('店内现货');
h.context.__api = async () => {
throw Object.assign(new Error('货盘名称已存在'), { status: 400, confirmed: true });
};
await h.run('submitPocketManagement(__form)');
assert.equal(form.fields.name.value, '店内现货');
assert.equal(h.storage.size, 0);
assert.match(h.nodes.get('#pocket-manager-error').innerHTML, /名称已存在/);
assert.equal(h.run('pocketManagerStale'), false);
});
test('管理版本冲突保留填写并禁旧数据,重新读取成功后才可再修改', async () => {
const h = harness();
h.run('pocketManagerRows=state.pocketCatalog;');
const form = h.form('用户正在改的名字', { id: 'rename', dataset: { pocketKey: '现货' } });
h.context.__api = async () => {
throw Object.assign(new Error('货盘已有变化'), { status: 409, confirmed: true });
};
await h.run('submitPocketManagement(__form)');
assert.equal(form.fields.name.value, '用户正在改的名字');
assert.equal(h.run('pocketManagerStale'), true);
assert.match(h.nodes.get('#pocket-manager-error').innerHTML, /重新读取货盘/);
const calls = h.calls.length;
await h.run('submitPocketManagement(__form)');
assert.equal(h.calls.length, calls);
h.context.__api = async () => ({ catalog: catalog(), pockets: ['现货', 'pocket-custom'], canManage: true });
h.run('pocketManagerOpen=true;');
await h.run('loadPocketManager()');
assert.equal(h.run('pocketManagerStale'), false);
assert.match(h.nodes.get('#pocket-manager-content').innerHTML, />店内现货<\/strong>/);
});
test('管理写入断线保留原请求,恢复沿同操作号和内容进入货盘成功处理,不走订单记账', async () => {
const h = harness();
h.form('待确认的新盘');
h.context.__api = async () => {
throw new TypeError('响应中断');
};
await h.run('submitPocketManagement(__form)');
const job = JSON.parse(h.storage.get('mm-pending-synthetic-owner'));
assert.equal(job.url, '/api/pockets');
assert.match(h.nodes.get('#pocket-manager-error').innerHTML, /恢复原操作/);
h.context.__api = async () => ({ catalog: catalog(), pockets: ['现货', 'pocket-custom'] });
await h.click('retry');
const writes = h.calls.filter(row => row.data);
assert.equal(writes.length, 2);
assert.equal(writes[0].key, writes[1].key);
assert.deepEqual(writes[0].data, writes[1].data);
assert.equal(h.storage.size, 0);
assert.match(h.toasts.at(-1).message, /货盘已新增/);
assert.ok(h.calls.some(row => row.renderStock));
assert.ok(h.run(`retryableMutation('/api/pockets')&&retryableMutation('/api/pockets/pocket-custom/update')`));
});
test('管理读取晚于关面板、换页或换号时不能覆盖当前界面', async () => {
for (const action of [
'pocketManagerOpen=false;++pocketManagerRequest;',
"tab='orders';",
"state.user={id:'new-user',role:'owner'};session.user=state.user;",
]) {
const h = harness();
h.run('pocketManagerOpen=true;');
let resolve;
h.context.__api = () => new Promise(done => (resolve = done));
const loading = h.run('loadPocketManager()');
h.run(action);
const before = h.nodes.get('#pocket-manager-content').innerHTML;
resolve({ catalog: catalog(), pockets: ['现货', 'pocket-custom'], canManage: true });
await loading;
assert.equal(h.nodes.get('#pocket-manager-content').innerHTML, before);
assert.equal(h.run('pocketManagerRows'), null);
}
});
test('历史编辑保留停用原值但不能重新选择,新模板或复制的新单明确提示并阻止停用值', () => {
const h = harness(),
historical = h.run(`pocketChoice('货盘','pocket','金料',{historical:true})`),
fresh = h.run(`pocketChoice('货盘','pocket','金料')`);
assert.match(historical, /<option value="金料" selected disabled>原金料盘(已停用 · 原货盘)/);
assert.doesNotMatch(historical, /pocket-selection-note/);
assert.match(fresh, /已停用,请重新选择/);
assert.match(fresh, /pocket-selection-note/);
const row = { dataset: { historicalPocket: 'false' } },
select = { value: '金料', closest: () => row };
h.context.__pocketForm = { querySelectorAll: () => [select] };
assert.throws(() => h.run('validateNewPocketSelections(__pocketForm)'), /原金料盘.*已停用/);
row.dataset.historicalPocket = 'true';
assert.doesNotThrow(() => h.run('validateNewPocketSelections(__pocketForm)'));
row.dataset.historicalPocket = 'false';
select.value = 'pocket-custom';
assert.doesNotThrow(() => h.run('validateNewPocketSelections(__pocketForm)'));
});
test('全停用时库存与管理仍可渲染,历史存量可核对且新选择列表为空', () => {
const h = harness();
h.run('state.pockets=[];');
assert.deepEqual(h.json('activePocketKeys()'), []);
assert.doesNotThrow(() => h.run(`stockCards({current:[],yesterday:null,yesterdayDate:'2026-11-07'})`));
assert.doesNotThrow(() => h.run('stockEntryForm()'));
assert.match(h.run('stockHeading({canReview:true})'), /管理货盘/);
assert.equal(h.json('pocketOptions()').length, 0);
});
test('货盘名称作为文本转义,原始key只作value,不让改名内容注入HTML', () => {
const h = harness();
h.run(`state.pocketCatalog[0].name='<img src=x onerror=alert(1)>';pocketManagerRows=state.pocketCatalog;`);
for (const html of [
h.run('pocketManagerContent()'),
h.run('stockEntryForm()'),
h.run(`orderLinePocketHTML({status:'delivered'},{pocket:'现货'})`),
]) {
assert.match(html, /&lt;img/);
assert.doesNotMatch(html, /<img/);
}
});
test('模板纯函数允许明确传入新货盘范围,未知key不靠任意字符串放行,套用旧停用预设仍保留重选依据', () => {
const Templates = require('../public/order-templates'),
preset = { lines: [{ name: '足金999', unit: 'g', pocket: 'pocket-custom' }] };
assert.throws(() => Templates.fromDraft(preset), /出库货盘无效/);
const saved = Templates.fromDraft(preset, { pocketKeys: ['pocket-custom'] });
assert.equal(saved.lines[0].pocket, 'pocket-custom');
assert.throws(() => Templates.fromDraft(preset, { pocketKeys: [] }), /出库货盘无效/);
assert.equal(Templates.apply(saved, { today: D, pocketKeys: ['pocket-custom'] }).lines[0].pocket, 'pocket-custom');
});