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

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

1170 lines
42 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 { randomUUID } = require('node:crypto'),
Calc = require('../public/calculations');
const D = '2026-10-22',
TODAY = '2026-10-23',
RID = '11111111-1111-4111-8111-111111111111';
const clone = value => JSON.parse(JSON.stringify(value));
const { currentAccount } = require('../domains/funds/ownership-business');
const sixItems = () =>
[80, 90, 173, 63, 80, 10].map((value, index) => ({ name: '报销项目' + (index + 1), amount: value * 100 }));
function claim(extra = {}) {
return {
id: RID,
date: D,
items: sixItems(),
total: 49600,
note: '合成报销',
status: 'pending',
revision: 1,
requester_id: 'assistant',
requester_name: '助理',
reviewer_id: null,
reviewer_name: null,
reviewed: null,
review_note: '',
created: D + 'T01:00:00Z',
updated: D + 'T01:00:00Z',
canEdit: true,
canApprove: true,
...extra,
};
}
function data(extra = {}) {
const date = extra.date || D,
from = extra.from || date,
sources = {
revision: 'source-v1',
total: 20000,
items: [
{
id: 'payment-one',
sourceType: 'materialPurchase',
sourceId: 'one',
date,
amount: 20000,
payer: 'owner',
name: '未售现货实际采购',
note: '合成付款参考',
},
],
},
ownerReceipts = { receipt: 110000, refund: 10000, net: 100000 };
const result = {
date,
from,
readOnly: from !== date,
hasRecords: false,
pendingCount: 0,
ownerReceipts,
reimbursements: [],
approvedReimbursements: 0,
actualOutlay: null,
confirmation: null,
sources,
ready: false,
transferAmount: null,
direction: null,
missingDates: [date],
staleDates: [],
days: [],
transfersNotDeducted: true,
...extra,
};
if (result.ready) {
result.actualOutlay = result.actualOutlay ?? 80000;
result.confirmation = result.confirmation || {
date,
amount: result.actualOutlay,
revision: 1,
sourceRevision: result.sources.revision,
note: '已核对全部支出',
actor: '麦麦',
created: D,
updated: D,
stale: false,
};
result.transferAmount = result.ownerReceipts.net - result.actualOutlay + result.approvedReimbursements;
result.direction = result.transferAmount > 0 ? 'toAssistant' : result.transferAmount < 0 ? 'toOwner' : 'none';
result.missingDates = [];
}
if (!extra.days)
result.days = [
{
date,
ownerReceipts: result.ownerReceipts,
approvedReimbursements: result.approvedReimbursements,
actualOutlay: result.actualOutlay,
confirmation: result.confirmation,
sources: result.sources,
ready: result.ready,
transferAmount: result.transferAmount,
direction: result.direction,
hasActivity: true,
},
];
return result;
}
function node(extra = {}) {
return {
innerHTML: '',
textContent: '',
disabled: false,
hidden: false,
dataset: {},
checked: false,
value: '',
classList: { toggle() {} },
setAttribute() {},
scrollIntoView() {},
querySelector() {
return null;
},
querySelectorAll() {
return [];
},
insertAdjacentHTML(position, html) {
this.innerHTML += html;
},
...extra,
};
}
function reportForFunds(funds) {
const person = (recipient, name) => ({
recipient,
name,
receipt: recipient === 'owner' ? funds.ownerReceipts.receipt : 0,
refund: recipient === 'owner' ? funds.ownerReceipts.refund : 0,
net: recipient === 'owner' ? funds.ownerReceipts.net : 0,
items:
recipient === 'owner'
? ['receipt', 'refund']
.filter(kind => funds.ownerReceipts[kind])
.map(kind => ({
id: kind,
date: funds.date,
order_date: funds.date,
order_id: 'synthetic-order',
kind,
amount: funds.ownerReceipts[kind],
account: '麦麦微信',
}))
: [],
});
const cost = name => ({ name, goods: 0, paidFees: 0, total: 0, missingCount: 0, pendingCount: 0, items: [] });
const recipientReceipts = { owner: person('owner', '麦麦'), assistant: person('assistant', '助理') },
member = 'owner',
items = recipientReceipts.owner.items;
const owned = {
member,
name: member === 'owner' ? '麦麦' : '助理',
...funds.ownerReceipts,
items,
accounts: items.length
? [
{
account: '麦麦微信',
recipient: 'owner',
channel: 'wechat',
...funds.ownerReceipts,
entryCount: items.length,
},
]
: [],
};
const ownershipReceipts = {
owner: owned,
assistant: { member: 'assistant', name: '助理', receipt: 0, refund: 0, net: 0, accounts: [], items: [] },
};
const ownershipBusiness = Object.fromEntries(
Object.entries(ownershipReceipts).map(([member, person]) => [
member,
{
member,
name: person.name,
basis: 'orderDate',
from: funds.from,
date: funds.date,
sales: 0,
netReceipts: person.net,
totalCost: 0,
knownTotalCost: 0,
selfCost: 0,
knownSelfCost: 0,
otherCost: 0,
knownOtherCost: 0,
profit: 0,
knownProfit: 0,
incomplete: false,
missingCostCount: 0,
pendingCostCount: 0,
unknownProfitCount: 0,
draftCount: 0,
recordCount: 0,
orderCount: 0,
afterSaleCount: 0,
hasActivity: person.items.length > 0,
costByPayer: Object.fromEntries(
['owner', 'assistant', 'assistant2'].map(key => [
key,
{ member: key, name: key, totalCost: 0, knownTotalCost: 0, missingCount: 0, pendingCount: 0 },
]),
),
difference: { amount: person.net, reconciled: person.net === 0, reasons: [] },
equation: { basis: 'sales', revenue: 0, totalCost: 0, profit: 0, complete: true },
settlement: {
available: false,
basis: 'cumulative-through-date',
from: funds.from,
date: funds.date,
dueOut: null,
dueIn: null,
partial: false,
pendingCount: 0,
legacyCount: 0,
notice: '旧双人结算请核对原单。',
counterparts: [],
},
},
]),
);
for (const b of Object.values(ownershipBusiness))
b.poolMaterial = {
mg: 0,
amount: 0,
knownAmount: 0,
missingCount: 0,
hasPriceLocks: false,
byPayer: Object.fromEntries(
['owner', 'assistant', 'assistant2'].map(key => [key, { amount: 0, knownAmount: 0 }]),
),
days: [],
otherCosts: { amount: 0, knownAmount: 0 },
};
for (const b of Object.values(ownershipBusiness)) {
b.ownerAdvances = { basis: 'orderDate', from: funds.from, date: funds.date, days: [] };
b.currentAccount = currentAccount([], ownershipReceipts[b.member], b.ownerAdvances, funds.from, funds.date);
}
return {
basis: 'orderDate',
date: funds.date,
from: funds.from,
summary: {
orderCount: 0,
completedCount: 0,
returnedCount: 0,
cancelledCount: 0,
draftCount: 0,
afterSaleCount: 0,
sale: 0,
profit: 0,
totalCost: 0,
missingCosts: 0,
},
orderRows: [],
accounts: [],
receiptsByOrderDate: funds.ownerReceipts,
recipientReceipts,
ownershipReceipts,
ownershipBusiness,
dailyProfits: {
basis: 'orderDate',
date: funds.date,
from: funds.from,
rows: [],
summary: {
recordCount: 0,
orderCount: 0,
afterSaleCount: 0,
draftCount: 0,
sales: 0,
knownTotalCost: 0,
knownProfit: 0,
totalCost: 0,
profit: 0,
unknownCostCount: 0,
unknownProfitCount: 0,
incomplete: false,
},
},
payerCosts: { owner: cost('麦麦'), assistant: cost('助理') },
goods: 0,
expense: 0,
inventory: [],
unsettled: [],
warnings: [],
customerBalance: 0,
settlementDue: 0,
close: null,
dailyFunds: funds,
};
}
function attrs(tag) {
const result = {};
for (const match of tag.matchAll(/([\w-]+)="([^"]*)"/g))
result[match[1]] = match[2]
.replace(/&quot;/g, '"')
.replace(/&amp;/g, '&')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>');
return result;
}
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
function harness(initial = data(), role = 'owner') {
const nodes = new Map(),
saved = new Map(),
calls = [],
toasts = [],
handlers = {},
responses = new Map([[initial.date, clone(initial)]]),
postResults = new Map();
let forms = [];
const user = { id: role, name: role === 'owner' ? '麦麦' : '助理', role };
for (const key of [
'#main',
'#daily-funds-content',
'#report-daily-profits-content',
'#report-content',
'#daily-reimbursements-list',
'#pending',
'#toast',
'#reimbursement-edit-total',
])
nodes.set(key, node());
nodes.set(
'#daily-reimbursements-dialog',
node({
open: false,
showModal() {
this.open = true;
},
close() {
this.open = false;
},
}),
);
function parseForms(html) {
for (const old of forms) nodes.delete('#' + old.id);
forms = [];
for (const match of html.matchAll(/<form\b([^>]*)>([\s\S]*?)<\/form>/g)) {
const metadata = attrs(match[1]),
body = match[2],
fields = {},
controls = [],
rows = [];
const form = node({
id: metadata.id,
dataset: Object.fromEntries(
Object.entries(metadata)
.filter(([key]) => key.startsWith('data-'))
.map(([key, value]) => [key.slice(5).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase()), value]),
),
});
const makeField = (tag, content = '') => {
const a = attrs(tag),
field = node({
name: a.name || '',
value: a.value ?? content,
checked: /\schecked(?:\s|>)/.test(tag),
disabled: /\sdisabled(?:\s|>)/.test(tag),
type: a.type || 'text',
dataset: {},
closest(selector) {
return selector.split(',').some(value => value === '#' + form.id) ? form : null;
},
});
if (a.name) fields[a.name] = field;
controls.push(field);
return field;
};
for (const item of body.matchAll(/<input\b[^>]*>/g)) makeField(item[0]);
for (const item of body.matchAll(/<textarea\b([^>]*)>([\s\S]*?)<\/textarea>/g)) makeField(item[1], item[2]);
for (const item of body.matchAll(/<button\b([^>]*)>/g)) {
const a = attrs(item[1]);
controls.push(
node({
type: a.type || 'button',
dataset: { action: a['data-action'] || '' },
disabled: /\sdisabled(?:\s|$)/.test(item[1]),
}),
);
}
for (const item of body.matchAll(/<div class="reimbursement-item-row"[^>]*>([\s\S]*?)<\/div>/g)) {
const rowFields = {};
for (const input of item[1].matchAll(/<input\b[^>]*>/g)) {
const a = attrs(input[0]);
rowFields[a.name] = makeField(input[0]);
}
rows.push(
node({
querySelector(selector) {
return rowFields[selector.match(/name="([^"]+)"/)?.[1]] || null;
},
}),
);
}
form.querySelector = selector => fields[selector.match(/name="([^"]+)"/)?.[1]] || null;
form.querySelectorAll = selector => (selector === '.reimbursement-item-row' ? rows : controls);
form.fields = fields;
form.rows = rows;
forms.push(form);
nodes.set('#' + form.id, form);
for (const id of ['daily-outlay-error', 'reimbursement-error', 'reimbursement-review-error'])
if (body.includes('id="' + id + '"')) nodes.set('#' + id, node());
}
}
let content = '';
Object.defineProperty(nodes.get('#daily-funds-content'), 'innerHTML', {
get: () => content,
set: value => {
content = value;
parseForms(value);
},
});
const context = vm.createContext({
console,
URLSearchParams,
LedgerCalc: Calc,
crypto: { randomUUID },
setInterval() {},
setTimeout() {},
clearTimeout() {},
document: {
querySelector(selector) {
if (nodes.has(selector)) return nodes.get(selector);
const match = selector.match(/^(#[^ ]+) (.+)$/);
return match ? nodes.get(match[1])?.querySelector?.(match[2]) || null : null;
},
querySelectorAll() {
return forms.flatMap(form => form.querySelectorAll('controls'));
},
addEventListener(type, fn) {
(handlers[type] ??= []).push(fn);
},
},
window: { scrollTo() {} },
localStorage: {
getItem: key => saved.get(key) ?? null,
setItem: (key, value) => saved.set(key, String(value)),
removeItem: key => saved.delete(key),
},
sessionStorage: {
getItem() {
return null;
},
setItem() {},
},
__user: user,
__initial: initial,
__calls: calls,
__toasts: toasts,
__refreshes: 0,
__api: async (url, payload, key) => {
if (url.startsWith('/api/report?')) {
const query = new URLSearchParams(url.split('?')[1]),
date = query.get('date'),
from = query.get('from'),
funds = clone(responses.get(date) || data({ date }));
funds.from = from;
funds.readOnly = from !== date;
return reportForFunds(funds);
}
if (url.startsWith('/api/reimbursements?'))
return {
requests: [],
counts: { pending: 0, approved: 0, rejected: 0 },
total: 0,
limit: 50,
offset: 0,
hasMore: false,
};
if (payload) {
if (postResults.has(key)) return clone(postResults.get(key));
let result;
if (url === '/api/daily-funds/confirm') {
const prior = responses.get(payload.date) || data({ date: payload.date }),
confirmation = {
date: payload.date,
amount: Calc.cents(payload.amount),
revision: (prior.confirmation?.revision || 0) + 1,
sourceRevision: payload.sourceRevision,
note: payload.note,
actor: '麦麦',
created: D,
updated: D,
stale: false,
};
responses.set(payload.date, data({ ...prior, ready: true, actualOutlay: confirmation.amount, confirmation }));
result = { date: payload.date, confirmation };
} else {
const old = responses.get(payload.date || D) || responses.get(D),
previous = old.reimbursements.find(row => url.includes(row.id)),
updated = url.endsWith('/approve')
? claim({
...previous,
status: 'approved',
revision: (previous?.revision || 1) + 1,
reviewer_name: '麦麦',
canEdit: false,
canApprove: false,
})
: url.endsWith('/reject')
? claim({
...previous,
status: 'rejected',
revision: (previous?.revision || 1) + 1,
review_note: payload.note,
canApprove: false,
})
: claim({
date: payload.date,
items: payload.items.map(item => ({ name: item.name, amount: Calc.cents(item.amount) })),
total: payload.items.reduce((sum, item) => sum + Calc.cents(item.amount), 0),
note: payload.note,
status: 'pending',
canApprove: role === 'owner',
revision: previous ? previous.revision + 1 : 1,
});
const reimbursements = old.reimbursements.filter(row => row.id !== updated.id).concat([updated]),
approvedReimbursements = reimbursements
.filter(row => row.status === 'approved')
.reduce((sum, row) => sum + row.total, 0);
responses.set(
updated.date,
data({
...old,
date: updated.date,
reimbursements,
approvedReimbursements,
pendingCount: reimbursements.filter(row => row.status === 'pending').length,
}),
);
result = { id: updated.id, reimbursement: updated };
}
postResults.set(key, result);
return clone(result);
}
throw new Error('Unexpected API ' + url);
},
});
const run = code => vm.runInContext(code, context),
json = code => JSON.parse(JSON.stringify(run(code)));
for (const file of ['price-locks-ui.js', 'material-pools-ui.js', 'daily-funds-ui.js', 'app.js'])
run(fs.readFileSync(path.join(__dirname, '../public', file), 'utf8').replace(/\ninit\(\);\s*$/, ''));
run(
`state={user:__user,today:'${TODAY}'};session={user:__user};tab='report';reportDate='${initial.date}';reportMonth=false;api=async function(url,payload,key){__calls.push({url,data:payload,key});return await __api(url,payload,key);};toast=function(message,error){__toasts.push({message,error});};openOrder=async function(){throw new Error('Daily funds cannot open an order');};`,
);
const load = async () => await run('loadDailyFunds({...reportRange(),month:reportMonth})');
async function action(name, extra = {}) {
context.__button = node({
dataset: { action: name, ...extra },
closest() {
return null;
},
});
return await run(`dailyFundsAction('${name}',__button)`);
}
async function click(name, extra = {}) {
const button = node({
dataset: { action: name, ...extra },
closest() {
return null;
},
});
for (const handler of handlers.click || []) await handler({ target: { closest: () => button } });
}
function fill(name, value, id = 'daily-outlay-form') {
const field = nodes.get('#' + id)?.querySelector('[name="' + name + '"]');
assert.ok(field, 'field ' + name + ' in ' + id);
if (typeof value === 'boolean') field.checked = value;
else field.value = value;
context.__target = field;
run('dailyFundsInput(__target)');
}
function item(index, name, amount) {
const row = nodes.get('#reimbursement-form').rows[index];
assert.ok(row);
row.querySelector('[name="itemName"]').value = name;
row.querySelector('[name="itemAmount"]').value = amount;
context.__target = row.querySelector('[name="itemAmount"]');
run('dailyFundsInput(__target)');
}
async function submit(id) {
context.__form = nodes.get('#' + id);
assert.ok(context.__form, 'form ' + id);
return await run('submitDailyFundsForm(__form)');
}
const html = () => nodes.get('#daily-funds-content').innerHTML,
posts = () => calls.filter(call => call.data);
return {
context,
run,
json,
nodes,
calls,
toasts,
saved,
responses,
postResults,
load,
action,
click,
fill,
item,
submit,
html,
posts,
};
}
test('未确认时只显示真实付款参考,不把参考或订单成本冒充完整支出与应转结果', async () => {
const h = harness();
await h.load();
assert.match(h.html(), /未售现货实际采购/);
assert.match(h.html(), /可能不完整/);
assert.match(h.html(), /暂不显示应转合计/);
assert.doesNotMatch(h.html(), /class="daily-transfer-result"/);
assert.equal(h.nodes.get('#daily-outlay-form').fields.amount.value, '200.00');
assert.equal(h.nodes.get('#daily-outlay-form').fields.verified.checked, false);
assert.equal(h.posts().length, 0);
assert.match(h.html(), /不含客户退款/);
assert.match(h.html(), /之前已经支付的货品,后续卖出不算一笔新支出/);
});
test('0元也必须明确确认,确认使用所见来源和版本,之后才显示正式分项公式', async () => {
const h = harness();
await h.load();
h.fill('amount', '0');
await h.submit('daily-outlay-form');
assert.equal(h.posts().length, 0);
assert.match(h.nodes.get('#daily-outlay-error').innerHTML, /0 元也需要确认/);
h.fill('verified', true);
await h.submit('daily-outlay-form');
assert.deepEqual(clone(h.posts()[0].data), {
date: D,
amount: '0',
revision: 0,
sourceRevision: 'source-v1',
note: '',
verified: true,
});
assert.match(h.html(), /class="daily-transfer-result"/);
assert.match(h.html(), /确认对外支出 ¥0\.00/);
assert.match(h.html(), /不要与下方旧按单/剩料待结重复相加/);
assert.equal(h.nodes.has('#daily-outlay-form'), false, '本人确认成功正常收起,不误当他窗修改');
});
test('助理与麦麦都能代录六项496元,日期默认今天可改,提交不会自动批准', async () => {
for (const role of ['assistant', 'owner']) {
const h = harness(data(), role);
await h.load();
await h.action('reimbursement-new');
assert.equal(h.nodes.get('#reimbursement-form').fields.date.value, TODAY);
h.fill('date', D, 'reimbursement-form');
for (const [index, value] of [80, 90, 173, 63, 80, 10].entries()) {
if (index) await h.action('reimbursement-add-item');
h.item(index, '项目' + index, String(value));
}
assert.match(h.nodes.get('#reimbursement-edit-total').innerHTML, /¥496\.00/);
await h.submit('reimbursement-form');
const post = h.posts()[0];
assert.equal(post.url, '/api/reimbursements');
assert.equal(post.data.date, D);
assert.equal(post.data.items.length, 6);
assert.equal(
post.data.items.reduce((sum, row) => sum + Calc.cents(row.amount), 0),
49600,
);
assert.equal(h.responses.get(D).reimbursements[0].status, 'pending');
assert.equal(h.responses.get(D).approvedReimbursements, 0);
assert.equal(h.posts().length, 1);
}
});
test('助理不能确认或审批;已批准报销只读,不因返回canEdit异常而恢复编辑', async () => {
const row = claim(),
h = harness(data({ reimbursements: [row], pendingCount: 1 }), 'assistant');
await h.load();
assert.doesNotMatch(
h.html(),
/id="daily-outlay-form"|data-action="reimbursement-approve"|data-action="reimbursement-reject"/,
);
await h.action('reimbursement-approve', { id: RID });
assert.equal(h.posts().length, 0);
assert.match(h.toasts.at(-1).message, /只能由店主/);
const owner = harness(
data({
reimbursements: [claim({ status: 'approved', canEdit: true, canApprove: true })],
approvedReimbursements: 49600,
}),
);
await owner.load();
assert.doesNotMatch(owner.html(), /data-action="reimbursement-edit"|data-action="reimbursement-approve"/);
assert.match(owner.html(), /已批准单据只读/);
await owner.action('reimbursement-edit', { id: RID });
assert.equal(owner.posts().length, 0);
});
test('待审和被驳回单可修改重新提交,保留原版本与驳回原因,批准后不可改', async () => {
for (const status of ['pending', 'rejected']) {
const h = harness(
data({
reimbursements: [claim({ status, review_note: status === 'rejected' ? '需核对工费凭据' : '' })],
pendingCount: status === 'pending' ? 1 : 0,
}),
'assistant',
);
await h.load();
if (status === 'rejected') assert.match(h.html(), /驳回原因:需核对工费凭据/);
await h.action('reimbursement-edit', { id: RID });
h.item(0, '核实后的工费', '81');
await h.submit('reimbursement-form');
assert.equal(h.posts()[0].url, '/api/reimbursements/' + RID + '/update');
assert.equal(h.posts()[0].data.revision, 1);
assert.equal(h.responses.get(D).reimbursements[0].status, 'pending');
assert.equal(h.responses.get(D).reimbursements[0].total, 49700);
}
});
test('同意须勾选,驳回须原因,批准加报销回到原日期且不触发订单费用接口', async () => {
const h = harness(data({ ready: true, reimbursements: [claim()], pendingCount: 1 }));
await h.load();
await h.action('reimbursement-approve', { id: RID });
await h.submit('reimbursement-review-form');
assert.equal(h.posts().length, 0);
h.fill('verified', true, 'reimbursement-review-form');
await h.submit('reimbursement-review-form');
assert.equal(h.posts()[0].data.verified, true);
assert.equal(h.posts()[0].data.revision, 1);
assert.equal(h.responses.get(D).approvedReimbursements, 49600);
assert.equal(h.responses.get(D).transferAmount, 69600);
assert.match(h.html(), /¥696\.00/);
const reject = harness(data({ reimbursements: [claim()] }));
await reject.load();
await reject.action('reimbursement-reject', { id: RID });
await reject.submit('reimbursement-review-form');
assert.equal(reject.posts().length, 0);
reject.fill('note', '请补实际付款说明', 'reimbursement-review-form');
await reject.submit('reimbursement-review-form');
assert.deepEqual(clone(reject.posts()[0].data), { revision: 1, note: '请补实际付款说明' });
assert.equal(reject.responses.get(D).approvedReimbursements, 0);
assert.ok(h.posts().every(row => /^\/api\/reimbursements\//.test(row.url)));
});
test('正负应转方向清晰,不扣已转金额,不把应转合计叫尚欠', async () => {
for (const [outlay, expected] of [
[80000, '麦麦转娜娜'],
[120000, '娜娜转麦麦'],
[100000, '无需转款'],
]) {
const h = harness(data({ ready: true, actualOutlay: outlay }));
await h.load();
assert.match(h.html(), new RegExp(expected));
assert.match(h.html(), /未扣已转/);
assert.doesNotMatch(h.html(), /尚欠/);
}
});
test('月汇总及月首单日范围均只读,可查看待确认日期但没有改写按钮', async () => {
for (const date of [D, '2026-10-01']) {
const value = data({ date, from: '2026-10-01', reimbursements: [claim({ date })] }),
h = harness(value);
h.run('reportMonth=true');
await h.load();
assert.match(h.html(), /只读汇总/);
assert.match(h.html(), /待确认日期/);
assert.doesNotMatch(
h.html(),
/id="daily-outlay-form"|data-action="reimbursement-new"|data-action="reimbursement-edit"|data-action="reimbursement-approve"/,
);
await h.action('reimbursement-new');
assert.equal(h.posts().length, 0);
assert.match(h.toasts.at(-1).message, /月汇总只读/);
assert.match(h.html(), /data-action="reimbursement-open-list"/);
}
});
test('付款来源变更使旧确认失效,保留输入但清勾选并隐藏正式合计', async () => {
const h = harness(data({ ready: true }));
await h.load();
await h.action('daily-outlay-edit');
h.fill('amount', '999.99');
h.fill('verified', true);
const next = data({
ready: false,
confirmation: { ...data({ ready: true }).confirmation, stale: true },
sources: { revision: 'source-v2', total: 0, items: [] },
staleDates: [D],
missingDates: [],
});
h.responses.set(D, next);
await h.load();
assert.equal(h.nodes.get('#daily-outlay-form').fields.amount.value, '999.99');
assert.equal(h.nodes.get('#daily-outlay-form').fields.verified.checked, false);
assert.match(h.html(), /付款有变动/);
assert.doesNotMatch(h.html(), /class="daily-transfer-result"/);
assert.equal(h.posts().length, 0);
});
test('另一窗口只改确认版本也必须重新核对,普通重新读取及修改金额都不复用旧勾选', async () => {
const h = harness(data({ ready: true }));
await h.load();
await h.action('daily-outlay-edit');
h.fill('amount', '900.00');
h.fill('verified', true);
h.responses.set(
D,
data({
ready: true,
actualOutlay: 85000,
confirmation: { ...data({ ready: true }).confirmation, amount: 85000, revision: 2 },
}),
);
await h.load();
assert.equal(h.nodes.get('#daily-outlay-form').fields.amount.value, '900.00');
assert.equal(h.nodes.get('#daily-outlay-form').fields.verified.checked, false);
assert.match(h.html(), /支出确认已被更新/);
await h.submit('daily-outlay-form');
assert.equal(h.posts().length, 0);
h.fill('verified', true);
await h.load();
assert.equal(h.nodes.get('#daily-outlay-form').fields.verified.checked, false);
h.fill('verified', true);
h.fill('amount', '901.00');
assert.equal(h.nodes.get('#daily-outlay-form').fields.verified.checked, false);
h.fill('verified', true);
await h.submit('daily-outlay-form');
assert.equal(h.posts()[0].data.revision, 2);
});
test('日期与账号时序守卫拒收旧响应,失败不清除当前日期资料', async () => {
const h = harness(),
slow = deferred(),
original = h.context.__api;
h.context.__api = url => (url.includes('date=' + D) ? slow.promise : original(url));
const first = h.load();
h.run(`reportDate='${TODAY}'`);
await h.load();
slow.resolve(data());
await first;
assert.equal(h.json('dailyFundsEntry.data.date'), TODAY);
const h2 = harness(),
waiting = deferred();
h2.context.__api = () => waiting.promise;
const request = h2.load();
h2.run("state={...state,user:{id:'different',name:'另一个账号',role:'owner'}}");
waiting.resolve(data());
await request;
assert.equal(h2.run('dailyFundsEntry.data'), null);
assert.equal(h2.posts().length, 0);
});
test('读取失败保留尚未保存的项目、金额与日期,并锁定提交直到重新读取', async () => {
const h = harness();
await h.load();
await h.action('reimbursement-new');
h.item(0, '尚未提交的进货工费', '80.00');
h.fill('date', D, 'reimbursement-form');
h.fill('amount', '321.00');
const original = h.context.__api;
h.context.__api = async () => {
throw new Error('合成断线');
};
await h.load();
assert.equal(
h.nodes.get('#reimbursement-form').rows[0].querySelector('[name="itemName"]').value,
'尚未提交的进货工费',
);
assert.equal(h.nodes.get('#daily-outlay-form').fields.amount.value, '321.00');
assert.equal(h.nodes.get('#reimbursement-form').fields.date.value, D);
assert.equal(h.nodes.get('#reimbursement-form').fields.date.disabled, true);
assert.match(h.nodes.get('#report-content').innerHTML, /合成断线/);
assert.doesNotMatch(h.html(), /合成断线/);
assert.equal(h.run('currentReport'), null);
assert.equal(h.run('dailyFundsEntry.data'), null);
assert.throws(() => h.run('requireDailyFunds()'), /请先重新读取/);
h.context.__api = original;
await h.load();
assert.equal(h.nodes.get('#reimbursement-form').rows[0].querySelector('[name="itemAmount"]').value, '80.00');
assert.equal(h.posts().length, 0);
});
test('同一日报校验失败只显示一个错误,资金与报销资料同时失效且重读成功后恢复', async () => {
const h = harness(data({ ready: true }));
await h.load();
const original = h.context.__api;
h.context.__api = async (...args) => {
const response = await original(...args);
response.ownershipBusiness.owner.knownTotalCost++;
return response;
};
await h.load();
const message = '所属订单成本、利润或待转资料未完整返回',
html = h.nodes.get('#report-content').innerHTML + h.html();
assert.equal((html.match(new RegExp(message, 'g')) || []).length, 1);
assert.equal(h.run('currentReport'), null);
assert.equal(h.run('dailyFundsEntry.data'), null);
assert.equal(h.run('dailyFundsLoading'), false);
assert.throws(() => h.run('requireCurrentReport()'), /正在读取或已失效/);
assert.throws(() => h.run('requireDailyFunds()'), /请先重新读取/);
assert.doesNotMatch(h.html(), /class="daily-transfer-result"|data-action="reimbursement-new"/);
h.context.__api = original;
await h.load();
assert.ok(h.run('currentReport'));
assert.ok(h.run('dailyFundsEntry.data'));
assert.match(h.html(), /class="daily-transfer-result"/);
assert.equal(h.posts().length, 0);
});
test('全日期待复核独立分页,打开跨日申请回原报销日,不在月汇总直接写入', async () => {
const older = '2026-10-20',
row = claim({ date: older }),
h = harness(data({ pendingCount: 1 }));
h.responses.set(older, data({ date: older, reimbursements: [row], pendingCount: 1 }));
const original = h.context.__api;
h.context.__api = async (url, payload, key) =>
url.startsWith('/api/reimbursements?')
? {
requests: [row],
counts: { pending: 1, approved: 0, rejected: 0 },
total: 1,
offset: 0,
limit: 50,
hasMore: false,
}
: original(url, payload, key);
h.run('reportMonth=true');
await h.load();
await h.action('reimbursement-open-list');
assert.match(h.nodes.get('#daily-reimbursements-list').innerHTML, /2026-10-20/);
assert.match(h.nodes.get('#daily-reimbursements-list').innerHTML, /查看并复核/);
await h.action('reimbursement-open-date', { date: older, id: RID });
assert.equal(h.run('reportDate'), older);
assert.equal(h.run('reportMonth'), false);
assert.match(h.html(), /id="reimbursement-review-form"/);
assert.equal(h.posts().length, 0);
});
test('断线恢复复用原操作号,报销和审批不重复、日期不跳回且不走旧订单完成路径', async () => {
for (const kind of ['create', 'approve']) {
const h = harness(
data({
ready: true,
reimbursements: kind === 'approve' ? [claim()] : [],
pendingCount: kind === 'approve' ? 1 : 0,
}),
);
await h.load();
const original = h.context.__api;
let drop = true;
h.context.__api = async (url, payload, key) => {
const result = await original(url, payload, key);
if (payload && drop) {
drop = false;
throw new Error('合成响应丢失');
}
return result;
};
if (kind === 'create') {
await h.action('reimbursement-new');
h.fill('date', D, 'reimbursement-form');
h.item(0, '实际进货工费', '496');
await h.submit('reimbursement-form');
} else {
await h.action('reimbursement-approve', { id: RID });
h.fill('verified', true, 'reimbursement-review-form');
await h.submit('reimbursement-review-form');
}
assert.equal(h.posts().length, 1);
const first = h.posts()[0];
assert.ok(h.saved.has('mm-pending-owner'));
h.run(`reportDate='${TODAY}'`);
await h.load();
await h.click('retry');
assert.equal(h.posts().length, 2);
assert.equal(h.posts()[1].key, first.key);
assert.deepEqual(clone(h.posts()[1].data), clone(first.data));
assert.equal(h.responses.get(D).reimbursements.length, 1);
assert.equal(h.run('reportDate'), TODAY);
assert.equal(h.saved.has('mm-pending-owner'), false);
assert.equal(h.responses.get(D).approvedReimbursements, kind === 'approve' ? 49600 : 0);
}
const h = harness();
for (const [url, kind] of [
['/api/daily-funds/confirm', 'confirm'],
['/api/reimbursements', 'create'],
['/api/reimbursements/x/update', 'update'],
['/api/reimbursements/x/approve', 'approve'],
['/api/reimbursements/x/reject', 'reject'],
]) {
h.context.__url = url;
assert.equal(h.run('dailyFundsOperation(__url).kind'), kind);
}
});
test('报表与新卡只用同一读取快照,资金重读也刷新收款与下载,不并发读取第二来源', async () => {
const h = harness(data({ ready: true }));
await h.load();
assert.equal(h.run('dailyFundsEntry.data===currentReport.dailyFunds'), true);
assert.equal(h.calls.filter(row => row.url.startsWith('/api/report?')).length, 1);
assert.equal(
h.calls.some(row => row.url.startsWith('/api/daily-funds?')),
false,
);
const next = data({
ready: true,
ownerReceipts: { receipt: 120000, refund: 5000, net: 115000 },
actualOutlay: 90000,
confirmation: { ...data({ ready: true }).confirmation, revision: 2, amount: 90000 },
});
h.responses.set(D, next);
await h.action('daily-funds-retry');
assert.equal(h.run('currentReport.recipientReceipts.owner.net'), 115000);
assert.equal(h.run('dailyFundsEntry.data===currentReport.dailyFunds'), true);
assert.match(h.html(), /麦麦净收款 ¥1,150\.00 − 确认对外支出 ¥900\.00/);
assert.match(
h.run('reportDownloadText(currentReport)'),
/麦麦净收款 ¥1,150\.00 − 确认完整对外支出 ¥900\.00 + 已批准报销 ¥0\.00 = 应转合计 ¥250\.00/,
);
assert.equal(h.calls.filter(row => row.url.startsWith('/api/report?')).length, 2);
});
test('保存中锁定项目与备注;请求发出后内容有变化时成功响应不得清掉新草稿', async () => {
const h = harness();
await h.load();
await h.action('reimbursement-new');
h.fill('date', D, 'reimbursement-form');
h.item(0, '提交时项目', '10');
h.fill('note', '提交时备注', 'reimbursement-form');
const gate = deferred(),
original = h.context.__api;
h.context.__api = async (url, payload, key) => {
const result = await original(url, payload, key);
if (payload) await gate.promise;
return result;
};
const saving = h.submit('reimbursement-form');
assert.equal(h.nodes.get('#reimbursement-form').fields.note.disabled, true);
assert.equal(h.nodes.get('#reimbursement-form').rows[0].querySelector('[name="itemAmount"]').disabled, true);
h.fill('note', '请求之后另存的新备注', 'reimbursement-form');
gate.resolve();
await saving;
assert.equal(h.nodes.get('#reimbursement-form').fields.note.value, '请求之后另存的新备注');
assert.equal(h.responses.get(D).reimbursements[0].note, '提交时备注');
assert.equal(h.posts().length, 1);
});
test('含空格名称与备注的已提交草稿恢复后清理原日期编辑器,未匹配的后续更新草稿保留', async () => {
const h = harness();
await h.load();
await h.action('reimbursement-new');
h.fill('date', D, 'reimbursement-form');
h.item(0, ' 进货工费 ', '80.00');
h.fill('note', ' 原备注 ', 'reimbursement-form');
const original = h.context.__api;
let lose = true;
h.context.__api = async (url, payload, key) => {
const result = await original(url, payload, key);
if (payload && lose) {
lose = false;
throw new Error('响应丢失');
}
return result;
};
await h.submit('reimbursement-form');
h.run(`reportDate='${TODAY}'`);
await h.load();
await h.click('retry');
assert.equal(h.run('reportDate'), TODAY);
h.run(`reportDate='${D}'`);
await h.load();
assert.equal(h.nodes.has('#reimbursement-form'), false);
assert.equal(h.responses.get(D).reimbursements.length, 1);
assert.equal(h.responses.get(D).reimbursements[0].items[0].name, '进货工费');
const later = harness(data({ reimbursements: [claim()] }));
await later.load();
await later.action('reimbursement-edit', { id: RID });
later.fill('note', '后续新草稿', 'reimbursement-form');
later.context.__input = { date: D, items: [{ name: '原提交', amount: '1' }], note: '原备注', revision: 1 };
later.context.__result = { id: RID, reimbursement: claim({ revision: 2 }) };
await later.run(`finishDailyFundsSave('/api/reimbursements/${RID}/update',__input,__result,null)`);
assert.equal(later.nodes.get('#reimbursement-form').fields.note.value, '后续新草稿');
});
test('下载文本包含正式公式、原日期批准项目与待确认状态,所有输入安全转义', async () => {
const row = claim({ status: 'approved', reviewer_name: '麦麦' }),
value = data({ ready: true, reimbursements: [row], approvedReimbursements: 49600 }),
h = harness(value);
await h.load();
h.context.__report = { date: D, from: D, dailyFunds: value };
const text = h.run('dailyFundsDownloadText(__report).join(String.fromCharCode(10))');
assert.match(text, /净收款 ¥1,000\.00 − 确认完整对外支出 ¥800\.00 + 已批准报销 ¥496\.00 = 应转合计 ¥696\.00/);
assert.match(text, /报销项目3:¥173\.00/);
assert.match(text, /不要与旧按单/剩料待结重复相加/);
h.context.__report = { date: D, from: D, dailyFunds: data() };
assert.match(h.run('dailyFundsDownloadText(__report).join(String.fromCharCode(10))'), /待确认日期/);
const unsafe = data({
reimbursements: [
claim({
requester_name: '<img src=x>',
items: [{ name: '<script>付款</script>', amount: 100 }],
total: 100,
note: '<b>备注</b>',
review_note: '<u>原因</u>',
}),
],
});
h.responses.set(D, unsafe);
await h.load();
assert.doesNotMatch(h.html(), /<img|<script|<b>备注|<u>原因/);
assert.match(h.html(), /&lt;script&gt;付款&lt;\/script&gt;/);
});
test('不完整返回不显示0元结论,也不允许提交', async () => {
const value = data();
value.sources.total = 999;
const h = harness(value);
await h.load();
assert.match(h.html(), /未完整返回/);
assert.doesNotMatch(h.html(), /class="daily-transfer-result"/);
assert.equal(h.posts().length, 0);
assert.equal(h.run('currentReport.basis'), 'orderDate', '新区域资料缺失不能遮掉原报表');
assert.match(h.nodes.get('#report-content').innerHTML, /按收款账户核对/);
assert.match(h.run('dailyFundsDownloadText(currentReport).join(String.fromCharCode(10))'), /不输出应转金额/);
});
test('团队每日报销保留入口和逐项明细,移除重复累计成员面板及对应导出', () => {
const h = harness(),
funds = data({
reimbursements: [claim()],
pendingCount: 1,
team: { pairs: [{ members: ['owner', 'assistant'], due: 999900, fromMember: 'assistant', toMember: 'owner' }] },
});
h.context.__entry = { key: 'synthetic-team', range: { date: D, from: D, month: false }, data: funds, error: '' };
h.context.__report = { date: D, from: D, dailyFunds: funds };
const html = h.run(`renderTeamDailyFundsHTML(__entry,false,'${D}')`),
text = h.run('dailyFundsDownloadText(__report).join(String.fromCharCode(10))');
assert.match(html, /每日报销单/);
assert.match(html, /2026-10-22/);
assert.match(html, /data-action="reimbursement-new"/);
assert.match(html, /data-action="reimbursement-open-list"/);
assert.match(html, /报销项目1/);
assert.match(html, /¥496\.00/);
assert.doesNotMatch(html, /成员往来<\/h2>|剩余待转|累计往来|9,999\.00/);
assert.match(text, /每日报销单/);
assert.match(text, /待店主复核 \/ 合计 ¥496\.00/);
assert.match(text, /报销项目1:¥80\.00/);
assert.doesNotMatch(text, /团队成员往来|累计|9,999\.00/);
});