2026-10-23 09:49:36 +08:00
'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 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 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 { 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 , 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' , '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 ];
}
2026-10-24 16:09:45 +08:00
test ( '收款人净额在账户表上方,收款与退款各自逐笔合计,冲回保留符号与明确标签' , async ()=>{
2026-10-23 09:49:36 +08:00
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' );
2026-10-24 16:09:45 +08:00
for ( const name of [ '助理净收款' , '麦麦净收款' ]) assert . ok ( html . indexOf ( name ) < html . indexOf ( '按收款账户核对' ));
assert . match ( html , /助理净收款<\/h2><div class="report-recipient-total">¥128\.45/ );
assert . match ( html , /麦麦净收款<\/h2><div class="report-recipient-total">¥590\.03/ );
assert . match ( html , /退款 ¥5\.00<\/span><span>总收款 ¥133\.45/ ); assert . match ( html , /退款 ¥10\.00<\/span><span>总收款 ¥600\.03/ );
2026-10-23 09:49:36 +08: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 , /<img src=x onerror="alert\(1\)">/ ); assert . match ( html , /<script>alert\(2\)<\/script>/ ); assert . match ( html , /纸单 "<01>/ ); 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 , 2 );
assert . match ( table ( html , '助理收款逐笔明细' ), /所选范围没有助理收款记录/ ); assert . match ( table ( 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 };
2026-10-24 16:09:45 +08:00
h . context . __response = response ; await h . run ( 'renderReport()' ); assert . match ( h . content . innerHTML , /助理净收款<\/h2><div class="report-recipient-total">¥-1\.00/ ); assert . match ( h . content . innerHTML , /退款 ¥1\.00<\/span><span>总收款 ¥0\.00/ ); assert . match ( table ( h . content . innerHTML , '助理收款逐笔明细' ), /所选范围没有助理收款记录/ ); assert . match ( table ( h . content . innerHTML , '助理退款逐笔明细' ), /客户-only-refund/ );
2026-10-23 09:49:36 +08:00
});
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 , /账面库存/ );
});