'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'),
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 = createBrowserContext({
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()'), /