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

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

516 lines
20 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'),
path = require('node:path'),
vm = require('node:vm'),
{ randomUUID } = require('node:crypto');
const Calc = require('../public/calculations'),
Cards = require('../public/credit-card-fees'),
Fees = require('../public/fee-estimates'),
Templates = require('../public/order-templates');
const STAFF = 'staff_11111111-2222-4333-8444-555555555555',
OTHER = 'staff_aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
function directory() {
return {
revision: 4,
employees: [
['owner', '店主', 'owner'],
['assistant', '阿一', 'one'],
['assistant2', '阿二', 'two'],
[STAFF, '新员工', 'new-staff'],
].map(([member, label, loginName]) => ({
member,
label,
loginName,
userId: randomUUID(),
role: member === 'owner' ? 'owner' : 'assistant',
enabled: true,
passwordSet: true,
hasBusinessData: member === 'assistant',
canDelete: member !== 'owner' && member !== 'assistant',
canDeactivate: member !== 'owner',
businessUsage: member === 'assistant' ? [{ source: 'orders', label: '订单', count: 2 }] : [],
})),
};
}
function harness() {
const nodes = new Map(),
handlers = {},
windowHandlers = {},
writes = [],
posts = [];
let confirmResult = true;
const context = createBrowserContext({
console,
URLSearchParams,
AbortController,
crypto: { randomUUID },
LedgerCalc: Calc,
CreditCardFees: Cards,
FeeEstimates: Fees,
OrderTemplates: Templates,
setInterval() {},
setTimeout() {},
clearTimeout() {},
window: {
scrollTo() {},
confirm() {
return confirmResult;
},
addEventListener(type, handler) {
(windowHandlers[type] ??= []).push(handler);
},
},
document: {
querySelector: selector => nodes.get(selector) || null,
querySelectorAll: () => [],
addEventListener(type, handler, capture) {
(handlers[type] ??= []).push({ handler, capture });
},
body: { append() {} },
createElement() {
throw new Error('测试需先提供目标元素');
},
},
localStorage: {
getItem() {
return null;
},
setItem(key, value) {
writes.push({ key, value });
},
removeItem() {},
},
sessionStorage: {
getItem() {
return null;
},
setItem() {},
},
__directory: directory(),
__posts: posts,
});
const run = code => vm.runInContext(code, context),
json = code => JSON.parse(JSON.stringify(run(code)));
for (const file of [
'price-locks-ui.js',
'price-lock-changes-ui.js',
'order-edit-ui.js',
'order-ownership-ui.js',
'order-changes-ui.js',
'order-after-sales-ui.js',
'recoveries-ui.js',
'recovery-changes-ui.js',
'team-funds-ui.js',
'material-pools-ui.js',
'shop-settings-ui.js',
'employees-ui.js',
'app.js',
])
run(fs.readFileSync(path.join(__dirname, '../public', file), 'utf8').replace(/\ninit\(\);\s*$/, ''));
run(
"session={user:{id:'owner-test',member:'owner',role:'owner',label:'店主'}};state={today:'2026-11-14',user:session.user,members:__directory.employees,accounts:['麦麦微信','助理微信','助理2微信','麦麦信用卡','" +
STAFF +
"微信','" +
STAFF +
"支付宝','" +
STAFF +
"现金'],shopSettings:{revision:4,storeName:'测试店',members:__directory.employees,feeDefaults:{},creditCardRatePermille:6},orders:[]};employeeDirectory=__directory;employeeDirectoryUser=state.user.id;pending=()=>null;toast=()=>{};shopSettingsDirty=()=>false;printSettingsDirty=()=>false;",
);
const dialog = {
open: false,
innerHTML: '',
addEventListener() {},
setAttribute() {},
querySelector() {
return { focus() {} };
},
querySelectorAll() {
return [];
},
showModal() {
this.open = true;
},
close() {
this.open = false;
},
};
nodes.set('#employee-dialog', dialog);
function form(
kind = 'add',
member = '',
values = { label: '新增员工', loginName: '13800000001', password: 'synthetic-password-123' },
) {
const controls = Object.fromEntries(Object.entries(values).map(([key, value]) => [key, { value }]));
const form = {
id: kind === 'add' || kind === 'update' ? 'employee-form' : 'employee-status-form',
dataset: {},
querySelector: selector => controls[selector.match(/name="([^"]+)"/)?.[1]] || null,
querySelectorAll: () => [],
};
controls.verified = { checked: true };
nodes.set('#' + form.id, form);
nodes.set('#employee-form-error', {
innerHTML: '',
replaceChildren() {
this.innerHTML = '';
},
});
context.__form = form;
context.__kind = kind;
context.__member = member;
context.__initial =
kind === 'update' ? { label: values.label, loginName: values.loginName } : { label: '', loginName: '' };
run(
'employeeEditor={kind:__kind,member:__member,revision:employeeDirectory.revision,user:state.user.id,...__initial}',
);
return { form, controls };
}
return {
context,
nodes,
handlers,
windowHandlers,
run,
json,
writes,
posts,
dialog,
form,
confirm(value) {
confirmResult = value;
},
};
}
test('设置页只有店主可见员工管理;列表明确业务禁删和店主保护,搜索为空有提示', () => {
const h = harness();
assert.match(h.run('employeeManagementHTML()'), /员工管理|新增员工/);
const html = h.run('employeeListHTML(employeeDirectory)');
assert.match(html, /已有业务记录,不能删除/);
assert.match(html, /订单:2 条/);
assert.match(html, /data-action="employee-delete"[^>]*data-member="assistant"[^>]*disabled/);
assert.doesNotMatch(html, /data-action="employee-(?:delete|deactivate)"[^>]*data-member="owner"/);
assert.match(h.run('employeeListHTML({employees:[]})'), /没有符合条件/);
h.run("state.user.role='assistant'");
assert.equal(h.run('employeeManagementHTML()'), '');
assert.throws(() => h.run('showEmployeeEditor()'), /仅店主/);
});
test('员工姓名、登录名、关联来源和搜索文本全部转义', () => {
const h = harness();
h.run(
`employeeDirectory.employees[3].label='<img src=x onerror=alert(1)>';employeeDirectory.employees[3].loginName='"<svg>';employeeDirectory.employees[1].businessUsage[0].label='<script>';employeeSearch='"<search>';`,
);
const html = h.run('employeeListHTML(employeeDirectory)+employeeManagementHTML()');
assert.match(html, /&lt;img/);
assert.match(html, /&quot;&lt;svg&gt;/);
assert.match(html, /&lt;script&gt;/);
assert.doesNotMatch(html, /<img|<svg|<script|<search/);
h.run(`showEmployeeEditor('${STAFF}')`);
assert.match(h.dialog.innerHTML, /&lt;img/);
assert.doesNotMatch(h.dialog.innerHTML, /<img|<svg/);
});
test('员工资料输入校验、空密码不改密码;禁删及店主操作不能用手工事件绕过', () => {
const h = harness(),
{ controls } = h.form('update', STAFF, { label: '新员工', loginName: 'new-staff', password: '' });
assert.deepEqual(h.json('employeeInput(__form)'), {
revision: 4,
label: '新员工',
operatorName: '',
loginName: 'new-staff',
});
controls.password.value = 'short';
assert.throws(() => h.run('employeeInput(__form)'), /12~500/);
controls.password.value = '';
controls.loginName.value = 'bad login';
assert.throws(() => h.run('employeeInput(__form)'), /不含空白/);
assert.throws(() => h.run("showEmployeeStatus('owner','delete')"), /店主账号/);
assert.throws(() => h.run("showEmployeeStatus('assistant','delete')"), /已有业务记录/);
const form = h.form('deactivate', STAFF);
form.controls.verified.checked = false;
assert.throws(() => h.run('employeeInput(__form)'), /勾选确认/);
});
test('搜索带入姓名和状态,旧请求迟到或切换账号时不覆盖员工列表', async () => {
const h = harness(),
list = {
innerHTML: '',
setAttribute() {},
querySelectorAll() {
return [];
},
};
h.nodes.set('#employee-list', list);
h.run(
"employeeSearch='阿 一';employeeStatus='inactive';api=async function(url){__posts.push({url});return {...__directory,employees:[]};}",
);
await h.run('loadEmployees()');
assert.match(h.posts[0].url, /search=%E9%98%BF\+%E4%B8%80&status=inactive/);
assert.match(list.innerHTML, /没有符合条件/);
h.run('api=function(){return new Promise(resolve=>{globalThis.__resolve=resolve;});}');
const delayed = h.run('loadEmployees()');
h.run("state.user={id:'changed',role:'assistant',member:'assistant'}");
h.context.__resolve(h.json('__directory'));
await delayed;
assert.equal(h.run('employeeDirectoryUser'), 'owner-test');
assert.doesNotMatch(list.innerHTML, /新员工/);
});
test('员工写入不写localStorage,结果不明保留原操作号与原payload,重试后清除敏感内存', async () => {
const h = harness();
h.form();
h.run(
"api=async function(url,data,key){__posts.push({url,data,key});throw Object.assign(new Error('network'),{name:'TypeError'});}",
);
await assert.rejects(h.run("employeeWrite('/api/employees',employeeInput(__form))"), /结果待确认/);
assert.equal(h.writes.length, 0);
assert.ok(h.run('employeePending'));
const first = h.json('employeePending');
assert.equal(first.data.password, 'synthetic-password-123');
assert.equal(h.run('closeEmployeeEditor()'), false);
h.run('api=async function(url,data,key){__posts.push({url,data,key});return __directory;}');
await h.run('employeeWrite(employeePending.url,employeePending.data,employeePending)');
assert.equal(h.posts.length, 2);
assert.equal(h.posts[0].key, h.posts[1].key);
assert.deepEqual(h.posts[0].data, h.posts[1].data);
assert.equal(h.run('employeePending'), null);
assert.equal(h.writes.length, 0);
h.run('invalidateEmployees()');
assert.equal(h.run('employeeEditor'), null);
assert.equal(h.dialog.innerHTML, '');
});
test('确认失败保留表单但不保留待恢复密码;错误文本脱敏,成功与关闭清空表单', async () => {
const h = harness();
h.form();
h.run(
"api=async function(){throw Object.assign(new Error('synthetic-password-123 重复'),{status:400,confirmed:true});}",
);
let error;
try {
await h.run("employeeWrite('/api/employees',employeeInput(__form))");
} catch (value) {
error = value;
}
h.context.__error = error;
h.run('employeeError(__error)');
assert.equal(h.run('employeePending'), null);
const errorHTML = h.nodes.get('#employee-form-error').innerHTML;
assert.doesNotMatch(errorHTML, /synthetic-password-123/);
assert.match(errorHTML, /••••/);
assert.equal(h.run('employeeFormValues().password'), 'synthetic-password-123');
h.confirm(false);
assert.equal(h.run('closeEmployeeEditor()'), false);
h.confirm(true);
assert.equal(h.run('closeEmployeeEditor()'), true);
assert.equal(h.dialog.innerHTML, '');
h.form();
h.run('refresh=async()=>{};loadEmployees=async()=>{};');
await h.run('finishEmployeeSave(__directory)');
assert.equal(h.run('employeeEditor'), null);
assert.equal(h.dialog.innerHTML, '');
});
test('账号变化清除员工密码与资料;版本冲突保留原输入并使旧表单停止提交', async () => {
const h = harness();
h.form();
h.run('api=async function(){throw accountChangedError();}');
await assert.rejects(h.run("employeeWrite('/api/employees',employeeInput(__form))"), /账号已切换/);
assert.equal(h.run('employeePending'), null);
assert.equal(h.run('employeeDirectory'), null);
assert.equal(h.dialog.innerHTML, '');
const changed = harness();
const { form, controls } = changed.form();
changed.run("employeeError(Object.assign(new Error('配置已有变动'),{status:409}))");
assert.equal(form.dataset.stale, 'true');
assert.equal(controls.password.value, 'synthetic-password-123');
assert.throws(() => changed.run('employeeInput(__form)'), /重新打开/);
});
test('第四位员工进入开单、付款、账户、成本、模板和人数,停用后新选项移除而历史原值保留', () => {
const h = harness();
assert.ok(h.json('teamMemberOptions()').some(([key]) => key === STAFF));
assert.match(h.run(`orderMemberField('${STAFF}')`), new RegExp('value="' + STAFF + '" selected'));
assert.match(h.run(`purchasePayerField('付款人','payer','${STAFF}')`), new RegExp('value="' + STAFF + '" selected'));
assert.equal(h.run(`accountDisplayName('${STAFF}支付宝')`), '新员工支付宝');
assert.match(h.run(`accountFields('${STAFF}支付宝')`), new RegExp('value="' + STAFF + '" selected>新员工'));
assert.equal(h.run(`orderAfterSaleAccountPayer('${STAFF}微信')`), STAFF);
assert.equal(h.run(`materialPayerName('${STAFF}')`), '新员工');
assert.equal(h.run(`priceLockPayerName('${STAFF}')`), '新员工');
assert.equal(h.run(`orderChangePayer('${STAFF}')`), '新员工');
assert.ok(h.json('peopleParts()').some(([key]) => key === STAFF));
h.run(`state.members[3].enabled=false`);
assert.equal(
h.json('teamMemberOptions()').some(([key]) => key === STAFF),
false,
);
assert.equal(
h.json('peopleParts()').some(([key]) => key === STAFF),
false,
);
assert.ok(h.json('peopleParts(true)').some(([key]) => key === STAFF));
assert.doesNotMatch(h.run('orderMemberField()'), new RegExp('value="' + STAFF + '"'));
assert.match(h.run(`choice('原付款人','payer',teamMemberOptions(),'${STAFF}')`), /新员工(已停用 · 原记录)/);
assert.match(h.run(`purchasePayerField('原料费付款人','payer','${STAFF}')`), /新员工(已停用 · 原记录)/);
assert.match(h.run('memberFilterHTML("report-member-filter")'), /新员工(已停用)/);
assert.equal(h.json('activePaymentAccounts()').includes(STAFF + '微信'), false);
assert.equal(h.json(`activePaymentAccounts('${STAFF}微信')`).includes(STAFF + '微信'), true);
const draft = {
payment_account: STAFF + '支付宝',
credit_card_fee_payer: STAFF,
lines: [{ name: '测试款', unit: '件', quantity: '1', pocket: '', payer: STAFF, sale: '100', cost: '50' }],
fee_items: [],
};
assert.equal(Templates.fromDraft(draft).payment_account, STAFF + '支付宝');
assert.equal(Templates.fromDraft(draft).lines[0].payer, STAFF);
assert.equal(
Fees.sync([], [{ charges: [{ id: randomUUID(), name: '包装' }] }], { shopDefaults: { packagingPayer: STAFF } })[0]
.payer,
STAFF,
);
h.context.__recovery = {
mode: 'direct',
date: '2026-11-14',
customer: '合成',
salesperson: '合成',
member: STAFF,
payer: STAFF,
old_lines: [{ name: '旧料', incoming_weight: '1', melted_weight: '1', purity: '100' }],
payment_account: STAFF + '支付宝',
buy_rate: '800',
};
h.run("state.pockets=['现货']");
assert.equal(h.json('recoveryEditDraft(__recovery)').payment_recipient, STAFF);
assert.equal(h.json('recoveryEditDraft(__recovery)').payment_method, '支付宝');
const cost = Calc.orderCosts({
status: 'delivered',
lines: [{ name: '测试款', payer: STAFF, cost: 5000 }],
expenses: [],
pendingFees: [],
});
assert.equal(cost.byPayer[STAFF].goods, 5000);
assert.throws(() => Calc.costPayers({ material: 'staff_bad', labor: STAFF }), /付款人无效/);
});
test('十名以上员工的每日利润按成员目录数值顺序校验,不按字符串序号错误拒绝', () => {
const h = harness();
h.context.__extra = Array.from({ length: 8 }, (_, index) => ({
member: 'staff_00000000-0000-4000-8000-' + String(index).padStart(12, '0'),
label: '合成员工' + index,
enabled: true,
}));
h.run('state.members.push(...__extra)');
const members = h.json('teamMemberKeys()'),
rows = members.map(member => ({
member,
name: member,
date: '2026-11-14',
sales: 10000,
knownTotalCost: 7500,
knownProfit: 2500,
totalCost: 7500,
profit: 2500,
recordCount: 1,
orderCount: 1,
afterSaleCount: 0,
draftCount: 0,
unknownCostCount: 0,
unknownProfitCount: 0,
incomplete: false,
}));
h.context.__daily = {
from: '2026-11-14',
date: '2026-11-14',
ownershipReceipts: Object.fromEntries(members.map(member => [member, {}])),
summary: {
sale: rows.length * 10000,
totalCost: rows.length * 7500,
profit: rows.length * 2500,
unknownProfitCount: 0,
unknownCostCount: 0,
draftCount: 0,
},
orderRows: rows.map(() => ({})),
dailyProfits: {
basis: 'orderDate',
from: '2026-11-14',
date: '2026-11-14',
rows,
summary: {
...rows[0],
sales: rows.length * 10000,
knownTotalCost: rows.length * 7500,
knownProfit: rows.length * 2500,
totalCost: rows.length * 7500,
profit: rows.length * 2500,
recordCount: rows.length,
orderCount: rows.length,
},
},
};
assert.doesNotThrow(() => h.run('validateDailyProfits(__daily)'));
[h.context.__daily.dailyProfits.rows[9], h.context.__daily.dailyProfits.rows[10]] = [
h.context.__daily.dailyProfits.rows[10],
h.context.__daily.dailyProfits.rows[9],
];
assert.throws(() => h.run('validateDailyProfits(__daily)'), /每日利润表/);
});
test('第四位员工的月度利润可验证,停用员工历史统计仍保留,未知成员与缺行被拒绝', () => {
const h = harness();
h.context.__report = {
month: '2026-11',
from: '2026-11-01',
date: '2026-11-14',
basis: 'orderDate',
rows: ['assistant', 'assistant2', STAFF].map(member => ({
member,
name: member,
recordCount: 1,
orderCount: 1,
afterSaleCount: 0,
draftCount: 0,
unknownCostCount: 0,
unknownProfitCount: 0,
sales: 10000,
knownTotalCost: 7500,
knownProfit: 2500,
incomplete: false,
profit: 2500,
shareRate: 30,
estimatedShare: 750,
})),
};
h.run("teamFundsMonth='2026-11'");
assert.ok(h.run('validateTeamProfits(__report)'));
h.run('state.members[3].enabled=false');
assert.ok(h.run('validateTeamProfits(__report)'));
h.context.__report.rows[2].member = OTHER;
assert.throws(() => h.run('validateTeamProfits(__report)'), /未完整返回/);
});
test('新增员工必须输入手机号,名称自动用于新单且忽略旧开单人映射', () => {
const h = harness(),
{ controls } = h.form();
assert.deepEqual(h.json('employeeInput(__form)'), {
revision: 4,
label: '新增员工',
operatorName: '',
phone: '13800000001',
password: 'synthetic-password-123',
});
controls.loginName.value = 'new-login';
assert.throws(() => h.run('employeeInput(__form)'), /手机号/);
h.run("state.shopSettings.salespersonDefaults={owner:'旧映射'};state.shopSettings.members[0].label='账号新名称'");
assert.equal(h.run('defaultSalesperson()'), '账号新名称');
assert.equal(h.run('currentSalesperson()'), '账号新名称');
assert.doesNotMatch(h.run('shopSettingsHTML()'), /账号对应开单人|salesperson_owner/);
h.run('showEmployeeEditor()');
assert.match(h.dialog.innerHTML, /手机号(登录账号)/);
assert.match(h.dialog.innerHTML, /账号名称/);
});
test('经办人单独带入新单,内部账号显示仍用实际员工名', () => {
const h = harness();
h.run("state.shopSettings.members[0].label='娜娜';state.shopSettings.members[0].operatorName='客服一'");
assert.equal(h.run('defaultSalesperson()'), '客服一');
assert.equal(h.run('teamMemberName("owner")'), '娜娜');
h.run("delete state.shopSettings.members[0].operatorName;state.user.operatorName='客服二'");
assert.equal(h.run('currentSalesperson()'), '客服二');
h.run('showEmployeeEditor()');
assert.match(h.dialog.innerHTML, /经办人名称(开单人)/);
});