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

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

344 lines
13 KiB
JavaScript
Raw Normal View History

'use strict';
const test = require('node:test'),
assert = require('node:assert/strict'),
fs = require('node:fs'),
path = require('node:path'),
vm = require('node:vm');
const Calc = require('../public/calculations'),
Cards = require('../public/credit-card-fees');
const settings = {
version: 1,
revision: 3,
storeName: '测试珠宝',
receiptSubtitle: '销售单',
contact: '测试电话',
members: [
{ member: 'owner', label: '店东', loginName: 'owner-test' },
{ member: 'assistant', label: '阿一', loginName: 'one-test' },
{ member: 'assistant2', label: '阿二', loginName: 'two-test' },
],
creditCardRatePermille: 9,
profitSharePercent: 30,
profitShareEffectiveMonth: '2000-01',
feeDefaults: { certificate: '8.50', packaging: '7', shipping: '12', packagingPayer: 'assistant2' },
};
function harness() {
const nodes = new Map(),
handlers = {},
windowHandlers = {};
let confirmResult = false;
const context = vm.createContext({
console,
URLSearchParams,
FeeEstimates: require('../public/fee-estimates'),
LedgerCalc: Calc,
CreditCardFees: Cards,
setInterval() {},
setTimeout() {},
clearTimeout() {},
window: {
scrollTo() {},
confirm() {
return confirmResult;
},
addEventListener(type, handler) {
windowHandlers[type] = handler;
},
},
document: {
title: '',
querySelector: selector => nodes.get(selector) || null,
querySelectorAll: () => [],
addEventListener(type, handler, capture) {
(handlers[type] ??= []).push({ handler, capture });
},
},
localStorage: {
getItem() {
return null;
},
setItem() {},
removeItem() {},
},
sessionStorage: {
getItem() {
return null;
},
setItem() {},
},
__settings: structuredClone(settings),
});
const run = code => vm.runInContext(code, context),
json = code => JSON.parse(JSON.stringify(run(code)));
for (const filename of [
'price-locks-ui.js',
'price-lock-changes-ui.js',
'order-edit-ui.js',
'recovery-changes-ui.js',
'recoveries-ui.js',
'team-funds-ui.js',
'material-pools-ui.js',
'shop-settings-ui.js',
'app.js',
])
run(fs.readFileSync(path.join(__dirname, '../public', filename), 'utf8').replace(/\ninit\(\);\s*$/, ''));
run(
"session={user:{id:'test-owner',member:'owner',role:'owner',label:'店东',name:'原登录名'},brand:{storeName:'测试珠宝'},loginOptions:__settings.members};state={today:'2026-11-14',user:session.user,shopSettings:__settings,members:__settings.members,accounts:['麦麦微信','助理微信','助理2微信','麦麦信用卡'],printing:{store:'测试珠宝',subtitle:'销售单',contact:'测试电话'},mode:'demo'};pending=()=>null;toast=()=>{};",
);
function form() {
const values = json('shopSettingsValues()'),
fields = Object.fromEntries(Object.entries(values).map(([key, value]) => [key, { value: String(value) }]));
const form = {
dataset: { revision: '3', baseline: JSON.stringify(values) },
elements: { namedItem: key => fields[key] },
querySelector: () => ({ disabled: false }),
};
nodes.set('#shop-settings-form', form);
context.__form = form;
return { form, fields };
}
return {
context,
nodes,
handlers,
windowHandlers,
run,
json,
form,
confirm(value) {
confirmResult = value;
},
};
}
test('仅店主显示店铺默认配置卡,成员资料由员工管理维护', () => {
const h = harness(),
html = h.run('shopSettingsHTML()');
for (const name of [
'storeName',
'receiptSubtitle',
'contact',
'creditCardRatePermille',
'profitSharePercent',
'profitShareEffectiveMonth',
'certificate',
'packaging',
'shipping',
'packagingPayer',
])
assert.ok(html.includes('name="' + name + '"'), name);
assert.doesNotMatch(html, /name="(?:owner|assistant2?)Label"|name="(?:owner|assistant2?)LoginName"/);
assert.match(html, /保存店铺配置/);
assert.match(html, /name="profitShareEffectiveMonth" value="2026-12"/);
assert.doesNotMatch(html, /value="2000-01"|profitShareHistory/);
h.run("state.user.role='assistant'");
assert.equal(h.run('shopSettingsHTML()'), '');
});
test('保存店铺配置使用revision且不提交员工资料;未改分成时不重复写入历史计划', () => {
const h = harness(),
{ fields } = h.form();
fields.storeName.value = '新店名';
const data = h.json('shopSettingsInput(__form)');
assert.equal(data.revision, 3);
assert.equal(data.storeName, '新店名');
assert.equal(Object.hasOwn(data, 'members'), false);
assert.deepEqual(data.feeDefaults, settings.feeDefaults);
assert.equal(Object.hasOwn(data, 'profitSharePercent'), false);
assert.equal(Object.hasOwn(data, 'profitShareEffectiveMonth'), false);
fields.profitSharePercent.value = '40';
assert.deepEqual(h.json('shopSettingsInput(__form)').profitSharePercent, 40);
assert.equal(h.json('shopSettingsInput(__form)').profitShareEffectiveMonth, '2026-12');
fields.profitShareEffectiveMonth.value = '2026-10';
assert.throws(() => h.run('shopSettingsInput(__form)'), /本月或以后/);
});
test('店铺配置校验阻止错误费率、过大默认费及非店主保存', () => {
const h = harness(),
{ fields } = h.form();
fields.creditCardRatePermille.value = '0.5';
assert.throws(() => h.run('shopSettingsInput(__form)'), /整数/);
fields.creditCardRatePermille.value = '0';
assert.equal(h.json('shopSettingsInput(__form)').creditCardRatePermille, 0);
fields.shipping.value = '1000000.01';
assert.throws(() => h.run('shopSettingsInput(__form)'), /最多1000000元/);
fields.shipping.value = '0';
h.run("state.user.role='assistant'");
assert.throws(() => h.run('shopSettingsInput(__form)'), /店主账号/);
});
test('成员、收款与品牌显示配置姓名,保留legacy账户键与自由文本原文', () => {
const h = harness();
assert.equal(h.run('accountDisplayName("麦麦微信")'), '店东微信');
assert.equal(h.run('accountDisplayName("助理2支付宝")'), '阿二支付宝');
assert.equal(h.run('accountDisplayName("客户说麦麦微信付款")'), '客户说麦麦微信付款');
assert.deepEqual(h.json('teamMemberOptions()'), [
['owner', '店东'],
['assistant', '阿一'],
['assistant2', '阿二'],
]);
assert.deepEqual(h.json('peopleParts()'), [
['assistant1', '阿一人数'],
['assistant2', '阿二人数'],
]);
assert.equal(h.run('priceLockPayerName("assistant2")'), '阿二');
assert.equal(h.run('materialPayerName("owner")'), '店东');
assert.equal(h.run('currentSalesperson()'), '店东');
const html = h.run('accountFields("麦麦信用卡")');
assert.match(html, /<option value="麦麦" selected>店东/);
assert.match(html, /信用卡统一由店东收款/);
assert.doesNotMatch(html, />麦麦<|娜娜|小昊/);
const title = { textContent: '' },
mark = { textContent: '' };
h.nodes.set('[data-shop-name]', title);
h.nodes.set('[data-shop-mark]', mark);
h.run('applyShopBrand()');
assert.equal(title.textContent, '测试珠宝');
assert.equal(mark.textContent, '测');
assert.equal(h.context.document.title, '测试珠宝 · 新账系统');
});
test('店名、成员及登录文本均转义,配置名不能变成HTML元素', () => {
const h = harness();
h.run(
`state.shopSettings.storeName='<img src=x>';state.shopSettings.members[0].label='<b>店东</b>';state.shopSettings.members[0].loginName='owner"<test>';`,
);
const card = h.run('shopSettingsHTML()'),
account = h.run('accountFields("麦麦信用卡")');
assert.match(card, /&lt;img src=x&gt;/);
assert.match(card, /&lt;b&gt;店东&lt;\/b&gt;/);
assert.doesNotMatch(card, /ownerLoginName/);
assert.doesNotMatch(card + account, /<img|<b>店东|<test>/);
h.run(`state.shopSettings.members[1].label='<i>成员</i>'`);
const people = h.run('peopleCountHTML(null)');
assert.match(people, /&lt;i&gt;成员&lt;\/i&gt;/);
assert.doesNotMatch(people, /<i>成员/);
const login = { innerHTML: '' };
h.nodes.set('#login', login);
h.nodes.set('#shell', { hidden: false });
h.run('login()');
assert.match(login.innerHTML, /&lt;img src=x&gt;/);
assert.doesNotMatch(login.innerHTML, /<img|<b>店东/);
});
test('历史转账方向、负数返款说明与垫付标题转义配置成员名', () => {
const h = harness();
h.run(`state.shopSettings.members[0].label='<b>店东</b>';state.shopSettings.members[1].label='<i>成员</i>';`);
h.context.__order = {
payments: [],
expenses: [],
settlements: [{ date: '2026-11-14', amount: -100, bucket: 'profit', actor: '原经办人', note: '原备注' }],
settlementDue: -100,
costDue: 0,
profitDue: -100,
};
const table = h.run('transactionTable(__order)');
assert.match(table, /&lt;b&gt;店东&lt;\/b&gt;返&lt;i&gt;成员&lt;\/i&gt;/);
assert.doesNotMatch(table, /<b>店东|<i>成员/);
const detail = { innerHTML: '', scrollIntoView() {} };
h.nodes.set('#detail-form', detail);
h.run("teamMode=()=>false;currentOrder=__order;showAction('settlement')");
assert.match(detail.innerHTML, /负数为&lt;b&gt;店东&lt;\/b&gt;需转回/);
assert.doesNotMatch(detail.innerHTML, /<b>店东|<i>成员/);
h.context.__business = {
member: 'assistant',
name: '所属成员',
ownerAdvances: { from: '2026-11-01', date: '2026-11-14', days: [] },
};
const advances = h.run('reportOwnerAdvancesHTML(__business)');
assert.match(advances, /暂无已登记的&lt;b&gt;店东&lt;\/b&gt;垫付明细/);
assert.doesNotMatch(advances, /<b>店东/);
});
test('新单费率跟随配置,旧订单、锁价与置换按各自快照预览,零费率有效', () => {
const h = harness();
assert.equal(h.run('creditCardPreviewRate({id:"order-credit-card-fee"})'), 9);
h.run("tab='order-edit';orderEditEntry={order:{credit_card_rate_permille:0}}");
assert.equal(h.run('creditCardPreviewRate({id:"order-credit-card-fee"})'), 0);
h.run("tab='create';currentOrder={credit_card_rate_permille:5}");
assert.equal(h.run('creditCardPreviewRate({id:"action-credit-card-fee"})'), 5);
assert.equal(h.run('creditCardPreviewRate({id:"order-credit-card-fee"})'), 9);
h.run('priceLockEditEntry={lock:{credit_card_rate_permille:4}}');
assert.equal(h.run('creditCardPreviewRate({id:"lock-create-card-fee"})'), 4);
h.run('currentPriceLock={credit_card_rate_permille:3}');
assert.equal(h.run('creditCardPreviewRate({id:"lock-delivery-card-fee"})'), 3);
h.run('recoveryEditEntry={data:{record:{credit_card_rate_permille:2}}}');
assert.equal(h.run('recoveryCardRate()'), 2);
});
test('未保存配置拦截导航和关闭,取消离开保留填写,确认后才放行', () => {
const h = harness(),
{ fields } = h.form();
assert.equal(h.run('shopSettingsDirty()'), false);
fields.storeName.value = '未保存店名';
assert.equal(h.run('shopSettingsDirty()'), true);
let prevented = 0,
stopped = 0;
const button = { dataset: { tab: 'orders' } },
event = {
target: { closest: () => button },
preventDefault() {
prevented++;
},
stopImmediatePropagation() {
stopped++;
},
};
h.handlers.click.find(row => row.capture).handler(event);
assert.equal(prevented, 1);
assert.equal(stopped, 1);
assert.equal(fields.storeName.value, '未保存店名');
h.confirm(true);
h.handlers.click.find(row => row.capture).handler(event);
assert.equal(prevented, 1);
const unload = {
preventDefault() {
prevented++;
},
};
h.windowHandlers.beforeunload(unload);
assert.equal(unload.returnValue, '');
assert.equal(prevented, 2);
});
test('月利润预览验证本期比例及舍入,展示生效比例而不是固定30%', () => {
const h = harness();
h.context.__report = {
month: '2026-11',
from: '2026-11-01',
date: '2026-11-14',
basis: 'orderDate',
rows: ['assistant', 'assistant2'].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: 40,
estimatedShare: 1000,
})),
};
h.run("teamFundsMonth='2026-11'");
assert.ok(h.run('validateTeamProfits(__report)'));
const html = h.run('teamProfitsBodyHTML(__report)');
assert.match(html, /40%/);
assert.match(html, /该月份生效比例/);
assert.doesNotMatch(html, /× 30%/);
h.context.__report.rows[0].estimatedShare = 750;
assert.throws(() => h.run('validateTeamProfits(__report)'), /未完整返回/);
});
test('保存店铺品牌和费用不把已停用员工重新加入新业务选项', async () => {
const h = harness();
h.form();
h.run('state.members=state.members.map(row=>({...row,enabled:row.member!=="assistant2"}));');
h.nodes.set('#shop-settings-error', { replaceChildren() {} });
h.nodes.set('#identity', { textContent: '' });
h.run(
'syncPrintSettingsPreview=()=>{};loadTeamMembers=async()=>{};mutate=async()=>({shopSettings:{...state.shopSettings,revision:4,members:state.shopSettings.members.map(row=>({...row}))}});',
);
await h.run('saveShopSettings(__form)');
assert.equal(h.run('state.members.find(row=>row.member==="assistant2").enabled'), false);
assert.equal(
h.json('teamMemberOptions()').some(([member]) => member === 'assistant2'),
false,
);
});