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

197 lines
34 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');
const D='2026-10-22',NEXT='2026-10-23',user={id:'receipts-ui-user',name:'合成麦麦',role:'owner'};
const payment=(id,kind,amount,account,extra={})=>({id,kind,amount,account,date:NEXT,order_date:D,order_id:'order-'+id,price_lock_id:null,number:'XS-'+id,paper_number:'纸单-'+id,customer:'客户-'+id,reference:'',created:NEXT+'T01:00:00Z',...extra});
function ownershipPerson(member,name,items){
const amount=(rows,kind)=>rows.filter(item=>item.kind===kind).reduce((total,item)=>total+item.amount,0),receipt=amount(items,'receipt'),refund=amount(items,'refund');
const accounts=[...new Set(items.map(item=>item.account))].map(account=>{const rows=items.filter(item=>item.account===account),receipt=amount(rows,'receipt'),refund=amount(rows,'refund');return {account,recipient:account.startsWith('麦麦')?'owner':account.startsWith('助理2')?'assistant2':'assistant',channel:account.endsWith('微信')?'wechat':account.endsWith('支付宝')?'alipay':account.endsWith('信用卡')?'credit_card':'cash',receipt,refund,net:receipt-refund,entryCount:rows.length};});
return {member,name,receipt,refund,net:receipt-refund,accounts,items};
}
function businessPerson(person,date=D,from=date,extra={}){
const costByPayer=Object.fromEntries(['owner','assistant','assistant2'].map(member=>[member,{member,name:{owner:'麦麦',assistant:'助理1',assistant2:'助理2'}[member],totalCost:0,knownTotalCost:0,missingCount:0,pendingCount:0,...extra.costByPayer?.[member]}])),payers=Object.values(costByPayer),others=payers.filter(row=>row.member!==person.member),knownTotalCost=payers.reduce((total,row)=>total+row.knownTotalCost,0),totalCost=payers.some(row=>row.totalCost===null)?null:knownTotalCost,sales=extra.sales??person.net,profit=Object.hasOwn(extra,'profit')?extra.profit:totalCost===null?null:sales-totalCost,incomplete=extra.incomplete??(totalCost===null||profit===null);
const result={member:person.member,name:person.name,basis:'orderDate',from,date,sales,netReceipts:person.net,totalCost,knownTotalCost,selfCost:costByPayer[person.member].totalCost,knownSelfCost:costByPayer[person.member].knownTotalCost,otherCost:others.some(row=>row.totalCost===null)?null:others.reduce((total,row)=>total+row.totalCost,0),knownOtherCost:others.reduce((total,row)=>total+row.knownTotalCost,0),profit,knownProfit:profit??0,incomplete,missingCostCount:payers.reduce((total,row)=>total+row.missingCount,0),pendingCostCount:payers.reduce((total,row)=>total+row.pendingCount,0),unknownProfitCount:profit===null?1:0,draftCount:0,recordCount:person.items.length,orderCount:person.items.length,afterSaleCount:0,hasActivity:person.items.length>0,costByPayer,difference:{amount:person.net-sales,reconciled:person.net===sales,reasons:person.net===sales?[]:[{code:'payment_sales_difference',text:'净收款与销售不同,按原账核对利润。'}]},equation:{basis:person.net===sales&&!incomplete?'netReceipts':'sales',revenue:person.net===sales&&!incomplete?person.net:sales,totalCost,profit,complete:!incomplete},settlement:{available:false,basis:'cumulative-through-date',from,date,dueOut:null,dueIn:null,partial:false,pendingCount:0,legacyCount:0,notice:'历史结算请核对原单。',counterparts:[]},...extra,costByPayer};return result;
}
function syncBusiness(response){response.ownershipBusiness=Object.fromEntries(Object.entries(response.ownershipReceipts).map(([member,person])=>[member,businessPerson(person,response.date,response.from)]));return response;}
function report(date=D,from=date,empty=false){
const items=empty?[]:[
payment('a','receipt',12345,'助理微信'),payment('b','receipt',2000,'助理支付宝'),payment('c','receipt',-1000,'助理微信',{reference:'更正收款'}),
payment('r','refund',501,'助理微信'),payment('rr','refund',-1,'助理微信',{reference:'更正退款'}),
payment('l','receipt',50001,'麦麦现金',{date,order_date:null,order_id:null,price_lock_id:'lock-l',paper_number:null}),
payment('d','receipt',10002,'麦麦支付宝',{date,price_lock_id:'lock-d'}),payment('dr','refund',1000,'麦麦支付宝',{date,price_lock_id:'lock-d'})
];
const amount=(rows,kind)=>rows.filter(item=>item.kind===kind).reduce((sum,item)=>sum+item.amount,0);
const recipientReceipts=Object.fromEntries([['assistant','助理'],['owner','麦麦']].map(([recipient,name])=>{
const rows=items.filter(item=>item.account.startsWith(name)),receipt=amount(rows,'receipt'),refund=amount(rows,'refund');
return [recipient,{recipient,name,receipt,refund,net:receipt-refund,items:rows}];
}));
const ownershipReceipts=Object.fromEntries(Object.entries(recipientReceipts).map(([member,person])=>[member,ownershipPerson(member,person.name,person.items)]));
const receipt=amount(items,'receipt'),refund=amount(items,'refund');
const accounts=[...new Set(items.map(item=>item.account))].map(account=>{
const rows=items.filter(item=>item.account===account),receipt=amount(rows,'receipt'),refund=amount(rows,'refund');return {account,receipt,refund,net:receipt-refund};
});
const cost=name=>({name,goods:0,paidFees:0,total:0,missingCount:0,pendingCount:0,items:[]});
return syncBusiness({basis:'orderDate',date,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:{receipt,refund,net:receipt-refund},recipientReceipts,ownershipReceipts,payerCosts:{assistant:cost('助理'),owner:cost('麦麦')},
goods:0,expense:0,customerBalance:0,settlementDue:0,inventory:[],unsettled:[],warnings:[],close:null,priceLockActivity:null,materialPoolActivity:null});
}
function harness(initial=report()){
const nodes=new Map(),handlers={},calls=[],saved=new Map(),content={innerHTML:'',attributes:{},setAttribute(name,value){this.attributes[name]=value;},insertAdjacentHTML(position,html){assert.equal(position,'beforeend');this.innerHTML+=html;}};
for(const [selector,node] of [['#main',{innerHTML:''}],['#report-content',content],['#report-date',{value:D}],['#report-month',{checked:false}]])nodes.set(selector,node);
const context=vm.createContext({console,URLSearchParams,crypto:{randomUUID},setInterval(){},setTimeout(){},clearTimeout(){},
document:{addEventListener(type,fn){(handlers[type]??=[]).push(fn);},querySelector:selector=>nodes.get(selector)||null,querySelectorAll:()=>[]},window:{scrollTo(){}},
localStorage:{getItem:key=>saved.get(key)??null,setItem:(key,value)=>saved.set(key,String(value)),removeItem:key=>saved.delete(key)},
__response:initial,__user:user,__calls:calls});
const run=code=>vm.runInContext(code,context);
for(const file of ['price-locks-ui.js','material-pools-ui.js','team-funds-ui.js','app.js'])run(fs.readFileSync(path.join(__dirname,'../public',file),'utf8').replace(/\ninit\(\);\s*$/,''));
run(`session={user:__user};state={user:__user,today:'${NEXT}'};tab='report';reportDate='${D}';api=async function(url){__calls.push({url});return __response;};openOrder=async function(id){__calls.push({openOrder:id});};openPriceLock=async function(id){__calls.push({openPriceLock:id});};`);
const range=(date,month=false)=>{context.__date=date;context.__month=month;run('reportDate=__date;reportMonth=__month;');nodes.get('#report-date').value=date;nodes.get('#report-month').checked=month;};
return {context,run,nodes,handlers,calls,content,range};
}
function table(html,label){
const found=html.match(new RegExp('<table[^>]*aria-label="'+label+'"[^>]*>([\\s\\S]*?)</table>'));
assert.ok(found,'应显示 '+label);return found[1];
}
test('所属订单净收入在账户表上方,收款与退款各自逐笔合计,冲回保留符号与明确标签',async()=>{
const h=harness();await h.run('renderReport()');const html=h.content.innerHTML;
assert.equal(h.run('currentReport.recipientReceipts.assistant.receipt'),13345);assert.equal(h.content.attributes['aria-busy'],'false');
for(const name of ['助理所属订单净收入','麦麦所属订单净收入'])assert.ok(html.indexOf(name)<html.indexOf('按收款账户核对'));
assert.match(html,/<header class="report-recipient-summary"><h2 id="report-ownership-assistant-title">助理所属订单净收入<\/h2><div class="report-recipient-total">¥128\.45/);
assert.match(html,/<header class="report-recipient-summary"><h2 id="report-ownership-owner-title">麦麦所属订单净收入<\/h2><div class="report-recipient-total">¥590\.03/);
assert.match(html,/实收 ¥133\.45<\/span><span>实退 ¥5\.00/);assert.match(html,/实收 ¥600\.03<\/span><span>实退 ¥10\.00/);
const receipts=table(html,'助理所属订单收款逐笔明细'),refunds=table(html,'助理所属订单退款逐笔明细');
assert.equal((receipts.match(/<tr(?: class="[^"]*")?>/g)||[]).length,5);assert.match(receipts,/客户-a/);assert.match(receipts,/客户-b/);assert.match(receipts,/收款冲回/);assert.match(receipts,/¥-10\.00/);assert.match(receipts,/收款明细合计<\/td><td class="number">¥133\.45/);
assert.doesNotMatch(receipts,/客户-r<|客户-rr<|退款冲回/);assert.match(refunds,/退款冲回/);assert.match(refunds,/¥-0\.01/);assert.match(refunds,/退款明细合计<\/td><td class="number">¥5\.00/);
assert.match(html,/<summary aria-label="助理所属订单收款明细">收款明细/);assert.match(html,/role="region" aria-label="助理所属订单收款明细表"/);
assert.match(receipts,/2026-10-23/);assert.match(receipts,/普通订单 · 开单 2026-10-22/);
assert.match(table(html,'麦麦所属订单收款逐笔明细'),/锁价 · 按实际收付日/);
assert.equal(h.calls.length,1);assert.equal(h.calls[0].url,'/api/report?basis=orderDate&from='+D+'&date='+D);
});
test('单号与锁价单沿用现有只读打开动作,客户和备注安全转义,缺单号仍可核对',async()=>{
const response=report(),item=response.recipientReceipts.assistant.items[0];item.customer='<img src=x onerror="alert(1)">';item.reference='<script>alert(2)</script>';item.paper_number='纸单 "<01>';
const h=harness(response);await h.run('renderReport()');const html=table(h.content.innerHTML,'助理所属订单收款逐笔明细');
assert.match(html,/&lt;img src=x onerror=&quot;alert\(1\)&quot;&gt;/);assert.match(html,/&lt;script&gt;alert\(2\)&lt;\/script&gt;/);assert.match(html,/纸单 &quot;&lt;01&gt;/);assert.doesNotMatch(html,/<img|<script/);
const locks=table(h.content.innerHTML,'麦麦所属订单收款逐笔明细');assert.match(locks,/data-action="open-price-lock"[^>]*data-id="lock-l"/);assert.match(locks,/data-action="open-order"[^>]*data-id="order-d"/);assert.match(locks,/data-id="lock-d">原锁价单/);
for(const [action,id] of [['open-order','order-a'],['open-price-lock','lock-l']]){
const button={dataset:{action,id},closest(){return null;}};for(const handler of h.handlers.click)await handler({target:{closest:()=>button}});
}
assert.deepEqual(JSON.parse(JSON.stringify(h.calls.slice(1))),[{openOrder:'order-a'},{openPriceLock:'lock-l'}]);
h.context.__item={kind:'receipt',amount:0,account:'助理现金',date:D,order_id:null,price_lock_id:null,order_date:null,number:null,paper_number:null};
const identity=h.run('reportReceiptIdentityHTML(__item)');assert.match(identity,/订单记录/);assert.match(identity,/未填客户称呼/);assert.doesNotMatch(identity,/data-action/);
});
test('老板全部成员空日显示简洁空态,只有退款时仍显示退款及负净收入',async()=>{
const h=harness(report(D,D,true));await h.run('renderReport()');const html=h.content.innerHTML;
assert.equal((html.match(/class="report-recipient-total">¥0\.00/g)||[]).length,0);
assert.match(html,/所选范围暂无所属订单收入、成本或待转记录/);assert.doesNotMatch(html,/aria-label="助理所属订单退款明细"/);
const response=report(D,D,true),refund=payment('only-refund','refund',100,'助理现金');response.recipientReceipts.assistant={recipient:'assistant',name:'助理',receipt:0,refund:100,net:-100,items:[refund]};response.receiptsByOrderDate={receipt:0,refund:100,net:-100};response.ownershipReceipts.assistant=ownershipPerson('assistant','助理',[refund]);response.accounts=[{account:'助理现金',receipt:0,refund:100,net:-100}];syncBusiness(response);
h.context.__response=response;await h.run('renderReport()');assert.match(h.content.innerHTML,/<header class="report-recipient-summary"><h2 id="report-ownership-assistant-title">助理所属订单净收入<\/h2><div class="report-recipient-total">¥-1\.00/);assert.match(h.content.innerHTML,/实收 ¥0\.00<\/span><span>实退 ¥1\.00/);assert.match(table(h.content.innerHTML,'助理所属订单收款逐笔明细'),/所选范围没有助理所属订单收款记录/);assert.match(table(h.content.innerHTML,'助理所属订单退款逐笔明细'),/客户-only-refund/);
});
test('切换日月立即清空旧明细,晚到响应和失败不恢复旧收款,下载只取当前完整报告',async()=>{
const h=harness();await h.run('renderReport()');assert.equal(h.run('requireCurrentReport().date'),D);
const pending=[];h.context.__pending=pending;h.run('api=function(url){__calls.push({url});return new Promise((resolve,reject)=>__pending.push({resolve,reject}));};');
h.range(NEXT);const first=h.run('renderReport()');assert.equal(h.run('currentReport'),null);assert.equal(h.content.attributes['aria-busy'],'true');assert.doesNotMatch(h.content.innerHTML,/收款明细|133\.45/);assert.throws(()=>h.run('requireCurrentReport()'),/正在读取或已失效/);
h.range(NEXT,true);const second=h.run('renderReport()'),month=report(NEXT,'2026-10-01',true);pending[1].resolve(month);await second;
assert.equal(h.run('requireCurrentReport().from'),'2026-10-01');assert.match(h.content.innerHTML,/2026-10-01 至 2026-10-23/);assert.match(h.content.innerHTML,/所选范围暂无所属订单收入、成本或待转记录/);
pending[0].resolve(report(NEXT));await first;assert.equal(h.run('currentReport.from'),'2026-10-01');assert.doesNotMatch(h.content.innerHTML,/客户-a/);
const failure=h.run('renderReport()');pending[2].reject(new Error('合成网络失败'));await failure;assert.equal(h.run('currentReport'),null);assert.equal(h.content.attributes['aria-busy'],'false');assert.match(h.content.innerHTML,/合成网络失败/);assert.doesNotMatch(h.content.innerHTML,/收款明细/);assert.throws(()=>h.run('requireCurrentReport()'),/正在读取或已失效/);
const wrongUser=h.run('renderReport()');h.run("state={...state,user:{id:'different-user'}};");pending[3].resolve(month);await wrongUser;assert.equal(h.run('currentReport'),null);assert.doesNotMatch(h.content.innerHTML,/收款明细/);
});
test('缺收款人字段、错金额或明细不完整时不渲染成零,也不能下载或保存快照',async()=>{
const mutations=[r=>delete r.recipientReceipts,r=>delete r.recipientReceipts.owner,r=>r.recipientReceipts.assistant.items[0].amount='12345',r=>r.recipientReceipts.assistant.items[0].kind='expense',r=>r.recipientReceipts.assistant.items[0].date='2026-02-30',r=>r.recipientReceipts.assistant.items.pop(),r=>r.recipientReceipts.assistant.net++,r=>r.receiptsByOrderDate.receipt++];
for(const mutate of mutations){
const response=report();mutate(response);const h=harness(response);await h.run('renderReport()');assert.equal(h.run('currentReport'),null);assert.match(h.content.innerHTML,/收款人汇总与明细/);assert.doesNotMatch(h.content.innerHTML,/report-recipient-total/);assert.throws(()=>h.run('requireCurrentReport()'),/正在读取或已失效/);
}
});
test('下载包含双方总收款、实际日期、账户及有符号收退款明细,并保持既有对账信息',async()=>{
const h=harness();await h.run('renderReport()');const text=h.run('reportDownloadText(requireCurrentReport())');
assert.match(text,/助理总收款:¥133\.45;退款 ¥5\.00;净收款 ¥128\.45/);assert.match(text,/麦麦总收款:¥600\.03;退款 ¥10\.00;净收款 ¥590\.03/);
assert.match(text,/2026-10-23 \/ 普通订单 · 开单 2026-10-22 \/ 纸单-c \/ 客户 客户-c \/ 助理微信 \/ 收款冲回 ¥-10\.00/);assert.match(text,/退款冲回 ¥-0\.01/);assert.match(text,/收款明细合计:¥133\.45/);assert.match(text,/锁价 · 按实际收付日/);
assert.match(text,/按收款账户核对/);assert.match(text,/双方支出成本/);assert.match(text,/订单与售后净额明细/);assert.match(text,/账面库存/);
});
test('所属净收入已经含他人代收,展示本人加实际代收账户关系且不再加一次',async()=>{
const response=report(),collected=response.recipientReceipts.owner.items.find(item=>item.id==='l'),assistant=response.recipientReceipts.assistant.items;
response.ownershipReceipts={assistant:ownershipPerson('assistant','助理',[...assistant,collected]),owner:ownershipPerson('owner','麦麦',response.recipientReceipts.owner.items.filter(item=>item.id!=='l'))};
syncBusiness(response);const h=harness(response);await h.run('renderReport()');const html=h.content.innerHTML;
assert.ok(html.startsWith('<section class="report-receipts report-ownership-receipts"'));assert.match(html,/助理所属订单净收入<\/h2><div class="report-recipient-total">¥628\.46/);assert.match(html,/本人收款净额 <b>¥128\.45<\/b>/);assert.match(html,/麦麦现金代收净额 <b>¥500\.01<\/b>/);assert.match(html,/=<\/span><strong>¥628\.46/);assert.match(html,/<h3>本人收款<\/h3>/);assert.match(html,/<h3>他人代收<\/h3>/);assert.doesNotMatch(html,/助理净收款<\/h2>|¥1,128\.47/);
const details=table(html,'助理所属订单收款逐笔明细');assert.match(details,/客户-l/);assert.match(details,/客户-a/);assert.match(details,/收款明细合计<\/td><td class="number">¥633\.46/);
const text=h.run('reportDownloadText(requireCurrentReport())');assert.match(text,/助理所属订单净收入:¥628\.46/);assert.match(text,/他人代收 \/ 麦麦现金:实收 ¥500\.01/);assert.equal(h.calls.length,1);assert.ok(h.nodes.get('#main').innerHTML.indexOf('id="report-content"')<h.nodes.get('#main').innerHTML.indexOf('id="daily-funds-content"'));
});
test('按账户核对只隐藏无活动全0账户,纯退款、收退相等和冲零账户仍保留',async()=>{
const response=report(D,D,true),items=[payment('same-receipt','receipt',100,'助理微信'),payment('same-refund','refund',100,'助理微信'),payment('only-refund','refund',80,'麦麦支付宝'),payment('correct-before','receipt',50,'麦麦信用卡'),payment('correct-after','receipt',-50,'麦麦信用卡')];
for(const member of ['owner','assistant']){const rows=items.filter(item=>item.account.startsWith(member==='owner'?'麦麦':'助理')),person=ownershipPerson(member,member==='owner'?'麦麦':'助理',rows);response.ownershipReceipts[member]=person;response.recipientReceipts[member]={recipient:member,name:person.name,receipt:person.receipt,refund:person.refund,net:person.net,items:rows};}
response.receiptsByOrderDate={receipt:100,refund:180,net:-80};response.accounts=Object.values(response.ownershipReceipts).flatMap(person=>person.accounts.map(({account,receipt,refund,net})=>({account,receipt,refund,net}))).concat([{account:'助理现金',receipt:0,refund:0,net:0}]);syncBusiness(response);
const h=harness(response);await h.run('renderReport()');const accounts=table(h.content.innerHTML,'按收款账户核对');assert.doesNotMatch(accounts,/助理现金/);for(const account of ['助理微信','麦麦支付宝','麦麦信用卡'])assert.ok(accounts.includes(account),account);assert.match(accounts,/麦麦支付宝<\/td><td class="number">¥0\.00<\/td><td class="number">¥0\.80<\/td><td class="number">¥-0\.80/);assert.match(accounts,/麦麦信用卡<\/td><td class="number">¥0\.00<\/td><td class="number">¥0\.00<\/td><td class="number">¥0\.00/);
assert.equal(h.run('reportActiveAccounts(currentReport).length'),3);assert.match(table(h.content.innerHTML,'麦麦所属订单收款逐笔明细'),/收款冲回/);
});
test('三人老板全部只显示有活动成员,选择成员或助理只显示该归属且允许跨人代收',async()=>{
const response=report();response.ownershipReceipts.assistant2=ownershipPerson('assistant2','助理2',[]);response.recipientReceipts.assistant2={recipient:'assistant2',name:'助理2',receipt:0,refund:0,net:0,items:[]};syncBusiness(response);const all=harness(response);all.run("state={...state,user:{...state.user,member:'owner'}};");await all.run('renderReport()');assert.doesNotMatch(all.content.innerHTML,/report-ownership-assistant2-title/);assert.match(all.content.innerHTML,/report-ownership-assistant-title/);assert.match(all.content.innerHTML,/report-ownership-owner-title/);
const owned=report(),items=Object.values(owned.recipientReceipts).flatMap(person=>person.items);owned.ownershipReceipts={assistant:ownershipPerson('assistant','助理1',items)};syncBusiness(owned);
const selected=harness(owned);selected.run("state={...state,user:{...state.user,member:'owner'}};reportMember='assistant';");await selected.run('renderReport()');assert.match(selected.content.innerHTML,/助理1所属订单净收入/);assert.doesNotMatch(selected.content.innerHTML,/report-ownership-owner-title|report-ownership-assistant2-title/);assert.ok(selected.calls[0].url.endsWith('&member=assistant'));
const assistant=harness(owned);assistant.run("state={...state,user:{id:'assistant-user',role:'assistant',name:'助理1',member:'assistant'}};");await assistant.run('renderReport()');assert.match(assistant.content.innerHTML,/助理1所属订单净收入/);assert.doesNotMatch(assistant.content.innerHTML,/report-ownership-owner-title/);assert.match(assistant.content.innerHTML,/麦麦现金/);assert.equal(assistant.run('currentReport.ownershipReceipts.assistant.net'),71848);
});
test('选定成员空日保留本人0收入说明,旧双人助理保持原可见两组范围',async()=>{
const empty=report(D,D,true);empty.ownershipReceipts={assistant:empty.ownershipReceipts.assistant};syncBusiness(empty);const h=harness(empty);h.run("state={...state,user:{...state.user,member:'owner'}};reportMember='assistant';");await h.run('renderReport()');assert.match(h.content.innerHTML,/助理所属订单净收入/);assert.match(h.content.innerHTML,/report-recipient-total">¥0\.00/);assert.match(h.content.innerHTML,/所选范围暂无收退款记录/);assert.doesNotMatch(h.content.innerHTML,/report-ownership-owner-title/);
const legacy=harness();legacy.run("state={...state,user:{id:'legacy-assistant',role:'assistant',name:'助理'}};");await legacy.run('renderReport()');assert.match(legacy.content.innerHTML,/助理所属订单净收入/);assert.match(legacy.content.innerHTML,/麦麦所属订单净收入/);assert.equal(legacy.run('currentReport.receiptsByOrderDate.net'),71848);
});
test('缺失所属收入、漏账户、金额或条数不符及跨权限成员均阻止展示和保存',async()=>{
const changes=[r=>delete r.ownershipReceipts,r=>r.ownershipReceipts.assistant.net++,r=>r.ownershipReceipts.assistant.accounts[0].entryCount--,r=>r.ownershipReceipts.assistant.accounts[0].net++,r=>r.ownershipReceipts.assistant.accounts.pop(),r=>r.ownershipReceipts.assistant.member='owner',r=>r.ownershipReceipts.assistant.items=r.ownershipReceipts.assistant.items.slice(0,-1)];
for(const change of changes){const response=report();change(response);const h=harness(response);await h.run('renderReport()');assert.equal(h.run('currentReport'),null);assert.match(h.content.innerHTML,/所属订单净收入与账户明细/);assert.throws(()=>h.run('requireCurrentReport()'),/正在读取或已失效/);assert.doesNotMatch(h.content.innerHTML,/report-ownership-assistant-title/);}
const leaked=harness();leaked.run("state={...state,user:{id:'assistant-user',role:'assistant',name:'助理1',member:'assistant'}};");await leaked.run('renderReport()');assert.equal(leaked.run('currentReport'),null);assert.match(leaked.content.innerHTML,/所属订单净收入与账户明细/);
});
test('所属账户和成员显示名转义,0净冲回明细不能被漏掉而伪装完整',async()=>{
const response=report(),item=response.recipientReceipts.assistant.items[0];item.account='<svg onload=x>';response.accounts[0].account=item.account;response.ownershipReceipts.assistant=ownershipPerson('assistant','<script>显示名</script>',response.recipientReceipts.assistant.items);const h=harness(response);await h.run('renderReport()');assert.match(h.content.innerHTML,/&lt;svg onload=x&gt;/);assert.match(h.content.innerHTML,/&lt;script&gt;显示名&lt;\/script&gt;/);assert.doesNotMatch(h.content.innerHTML,/<svg|<script>/);
const missing=report(),before=payment('zero-a','receipt',50,'助理现金'),after=payment('zero-b','receipt',-50,'助理现金');missing.recipientReceipts.assistant.items.push(before,after);const invalid=harness(missing);await invalid.run('renderReport()');assert.equal(invalid.run('currentReport'),null);assert.match(invalid.content.innerHTML,/所属订单净收入与账户明细/);
});
function counterpart(member,openingDue,periodNew,periodTransferred=0){const closingDue=openingDue+periodNew-periodTransferred;return {member,name:{owner:'麦麦',assistant:'助理1',assistant2:'助理2'}[member],dueOut:Math.max(0,closingDue),dueIn:Math.max(0,-closingDue),openingDue,periodNew,periodTransferred,closingDue,offset:0,period:{obligationNet:periodNew,transferred:periodTransferred,receivedForNet:0,advancedNet:periodNew}};}
function settlement(rows,date=D,from=date,extra={}){return {available:true,basis:'cumulative-through-date',from,date,dueOut:rows.reduce((total,row)=>total+row.dueOut,0),dueIn:rows.reduce((total,row)=>total+row.dueIn,0),partial:false,pendingCount:0,legacyCount:0,notice:'累计余额已抵扣代收和已转款。',counterparts:rows,...extra};}
function businessReport(){
const response=report(D,D,true),own=payment('self','receipt',130000,'助理微信'),other=payment('other','receipt',20000,'麦麦支付宝');
response.recipientReceipts={assistant:{recipient:'assistant',name:'助理1',receipt:130000,refund:0,net:130000,items:[own]},owner:{recipient:'owner',name:'麦麦',receipt:20000,refund:0,net:20000,items:[other]},assistant2:{recipient:'assistant2',name:'助理2',receipt:0,refund:0,net:0,items:[]}};
response.ownershipReceipts={assistant:ownershipPerson('assistant','助理1',[own,other]),owner:ownershipPerson('owner','麦麦',[]),assistant2:ownershipPerson('assistant2','助理2',[])};response.receiptsByOrderDate={receipt:150000,refund:0,net:150000};response.accounts=[{account:'助理微信',receipt:130000,refund:0,net:130000},{account:'麦麦支付宝',receipt:20000,refund:0,net:20000}];syncBusiness(response);
response.ownershipBusiness.assistant=businessPerson(response.ownershipReceipts.assistant,D,D,{costByPayer:{owner:{totalCost:68000,knownTotalCost:68000}},settlement:settlement([counterpart('owner',180000,48000)])});return response;
}
function memberCard(html,member){const match=html.match(new RegExp('<article[^>]*data-member="'+member+'"[^>]*>([\\s\\S]*?)</article>'));assert.ok(match,'应显示 '+member+' 个人经营卡');return match[1];}
function businessHarness(response=businessReport()){const h=harness(response);h.run("state={...state,user:{...state.user,member:'owner'}};");return h;}
test('个人经营卡闭环1500收入、680麦麦付款、820利润;本期480与累计2280分别展示',async()=>{
const h=businessHarness();await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');assert.match(html,/report-recipient-total">¥1,500\.00/);assert.match(html,/所属订单总成本<\/h3><strong>¥680\.00/);assert.match(html,/本人付款 <b>¥0\.00/);assert.match(html,/他人付款 <b>¥680\.00/);assert.match(html,/麦麦 ¥680\.00/);assert.match(html,/所属订单净收入 <b>¥1,500\.00<\/b>/);assert.match(html,/订单总成本 <b>¥680\.00<\/b>/);assert.match(html,/<strong class="">¥820\.00/);
assert.match(html,/本人应转他人<\/span><strong>¥2,280\.00/);assert.match(html,/此前 本人→麦麦 ¥1,800\.00 · 本期新增 本人→麦麦 ¥480\.00/);assert.match(html,/本期实际已转 <b>¥0\.00/);assert.match(html,/截至所选日待转 <strong>¥2,280\.00/);assert.doesNotMatch(html,/本人应转他人<\/span><strong>¥680\.00/);assert.equal(h.calls.length,1);
const lines=h.run('reportOwnershipReceiptsText(currentReport).join(String.fromCharCode(10))');assert.match(lines,/所属订单总成本:¥680\.00;本人付款 ¥0\.00;他人付款 ¥680\.00/);assert.match(lines,/本期利润:¥820\.00/);assert.match(lines,/此前 ¥1,800\.00 + 本期新增 ¥480\.00 − 本期实际已转 ¥0\.00 = 截至所选日 ¥2,280\.00/);
});
test('老板全部保留售后成本only、0元真实售后和纯待转卡,没有收入不漏经营活动',async()=>{
const response=businessReport();response.ownershipBusiness.owner=businessPerson(response.ownershipReceipts.owner,D,D,{hasActivity:true,recordCount:1,afterSaleCount:1,costByPayer:{assistant2:{totalCost:1200,knownTotalCost:1200}}});response.ownershipBusiness.assistant2=businessPerson(response.ownershipReceipts.assistant2,D,D,{hasActivity:true,settlement:settlement([counterpart('owner',0,-1200)])});const h=businessHarness(response);await h.run('renderReport()');const owner=memberCard(h.content.innerHTML,'owner'),helper=memberCard(h.content.innerHTML,'assistant2');assert.match(owner,/含售后 1 笔/);assert.match(owner,/助理2 ¥12\.00/);assert.match(owner,/<strong class="danger-text">¥-12\.00/);assert.doesNotMatch(owner,/<h3>本人收款<\/h3>/);assert.match(helper,/他人应转本人<\/span><strong>¥12\.00/);
response.ownershipBusiness.owner=businessPerson(response.ownershipReceipts.owner,D,D,{hasActivity:true,recordCount:1,afterSaleCount:1});await h.run('renderReport()');assert.match(memberCard(h.content.innerHTML,'owner'),/含售后 1 笔/);
});
test('现金净收与销售不同使用原销售利润式,差异说明转义,月汇总名称准确',async()=>{
const response=businessReport();response.ownershipBusiness.assistant=businessPerson(response.ownershipReceipts.assistant,D,D,{sales:170000,costByPayer:{owner:{totalCost:68000,knownTotalCost:68000}},difference:{amount:-20000,reconciled:false,reasons:[{code:'price_lock_timing',text:'锁价跨日与<原单>分开核对。'}]}});const h=businessHarness(response);await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');assert.match(html,/销售净额 <b>¥1,700\.00/);assert.match(html,/<strong class="">¥1,020\.00/);assert.match(html,/差额 ¥-200\.00/);assert.match(html,/锁价跨日与&lt;原单&gt;分开核对/);assert.doesNotMatch(html,/<原单>|<strong class="">¥820\.00/);
response.from='2026-10-01';for(const b of Object.values(response.ownershipBusiness)){b.from=response.from;b.settlement.from=response.from;}h.range(D,true);await h.run('renderReport()');assert.match(memberCard(h.content.innerHTML,'assistant'),/<h3>本期利润<\/h3>/);
});
test('成本待补只显示已知付款和待核算,已核算利润不能冒充完整利润或结清',async()=>{
const response=businessReport();response.ownershipBusiness.assistant=businessPerson(response.ownershipReceipts.assistant,D,D,{knownProfit:82000,profit:null,costByPayer:{owner:{totalCost:null,knownTotalCost:68000,missingCount:1}},settlement:settlement([] ,D,D,{partial:true,pendingCount:1,notice:'成本待补,仅列已知往来。'})});const h=businessHarness(response);await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');assert.match(html,/已知 ¥680\.00/);assert.match(html,/成本待补齐/);assert.match(html,/report-business-profit-pending">待核算/);assert.match(html,/已知本人应转他人/);assert.match(html,/成本待补,仅列已知往来/);assert.doesNotMatch(html,/¥820\.00|已结清/);const text=h.run('reportOwnershipReceiptsText(currentReport).join(String.fromCharCode(10))');assert.match(text,/本期利润:待核算/);assert.doesNotMatch(text,/本期利润:¥820\.00/);
});
test('逐人待转保留双向余额与负数转入,期初加本期减实转,不抵销成一个净数字',async()=>{
const response=businessReport();response.ownershipBusiness.assistant.settlement=settlement([counterpart('owner',-5000,8000,10000),counterpart('assistant2',10000,-3000,-2000)]);const h=businessHarness(response);await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');assert.match(html,/本人应转他人<\/span><strong>¥90\.00/);assert.match(html,/他人应转本人<\/span><strong>¥70\.00/);assert.match(html,/此前 麦麦→本人 ¥50\.00/);assert.match(html,/本期已转 助理2→本人 ¥20\.00/);assert.match(html,/本期实际已转 <b>(−¥20\.00)/);assert.match(html,/麦麦应转本人 ¥70\.00/);assert.match(html,/本人应转助理2 ¥90\.00/);assert.doesNotMatch(html,/本人应转他人<\/span><strong>¥20\.00/);
});
test('经营投影缺失、付款不平、利润等式或待转构成错误均阻止保存;历史待转不冒充0',async()=>{
const changes=[r=>delete r.ownershipBusiness,r=>r.ownershipBusiness.assistant.netReceipts++,r=>r.ownershipBusiness.assistant.knownTotalCost++,r=>r.ownershipBusiness.assistant.equation.profit++,r=>r.ownershipBusiness.assistant.settlement.counterparts[0].closingDue++,r=>delete r.ownershipBusiness.assistant.costByPayer.owner];
for(const change of changes){const response=businessReport();change(response);const h=businessHarness(response);await h.run('renderReport()');assert.equal(h.run('currentReport'),null);assert.match(h.content.innerHTML,/所属订单成本、利润或待转资料未完整返回/);assert.throws(()=>h.run('requireCurrentReport()'),/正在读取或已失效/);}
const legacy=report();legacy.ownershipBusiness.assistant.settlement.partial=true;legacy.ownershipBusiness.assistant.settlement.legacyCount=1;const h=harness(legacy);await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');assert.match(html,/待核对历史结算,暂不显示待转金额/);assert.doesNotMatch(html,/本人应转他人<\/span><strong>¥0\.00|已结清/);
});