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

397 lines
67 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 {currentAccount}=require('../ownership-business');
const {Ledger}=require('../ledger');
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,ownerAdvances:extra.ownerAdvances??advances(costByPayer.owner.knownTotalCost||costByPayer.owner.missingCount||costByPayer.owner.pendingCount?[advanceDay(date,[...(costByPayer.owner.knownTotalCost?[advanceItem('owner-paid','原订单成本',costByPayer.owner.knownTotalCost,{component:'unallocated'})]:[]),...Array.from({length:costByPayer.owner.missingCount},(_,i)=>advanceItem('missing-'+i,'成本待补',null)),...Array.from({length:costByPayer.owner.pendingCount},(_,i)=>advanceItem('pending-'+i,'费用待核对',null,{status:'pending'}))])]:[],from,date),poolMaterial:extra.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:result.totalCost,knownAmount:result.knownTotalCost}}};
}
function emptyDailyProfits(date,from=date){return {basis:'orderDate',date,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}};}
function syncBusiness(response){response.dailyProfits=emptyDailyProfits(response.date,response.from);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 attachCurrentAccounts(response){
for(const b of Object.values(response.ownershipBusiness||{})){
if(b.currentAccount||!response.ownershipReceipts?.[b.member]||!b.ownerAdvances)continue;
const rows=Array.from({length:b.recordCount},(_,index)=>({date:b.date,profit:index<b.unknownProfitCount?null:0,known:{profit:index===0?b.knownProfit:0},incomplete:index===0&&b.incomplete}));
b.currentAccount=currentAccount(rows,response.ownershipReceipts[b.member],b.ownerAdvances,b.from,b.date);
}
return response;
}
function harness(initial=report()){
attachCurrentAccounts(initial);
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-daily-profits-content',{innerHTML:''}],['#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,__attachCurrentAccounts:attachCurrentAccounts});
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 __attachCurrentAccounts(__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=attachCurrentAccounts(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('当日往来用680垫付加820净利润减200代收得到1300,历史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,/<strong class="">¥820\.00/);
assert.match(html,/<h3>当日往来账<\/h3>/);assert.match(html,/<h4>2026-10-22<\/h4><span>助理1应转麦麦<\/span><strong>¥1,300\.00/);assert.match(html,/麦麦垫付已用料费 ¥0\.00 + 麦麦垫付其他订单成本 ¥680\.00 + 本人当日订单净利润 ¥820\.00 − 麦麦代收净额 ¥200\.00 = ¥1,300\.00/);
assert.doesNotMatch(h.content.innerHTML,/累计往来|逐人核对待转|历史两人结算|¥2,280\.00|此前待转/);assert.equal(h.calls.length,1);
const lines=h.run('reportOwnershipReceiptsText(currentReport).join(String.fromCharCode(10))');assert.match(lines,/当日往来账/);assert.match(lines,/助理1应转麦麦 ¥1,300\.00/);assert.doesNotMatch(lines,/累计往来|逐人核对待转|此前|¥2,280\.00/);
});
test('老板全部保留真实售后和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');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.doesNotMatch(h.content.innerHTML,/report-ownership-assistant2-title/);
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';response.dailyProfits.from=response.from;for(const b of Object.values(response.ownershipBusiness)){b.from=response.from;b.settlement.from=response.from;b.ownerAdvances.from=response.from;delete b.currentAccount;}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,/本人当日订单净利润 待核算(已核算 ¥820\.00)/);assert.match(html,/暂不显示完整应转金额/);assert.doesNotMatch(html,/助理1应转麦麦|已结清/);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=businessPerson(response.ownershipReceipts.assistant,D,D,{sales:13000,costByPayer:{owner:{totalCost:68000,knownTotalCost:68000}},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,/麦麦应转助理1<\/span><strong>¥70\.00/);assert.match(html,/本人当日订单净利润 ¥-550\.00 − 麦麦代收净额 ¥200\.00 = ¥-70\.00/);assert.doesNotMatch(html,/逐人核对待转|此前待转|累计往来|本人应转他人/);assert.match(h.run('reportOwnershipReceiptsText(currentReport).join(String.fromCharCode(10))'),/麦麦应转助理1 ¥70\.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,/待核对历史结算|累计往来/);assert.doesNotMatch(html,/本人应转他人<\/span><strong>¥0\.00|已结清/);
});
function advanceItem(id,name,amount,extra={}){return {date:D,kind:'order',id,number:'XS-'+id,paperNumber:'纸单-'+id,customer:'垫付客户-'+id,name,source:'合成真实成本',component:'fee',poolId:null,poolMaterial:false,allocationPending:false,amount,estimatedAmount:null,status:amount===null?'missing':'recorded',...extra};}
function advanceDay(date,items){
const recorded=items.filter(item=>item.status==='recorded'),missing=items.filter(item=>item.status==='missing'),sum=rows=>rows.reduce((total,item)=>total+item.amount,0),knownAmount=sum(recorded),knownPoolAmount=sum(recorded.filter(item=>item.poolMaterial)),knownOtherAmount=knownAmount-knownPoolAmount;
return {date,items:items.map(item=>({...item,date})),knownAmount,amount:missing.length?null:knownAmount,missingCount:missing.length,pendingCount:items.filter(item=>item.status==='pending').length,poolAmount:missing.some(item=>item.poolMaterial)?null:knownPoolAmount,knownPoolAmount,otherAmount:missing.some(item=>!item.poolMaterial)?null:knownOtherAmount,knownOtherAmount};
}
function advances(days,from=D,date=D){return {basis:'orderDate',from,date,days};}
function poolBusinessReport(){
const response=businessReport(),byPayer={owner:{amount:103333,knownAmount:103333},assistant:{amount:90000,knownAmount:90000},assistant2:{amount:0,knownAmount:0}},day={poolId:D,date:D,mg:2000,averageRate:96667,amount:193333,knownAmount:193333,missingCount:0,byPayer};
response.ownershipBusiness.assistant=businessPerson(response.ownershipReceipts.assistant,D,D,{costByPayer:{owner:{totalCost:106933,knownTotalCost:106933},assistant:{totalCost:90300,knownTotalCost:90300}},poolMaterial:{mg:2000,amount:193333,knownAmount:193333,missingCount:0,hasPriceLocks:false,byPayer,days:[day],otherCosts:{amount:3900,knownAmount:3900}},settlement:settlement([counterpart('owner',50000,86933)])});
response.ownershipBusiness.assistant.ownerAdvances=advances([advanceDay(D,[advanceItem('pool','料池料费 · 麦麦垫付部分',103333,{component:'material',poolId:D,poolMaterial:true}),advanceItem('fee','实际工费与运费',3600)])]);
return response;
}
test('料池用料在所属订单卡直接可见,保留原分币金额、麦麦垫付和其他成本,待转不再加一次',async()=>{
const h=businessHarness(poolBusinessReport());await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');
assert.match(html,/所属订单总成本<\/h3><strong>¥1,972\.33/);assert.match(html,/料池已用料费<\/span><strong>¥1,933\.33/);assert.match(html,/2\.000g × ¥966\.67\/g = ¥1,933\.33/);assert.match(html,/其中麦麦垫付 <b>¥1,033\.33/);assert.match(html,/其他成本 <b>¥39\.00/);assert.match(html,/助理1应转麦麦<\/span><strong>¥397\.00/);assert.match(html,/公式中计入一次/);assert.match(html,/未四舍五入均价/);assert.doesNotMatch(html,/1,933\.34|3,302\.66/);
assert.match(html,/麦麦垫付合计:料池料费 ¥1,033\.33 + 其他成本 ¥36\.00 = ¥1,069\.33/);assert.doesNotMatch(html,/麦麦垫付合计:料池料费 ¥1,033\.33 + 其他成本 ¥39\.00/);
const text=h.run('reportOwnershipReceiptsText(currentReport).join(String.fromCharCode(10))');assert.match(text,/料池已用料费:¥1,933\.33/);assert.match(text,/2\.000g × ¥966\.67\/g = ¥1,933\.33/);assert.match(text,/其中麦麦垫付:¥1,033\.33/);assert.match(text,/其他成本:¥39\.00/);
assert.match(text,/麦麦垫付合计:料池料费 ¥1,033\.33 + 其他成本 ¥36\.00 = ¥1,069\.33/);
});
function sourcePoolBusinessReport(){
const response=poolBusinessReport(),day=response.ownershipBusiness.assistant.poolMaterial.days[0];
day.averageRate=null;day.sources=[{kind:'personal_recovery',member:'assistant',priceLocked:false,mg:1000,averageRate:90000,amount:90000,knownAmount:90000,missingCount:0},{kind:'public',member:null,priceLocked:false,mg:1000,averageRate:103333,amount:103333,knownAmount:103333,missingCount:0}];
return response;
}
test('个人与公共用料各一行公式,同日汇总克重及原分币料费明显,文本包含组合公式',async()=>{
const h=businessHarness(sourcePoolBusinessReport());await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');
assert.match(html,/已用料合计<\/span><strong>2\.000g/);assert.match(html,/料池已用料费<\/span><strong>¥1,933\.33/);assert.match(html,/已用 2\.000g · 料费 ¥1,933\.33/);
assert.match(html,/<p><span>娜娜个人回收料<\/span><strong>1\.000g × ¥900\.00\/g = ¥900\.00<\/strong><\/p>/);assert.match(html,/<p><span>公共料<\/span><strong>1\.000g × ¥1,033\.33\/g = ¥1,033\.33<\/strong><\/p>/);assert.doesNotMatch(html,/2\.000g ×/);
const text=h.run('reportOwnershipReceiptsText(currentReport).join(String.fromCharCode(10))');assert.match(text,/已用料合计:2\.000g/);assert.match(text,/娜娜个人回收料 1\.000g × ¥900\.00\/g + 公共料 1\.000g × ¥1,033\.33\/g = ¥1,933\.33/);
});
test('同日不同锁价原均价分别显示,不合成新料价;来源不全或克重金额不平不能保存',async()=>{
const response=sourcePoolBusinessReport(),day=response.ownershipBusiness.assistant.poolMaterial.days[0];day.sources[0]={...day.sources[0],kind:'public',member:null,priceLocked:true};
const h=businessHarness(response);await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');assert.match(html,/公共料(含锁价原料)<\/span><strong>1\.000g × ¥900\.00\/g = ¥900\.00/);assert.match(html,/公共料<\/span><strong>1\.000g × ¥1,033\.33\/g = ¥1,033\.33/);assert.doesNotMatch(html,/966\.67/);
for(const change of [d=>d.sources[0].mg++,d=>d.sources[0].amount++,d=>d.sources[0].knownAmount++,d=>delete d.sources[0].priceLocked,d=>d.sources[0].member='outside',d=>d.sources=[]]){
const broken=sourcePoolBusinessReport();change(broken.ownershipBusiness.assistant.poolMaterial.days[0]);const invalid=businessHarness(broken);await invalid.run('renderReport()');assert.equal(invalid.run('currentReport'),null);assert.match(invalid.content.innerHTML,/所属订单成本、利润或待转资料未完整返回/);
}
});
test('多日料池各列原均价与耗用额,跨日锁价说明不把交付料费当作本日新往来',async()=>{
const response=poolBusinessReport(),pool=response.ownershipBusiness.assistant.poolMaterial,prior='2026-10-21';
pool.hasPriceLocks=true;pool.days=[{...pool.days[0],poolId:prior,date:prior,mg:1000,averageRate:90000,amount:90000,knownAmount:90000,byPayer:{owner:{amount:0,knownAmount:0},assistant:{amount:90000,knownAmount:90000},assistant2:{amount:0,knownAmount:0}}},{...pool.days[0],mg:1000,averageRate:103333,amount:103333,knownAmount:103333,byPayer:{owner:{amount:103333,knownAmount:103333},assistant:{amount:0,knownAmount:0},assistant2:{amount:0,knownAmount:0}}}];
const h=businessHarness(response);await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');assert.match(html,/2026-10-21 料池/);assert.match(html,/1\.000g × ¥900\.00\/g = ¥900\.00/);assert.match(html,/2026-10-22 料池/);assert.match(html,/1\.000g × ¥1,033\.33\/g = ¥1,033\.33/);assert.match(html,/交付日的当日往来中列示,不重复记实际采购支出/);assert.match(html,/助理1应转麦麦<\/span><strong>¥397\.00/);
});
test('待补料费与未知FIFO付款人显示已知额和待补,其他已核实成本继续显示',async()=>{
const response=poolBusinessReport(),pool=response.ownershipBusiness.assistant.poolMaterial;
pool.amount=null;pool.knownAmount=0;pool.missingCount=1;pool.byPayer=Object.fromEntries(['owner','assistant','assistant2'].map(key=>[key,{amount:null,knownAmount:0}]));pool.days=[{poolId:D,date:D,mg:2000,averageRate:null,amount:null,knownAmount:0,missingCount:1,byPayer:pool.byPayer}];
response.ownershipBusiness.assistant=businessPerson(response.ownershipReceipts.assistant,D,D,{costByPayer:{owner:{totalCost:null,knownTotalCost:3600,missingCount:1},assistant:{totalCost:300,knownTotalCost:300}},poolMaterial:pool,settlement:settlement([],D,D,{partial:true,pendingCount:1})});
response.ownershipBusiness.assistant.ownerAdvances=advances([advanceDay(D,[advanceItem('missing-pool','料池料费 · 麦麦份额待补',null,{component:'material',poolId:D,poolMaterial:true,allocationPending:true}),advanceItem('paid-fee','实际工费与运费',3600)])]);
const h=businessHarness(response);await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');assert.match(html,/2\.000g × 待补料价 = 料费待补(已知 ¥0\.00)/);assert.match(html,/其中麦麦垫付 <b>已知 ¥0\.00/);assert.match(html,/其他成本 <b>¥39\.00/);assert.match(html,/待核算/);assert.doesNotMatch(html,/2\.000g × ¥0\.00/);
assert.match(html,/麦麦垫付合计:料池料费 待补(已知 ¥0\.00) + 其他成本 ¥36\.00 = 待补(已知 ¥36\.00)/);
});
test('个人来源已知而公共待补仍保留整单待补,已知料费和其他成本不提前改账',async()=>{
const response=sourcePoolBusinessReport(),pool=response.ownershipBusiness.assistant.poolMaterial;
pool.amount=null;pool.knownAmount=0;pool.missingCount=1;pool.byPayer=Object.fromEntries(['owner','assistant','assistant2'].map(key=>[key,{amount:null,knownAmount:0}]));
pool.days[0]={...pool.days[0],amount:null,knownAmount:0,missingCount:1,byPayer:pool.byPayer};pool.days[0].sources[1]={...pool.days[0].sources[1],averageRate:null,amount:null,knownAmount:0,missingCount:1};
response.ownershipBusiness.assistant=businessPerson(response.ownershipReceipts.assistant,D,D,{costByPayer:{owner:{totalCost:null,knownTotalCost:3600,missingCount:1},assistant:{totalCost:300,knownTotalCost:300}},poolMaterial:pool,settlement:settlement([],D,D,{partial:true,pendingCount:1})});
const h=businessHarness(response);await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant');assert.match(html,/娜娜个人回收料<\/span><strong>1\.000g × ¥900\.00\/g = ¥900\.00/);assert.match(html,/公共料<\/span><strong>1\.000g × 待补料价 = 料费待补(已知 ¥0\.00)/);assert.match(html,/料池已用料费<\/span><strong>已知 ¥0\.00/);assert.match(html,/其他成本 <b>¥39\.00/);assert.match(html,/料费待补的订单尚未计入已知料费/);assert.ok(h.run('currentReport'));
});
test('料费分项、克重、付款归属和其他成本必须守恒,缺失投影不会把料费隐藏成0',async()=>{
const changes=[r=>delete r.ownershipBusiness.assistant.poolMaterial,r=>r.ownershipBusiness.assistant.poolMaterial.mg++,r=>r.ownershipBusiness.assistant.poolMaterial.days[0].amount++,r=>r.ownershipBusiness.assistant.poolMaterial.byPayer.owner.knownAmount++,r=>r.ownershipBusiness.assistant.poolMaterial.otherCosts.knownAmount++];
for(const change of changes){const response=poolBusinessReport();change(response);const h=businessHarness(response);await h.run('renderReport()');assert.equal(h.run('currentReport'),null);assert.match(h.content.innerHTML,/所属订单成本、利润或待转资料未完整返回/);assert.doesNotMatch(h.content.innerHTML,/料池已用料费<\/span>/);}
});
2026-11-04 00:12:34 +08:00
test('麦麦逐笔垫付默认收起且客户可打开原单,多人池料子行只显示分摊金额,所有文字转义',async()=>{
const response=poolBusinessReport(),day=response.ownershipBusiness.assistant.ownerAdvances.days[0];day.items[0].customer='<img src=x>';day.items[1].name='<script>实际运费</script>';day.items[1].source='<b>付款备注</b>';
const h=businessHarness(response);await h.run('renderReport()');const card=memberCard(h.content.innerHTML,'assistant'),html=table(card,D+' 麦麦垫付明细');
2026-11-04 00:12:34 +08:00
assert.match(card,/<details class="report-owner-advances"[^>]*><summary>当日麦麦垫付明细<\/summary>/);assert.doesNotMatch(card,/<details[^>]*report-owner-advances[^>]*\sopen(?:\s|=|>)/);assert.match(card,/垫付小计 <strong>¥1,069\.33/);assert.match(html,/<th>日期<\/th><th>客户/单号<\/th><th>成本项目<\/th><th class="number">麦麦承担金额/);assert.match(html,/料池料费 · 麦麦垫付部分/);assert.match(html,/¥1,033\.33/);assert.doesNotMatch(html,/2\.000g|×/);assert.match(html,/&lt;img src=x&gt;/);assert.match(html,/&lt;script&gt;实际运费&lt;\/script&gt;/);assert.match(html,/&lt;b&gt;付款备注&lt;\/b&gt;/);assert.doesNotMatch(html,/<img|<script|<b>/);
assert.ok(card.indexOf('report-owner-advances')<card.indexOf('report-business-current'));assert.match(card,/<section class="report-business-settlement report-business-current"/);assert.doesNotMatch(card,/report-business-history|累计往来|逐人核对待转/);
const button={dataset:{action:'open-order',id:'pool'},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:'pool'}]);
const text=h.run('reportOwnershipReceiptsText(currentReport).join(String.fromCharCode(10))');assert.match(text,/2026-10-22 垫付小计:¥1,069\.33/);assert.match(text,/2026-10-22 \/ 助理1应转麦麦 ¥397\.00/);assert.doesNotMatch(text,/累计往来|逐人核对待转/);
});
test('月份垫付明细只列实际记录日期及各日小计,不把月合计或历史余额当每天垫付',async()=>{
const response=poolBusinessReport(),from='2026-10-01',prior='2026-10-21',old=response.ownershipBusiness.assistant;
response.from=from;response.dailyProfits.from=from;for(const b of Object.values(response.ownershipBusiness)){b.from=from;b.ownerAdvances.from=from;b.settlement.from=from;}
response.ownershipBusiness.assistant=businessPerson(response.ownershipReceipts.assistant,D,from,{costByPayer:{owner:{totalCost:116933,knownTotalCost:116933},assistant:{totalCost:90300,knownTotalCost:90300}},poolMaterial:{...old.poolMaterial,otherCosts:{amount:13900,knownAmount:13900}},ownerAdvances:advances([advanceDay(prior,[advanceItem('yesterday','昨日实际配件',10000)]),...old.ownerAdvances.days],from,D),settlement:settlement([counterpart('owner',50000,96933)],D,from)});
2026-11-04 00:12:34 +08:00
const h=businessHarness(response);h.range(D,true);await h.run('renderReport()');const card=memberCard(h.content.innerHTML,'assistant');assert.match(card,/<details class="report-owner-advances"[^>]*><summary>按日核对麦麦垫付明细<\/summary>/);assert.doesNotMatch(card,/<details[^>]*report-owner-advances[^>]*\sopen(?:\s|=|>)/);assert.match(card,/<h4>2026-10-21<\/h4><span>垫付小计 <strong>¥100\.00/);assert.match(card,/<h4>2026-10-22<\/h4><span>垫付小计 <strong>¥1,069\.33/);assert.doesNotMatch(card,/垫付小计 <strong>¥1,169\.33|<h4>2026-10-01/);assert.equal((card.match(/class="report-owner-advance-day"/g)||[]).length,2);
const text=h.run('reportOwnershipReceiptsText(currentReport).join(String.fromCharCode(10))');assert.match(text,/2026-10-21 垫付小计:¥100\.00/);assert.match(text,/2026-10-22 垫付小计:¥1,069\.33/);assert.doesNotMatch(text,/垫付小计:¥1,169\.33/);
});
test('只有历史余额的空日不显示历史卡,所选成员显示当日0,预估未付不计垫付',async()=>{
const response=report(D,D,true);response.ownershipBusiness.assistant.hasActivity=true;response.ownershipBusiness.assistant.settlement=settlement([counterpart('owner',50000,0)]);
const h=harness(response);await h.run('renderReport()');assert.doesNotMatch(h.content.innerHTML,/report-ownership-assistant-title|累计往来/);h.run("reportMember='assistant';");await h.run('renderReport()');let card=memberCard(h.content.innerHTML,'assistant');assert.match(card,/垫付小计 <strong>¥0\.00/);assert.match(card,/当日无需转款<\/span><strong>¥0\.00/);assert.doesNotMatch(card,/已结清|¥500\.00|累计往来/);
const b=response.ownershipBusiness.assistant;b.recordCount=1;b.unknownProfitCount=1;b.profit=null;b.incomplete=true;b.equation.profit=null;b.equation.complete=false;b.ownerAdvances=advances([advanceDay(D,[advanceItem('estimate','预估未付运费',null,{status:'pending',estimatedAmount:100000})])]);delete b.currentAccount;await h.run('renderReport()');card=memberCard(h.content.innerHTML,'assistant');assert.match(card,/垫付小计 <strong>¥0\.00/);assert.match(table(card,D+' 麦麦垫付明细'),/待核对(预估 ¥1,000\.00),未计垫付/);assert.match(card,/预估金额不计垫付小计/);assert.match(card,/应转金额待核算/);
});
test('垫付明细缺失、日期越界、小计不平或付款项目错误时阻止回执和下载',async()=>{
const changes=[r=>delete r.ownershipBusiness.assistant.ownerAdvances,r=>r.ownershipBusiness.assistant.ownerAdvances.days[0].date='2026-10-21',r=>r.ownershipBusiness.assistant.ownerAdvances.days[0].amount++,r=>r.ownershipBusiness.assistant.ownerAdvances.days[0].items[0].amount++,r=>r.ownershipBusiness.assistant.ownerAdvances.days[0].items[0].status='pending'];
for(const change of changes){const response=poolBusinessReport();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()'),/正在读取或已失效/);}
});
function dailyProfitReport(){
const response=report(D,D,true),rows=[{date:D,member:'owner',name:'麦麦',recordCount:1,orderCount:0,afterSaleCount:1,draftCount:0,sales:0,totalCost:500,knownTotalCost:500,profit:-500,knownProfit:-500,unknownCostCount:0,unknownProfitCount:0,incomplete:false},{date:D,member:'assistant',name:'助理',recordCount:1,orderCount:1,afterSaleCount:0,draftCount:0,sales:50000,totalCost:40000,knownTotalCost:40000,profit:10000,knownProfit:10000,unknownCostCount:0,unknownProfitCount:0,incomplete:false}];
const summary={...emptyDailyProfits(D).summary,recordCount:2,orderCount:1,afterSaleCount:1,sales:50000,totalCost:40500,knownTotalCost:40500,profit:9500,knownProfit:9500};response.dailyProfits={basis:'orderDate',from:D,date:D,rows,summary};Object.assign(response.summary,{recordCount:2,orderCount:1,completedCount:1,afterSaleCount:1,sale:50000,totalCost:40500,profit:9500});
response.orderRows=rows.map((row,index)=>({id:'profit-'+index,date:D,member:row.member,kind:index===0?'afterSale':undefined,status:index===0?'after_sale':'delivered',number:'XS-'+index,customer:'合成利润客户',project:'合成维修',sale:row.sales,totalCost:row.totalCost,profit:row.profit,known:{sale:row.sales,totalCost:row.knownTotalCost,profit:row.knownProfit},costItems:[{kind:index===0?'afterSale':'goods',component:index===0?'fee':'unallocated',payer:row.member,amount:row.totalCost}],pendingCostItems:[]}));return response;
}
test('每日利润表位于资金核对之后的页面最后,列出归属、销售成本利润及合计,负数和两种下载一致',async()=>{
const h=harness(dailyProfitReport());await h.run('renderReport()');const html=h.nodes.get('#report-daily-profits-content').innerHTML,profit=table(html,'每日利润明细'),page=h.nodes.get('#main').innerHTML;assert.ok(html.startsWith('<section class="panel report-daily-profits"'));assert.ok(page.indexOf('id="daily-funds-content"')<page.indexOf('id="report-daily-profits-content"'));assert.match(page,/<div id="report-daily-profits-content" aria-live="polite"><\/div>$/);assert.doesNotMatch(h.content.innerHTML,/每日利润表/);assert.match(html,/勾选“汇总当月”可查看当月逐日利润/);assert.match(profit,/<th scope="col">日期<\/th><th scope="col">归属人/);assert.match(profit,/data-date="2026-10-22" data-member="owner"/);assert.match(profit,/class="number danger-text">¥-5\.00/);assert.match(profit,/所选范围合计<\/td><td class="number">¥500\.00<\/td><td class="number">¥405\.00<\/td><td class="number">¥95\.00/);
assert.match(h.run('reportDownloadText(requireCurrentReport())'),/2026-10-22 \/ 麦麦 \/ 销售净额 ¥0\.00 \/ 成本 ¥5\.00 \/ 利润 ¥-5\.00/);h.context.dailyFundsDownloadText=()=>[];assert.match(h.run('reportTeamDownloadText(requireCurrentReport())'),/每日利润表/);assert.match(h.run('reportTeamDownloadText(requireCurrentReport())'),/所选范围合计:销售净额 ¥500\.00 \/ 成本 ¥405\.00 \/ 利润 ¥95\.00/);
});
test('成本和利润待补显示待核算及已核算部分,不把销售减已知成本冒充利润;空日不造业务行',async()=>{
const response=dailyProfitReport(),row=response.dailyProfits.rows[1],summary=response.dailyProfits.summary;Object.assign(row,{totalCost:null,profit:null,knownProfit:0,unknownCostCount:1,unknownProfitCount:1,incomplete:true});Object.assign(summary,{totalCost:null,profit:null,knownProfit:-500,unknownCostCount:1,unknownProfitCount:1,incomplete:true});Object.assign(response.summary,{profit:-500,unknownCostCount:1,unknownProfitCount:1});response.orderRows[1].totalCost=null;response.orderRows[1].profit=null;response.orderRows[1].known.profit=0;
const h=harness(response);await h.run('renderReport()');const html=table(h.nodes.get('#report-daily-profits-content').innerHTML,'每日利润明细');assert.match(html,/待补齐(已知 ¥400\.00)/);assert.match(html,/待核算(已核算 ¥0\.00)/);assert.match(html,/待核算(已核算 ¥-5\.00)/);assert.doesNotMatch(html,/利润<[^>]*>¥100\.00|¥95\.00/);
h.context.__response=report(D,D,true);await h.run('renderReport()');const empty=table(h.nodes.get('#report-daily-profits-content').innerHTML,'每日利润明细');assert.match(empty,/所选范围暂无订单或售后记录/);assert.doesNotMatch(empty,/data-date=/);
});
test('每日利润缺失、越权归属、利润错误、日期越界或合计不平会阻止保存和下载',async()=>{
const changes=[r=>delete r.dailyProfits,r=>r.dailyProfits.rows[0].member='assistant2',r=>r.dailyProfits.rows[0].profit++,r=>r.dailyProfits.rows[0].date='2026-10-21',r=>r.dailyProfits.summary.knownProfit++];
for(const change of changes){const response=dailyProfitReport();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()'),/正在读取或已失效/);}
});
test('月模式当日往来逐日列日期方向和金额,不将月利润或合计贴在某一天',async()=>{
const response=businessReport(),from='2026-10-01',prior='2026-10-21';response.from=from;response.dailyProfits.from=from;
for(const b of Object.values(response.ownershipBusiness)){b.from=from;b.ownerAdvances.from=from;b.settlement.from=from;}
const b=businessPerson(response.ownershipReceipts.assistant,D,from,{recordCount:2,orderCount:2,costByPayer:{owner:{totalCost:78000,knownTotalCost:78000}},ownerAdvances:advances([advanceDay(prior,[advanceItem('prior','昨日已付成本',10000)]),advanceDay(D,[advanceItem('today','今日已付成本',68000)])],from,D),settlement:settlement([counterpart('owner',500000,78000)],D,from)});
b.currentAccount=currentAccount([{date:prior,known:{profit:1000},profit:1000,incomplete:false},{date:D,known:{profit:71000},profit:71000,incomplete:false}],response.ownershipReceipts.assistant,b.ownerAdvances,from,D);response.ownershipBusiness.assistant=b;
const h=businessHarness(response);h.range(D,true);await h.run('renderReport()');const html=memberCard(h.content.innerHTML,'assistant'),section=html.slice(html.indexOf('report-business-current'));
assert.match(section,/按所选范围逐日核对/);assert.match(section,/<h4>2026-10-21<\/h4><span>助理1应转麦麦<\/span><strong>¥110\.00/);assert.match(section,/<h4>2026-10-22<\/h4><span>助理1应转麦麦<\/span><strong>¥1,190\.00/);assert.doesNotMatch(section,/<strong>¥1,300\.00|累计往来|逐人核对待转/);assert.equal((section.match(/class="report-current-day"/g)||[]).length,2);
const text=h.run('reportOwnershipReceiptsText(currentReport).join(String.fromCharCode(10))');assert.match(text,/2026-10-21 \/ 助理1应转麦麦 ¥110\.00/);assert.match(text,/2026-10-22 \/ 助理1应转麦麦 ¥1,190\.00/);
});
test('当日往来缺失、日期越界、成本分类或等式不平时不输出伪造0或允许下载',async()=>{
const changes=[b=>delete b.currentAccount,b=>b.currentAccount.days[0].date='2026-10-21',b=>b.currentAccount.days[0].amount++,b=>b.currentAccount.days[0].knownMaterialCost++,b=>b.currentAccount.days[0].ownerNetReceipts++,b=>b.currentAccount.days=[]];
for(const change of changes){const response=poolBusinessReport(),h=businessHarness(response);change(response.ownershipBusiness.assistant);h.run('api=async function(){return __response;};');await h.run('renderReport()');assert.equal(h.run('currentReport'),null);assert.match(h.content.innerHTML,/所属订单成本、利润或待转资料未完整返回/);assert.doesNotMatch(h.content.innerHTML,/report-business-current/);assert.throws(()=>h.run('requireCurrentReport()'),/正在读取或已失效/);}
});
function afterSaleReportFixture(t,{payer='owner',refundAccount='麦麦支付宝',pool=false}={}){
const ledger=new Ledger(':memory:'),actors={};t.after(()=>ledger.close());
for(const member of ['owner','assistant','assistant2']){
const actor={id:randomUUID(),name:'合成'+member,role:member==='owner'?'owner':'assistant'};actors[member]=actor;
ledger.run('INSERT INTO users VALUES (?,?,?,?,?)',actor.id,actor.name,actor.role,'synthetic-salt','synthetic-hash');ledger.bindMemberUser(actor.id,member);
}
ledger.enableTeamMode();
const originalDate='2026-10-21',run=(input,fn)=>ledger.scope(actors.owner,()=>ledger.transact(randomUUID(),actors.owner,input,fn));
run({},()=>ledger.stock({date:originalDate,kind:'opening',pocket:'现货',grams:'20',note:'合成售后测试库存'},actors.owner));
if(pool){const input={date:originalDate,grams:'10',total:'6000',payer,note:'合成售后原购料'};run(input,()=>ledger.createMaterialPurchase(input,actors.owner));}
const line={name:'足金合成挂件',unit:'g',quantity:'1.000',pocket:'现货',payer,sale:'1419',costPayers:{material:payer,labor:payer},
costParts:{material:pool?'':'1200',labor:'50',accessories:'0',other:'0'},...(pool?{costMaterial:{mode:'pool',poolId:originalDate}}:{})};
const input={date:originalDate,member:'assistant',customer:'合成售后客户',salesperson:'合成开单人',payment_account:'助理微信',rounding_mode:'cent',fee_items:[{key:'shipping',note:'合成运费',amount:'10',payer:'owner'}],lines:[line]};
const id=run(input,()=>ledger.issueOrder(input,actors.owner)).id;
const read=(date=D,from=date,actor=actors.owner,member)=>JSON.parse(JSON.stringify(ledger.asActor(actor).reportFor({date,from,basis:'orderDate',...(member?{member}:{})},actor)));
const original=read(originalDate),data={date:D,revision:ledger.detail(id).revision,verified:true,reason:'合成已核实退回现货',afterSale:{lines:[{lineIndex:0,quantity:'1.000',pocket:'现货',disposition:'stock'}],refund:{amount:'1300',account:refundAccount,payer:refundAccount.startsWith('麦麦')?'owner':'assistant'},deductionReason:'合成客户确认扣费',expenses:[]}};
run(data,()=>ledger.action(id,'return',data,actors.owner));
return {ledger,actors,id,line,run,read,original,originalDate};
}
test('真实售后负成本和负垫付通过逐项回流核验,跨日麦麦退款按实际日抵扣,原日及导出金额不变',async t=>{
const f=afterSaleReportFixture(t),response=f.read(),b=response.ownershipBusiness.assistant,h=businessHarness(response);await h.run('renderReport()');
assert.equal(h.run('currentReport.profit'),-5000);assert.equal(b.poolMaterial.otherCosts.amount,-125000);assert.equal(b.ownerAdvances.days[0].amount,-125000);
assert.equal(b.currentAccount.days[0].ownerNetReceipts,-130000);assert.equal(b.currentAccount.days[0].amount,0);
const card=memberCard(h.content.innerHTML,'assistant');assert.match(card,/¥-1,250\.00/);assert.match(card,/当日无需转款/);assert.match(card,/订单售后 · 按实际收付日/);
h.context.dailyFundsDownloadText=()=>[];assert.match(h.run('reportDownloadText(requireCurrentReport())'),/订单售后 · 按实际收付日/);
const original=f.read(f.originalDate);for(const key of ['sales','totalCost','profit','outlayTotal','reportRevision','receiptsByOrderDate','dailyProfits'])assert.deepEqual(original[key],f.original[key],'售后不改原开单日的'+key);
const old=businessHarness(original);old.range(f.originalDate);await old.run('renderReport()');assert.equal(old.run('currentReport.profit'),15900);
const month=businessHarness(f.read(D,'2026-10-01'));month.range(D,true);await month.run('renderReport()');assert.equal(month.run('currentReport.profit'),10900);assert.equal(month.run('currentReport.ownershipBusiness.assistant.currentAccount.days[1].ownerNetReceipts'),-130000);
});
test('真实助理成本回库及料池月内先耗用后回库都保留负调整,现货再售不新增现金支出',async t=>{
const assistant=afterSaleReportFixture(t,{payer:'assistant',refundAccount:'助理支付宝'}),day=businessHarness(assistant.read());await day.run('renderReport()');
assert.equal(day.run('currentReport.ownershipBusiness.assistant.totalCost'),-125000);assert.equal(day.run('currentReport.ownershipBusiness.assistant.ownerAdvances.days.length'),0);
const f=afterSaleReportFixture(t,{pool:true}),response=f.read(D,'2026-10-01'),b=response.ownershipBusiness.assistant,month=businessHarness(response);month.range(D,true);await month.run('renderReport()');
assert.equal(month.run('currentReport.ownershipBusiness.assistant.totalCost'),1000);assert.equal(b.poolMaterial.amount,60000);assert.equal(b.poolMaterial.otherCosts.amount,-59000);assert.equal(b.costByPayer.owner.totalCost,1000);
const lot=f.ledger.returnedStockLots({date:NEXT},f.actors.owner).lots[0],input={date:NEXT,member:'assistant',customer:'合成现货再售',salesperson:'合成开单人',payment_account:'助理微信',rounding_mode:'cent',fee_items:[],lines:[{...f.line,sale:'1400',returnedStockId:lot.id,costParts:{material:'',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'pool',poolId:lot.effectivePoolId}}]};
f.run(input,()=>f.ledger.issueOrder(input,f.actors.owner));const resale=businessHarness(f.read(NEXT));resale.range(NEXT);await resale.run('renderReport()');assert.equal(resale.run('currentReport.profit'),75000);assert.equal(resale.run('currentReport.outlayTotal'),0);
});
test('售后标志、成本回流分摊或负垫付被篡改仍拒绝保存下载,普通负成本不能冒充售后',async t=>{
const f=afterSaleReportFixture(t),base=f.read(),changes=[
r=>r.orderRows[0].kind='afterSale',
r=>delete r.orderRows[0].costItems[0].nonCash,
r=>r.orderRows[0].orderAfterSale.summary.materialReturnedCost++,
r=>r.orderRows[0].orderAfterSale.summary.lines[0].materialAllocations[0].amount++,
r=>r.ownershipBusiness.assistant.ownerAdvances.days[0].items[0].nonCash=false,
r=>r.ownershipBusiness.assistant.ownerAdvances.days[0].items[0].amount++,
r=>r.ownershipBusiness.assistant.poolMaterial.otherCosts.knownAmount++,
r=>r.ownershipBusiness.assistant.currentAccount.days[0].ownerNetReceipts++,
r=>{for(const person of Object.values(r.ownershipReceipts))for(const item of person.items)delete item.order_after_sale;},
r=>{const b=r.ownershipBusiness.assistant;b.ownerAdvances.days=[];b.currentAccount=currentAccount(r.orderRows,r.ownershipReceipts.assistant,b.ownerAdvances,b.from,b.date);}
];
for(const change of changes){const response=JSON.parse(JSON.stringify(base));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()'),/正在读取或已失效/);}
});