2026-10-25 14:19:24 +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' ),{ randomUUID } = require ( 'node:crypto' );
const Calc = require ( '../public/calculations' ), Fees = require ( '../public/fee-estimates' ), Templates = require ( '../public/order-templates' );
const D = '2026-10-25' , members = [ 'owner' , 'assistant' , 'assistant2' ];
function pair ( a = 'owner' , b = 'assistant' , extra = {}){ return { id : a + ':' + b , members : [ a , b ], net : 10000 , obligationNet : 15000 , receivedForNet : 20000 , advancedNet :- 5000 , offset : 5000 , transferred : 5000 , due : 10000 , fromMember : a , toMember : b , direction : 'transfer' , period : { obligationNet : 15000 , transferred : 5000 }, entries : [],... extra };}
function report ( self = 'owner' ){ return { from : D , to : D , revision : 'revision-1' , members : members . map ( id =>({ id , name : id })), balances : [], pairs : [ pair ( 'owner' , 'assistant' ), pair ( 'owner' , 'assistant2' ), pair ( 'assistant' , 'assistant2' )]. filter ( row => self === 'owner' || row . members . includes ( self )), transfers : []};}
function harness ( member = 'owner' ){
const nodes = new Map (), saved = new Map (), posts = [], handlers = {};
const user = { id : 'synthetic-' + member , member , name : member === 'owner' ? '麦麦' : member === 'assistant' ? '助理1' : '助理2' , role : member === 'owner' ? 'owner' : 'assistant' };
const context = vm . createContext ({ console , URLSearchParams , LedgerCalc : Calc , FeeEstimates : Fees , OrderTemplates : Templates , crypto : { randomUUID }, setInterval (){}, setTimeout (){}, clearTimeout (){}, window : { scrollTo (){}}, document : { querySelector : q => nodes . get ( q ) || null , querySelectorAll : ()=>[], addEventListener : ( type , fn )=>( handlers [ type ] ??= []). push ( fn )}, FormData : class { constructor ( form ){ return Object . entries ( form . values || {});}}, localStorage : { getItem : k => saved . get ( k ) || null , setItem : ( k , v )=> saved . set ( k , String ( v )), removeItem : k => saved . delete ( k )}, sessionStorage : { getItem (){ return null ;}, setItem (){}}, __user : user , __posts : posts });
const run = code => vm . runInContext ( code , context ), json = code => JSON . parse ( JSON . stringify ( run ( code )));
for ( const file of [ 'material-pools-ui.js' , 'daily-funds-ui.js' , 'cost-funding-ui.js' , 'team-funds-ui.js' , 'app.js' ]) run ( fs . readFileSync ( path . join ( __dirname , '../public' , file ), 'utf8' ). replace ( /\ninit\(\);\s*$/ , '' ));
run ( `session={user:__user,mode:'demo'};state={user:__user,mode:'demo',members:[{member:'owner'},{member:'assistant'},{member:'assistant2'}],today:' ${ D } ',accounts:['麦麦信用卡','助理信用卡','助理2信用卡'],pockets:['现货','金料']};toast=function(){};showPending=function(){};api=async function(url,data,key){__posts.push({url,data,key});return {saved:true};};` );
return { run , json , context , nodes , saved , posts , handlers , user };
}
test ( '三方分项付款人与成本汇总支持助理2,缺失或伪造付款人仍拒绝' ,()=>{
assert . deepEqual ( Calc . normalizeCostPayers ({ material : 'assistant2' , labor : 'assistant' }),{ material : 'assistant2' , labor : 'assistant' });
const order = { status : 'delivered' , lines : [{ name : '测试款' , payer : 'assistant2' , costParts : { material : 5000 , labor : 500 , accessories : 200 , other : 0 }, costPayers : { material : 'assistant2' , labor : 'owner' }}], expenses : [{ id : 'fee' , date : D , note : '快递' , payer : 'assistant2' , amount : 600 }], pendingFees : []};
const before = JSON . stringify ( order ), summary = Calc . orderCosts ( order ); assert . equal ( summary . byPayer . assistant2 . total , 5800 ); assert . equal ( summary . byPayer . owner . total , 500 ); assert . equal ( summary . total . total , 6300 ); assert . equal ( JSON . stringify ( order ), before );
assert . throws (()=> Calc . costPayers ({ material : 'assistant2' , labor : 'unknown' }), /付款人/ );
});
test ( '日购料与锁价的三方分摊逐分守恒,第三人分项不丢失' ,()=>{
const base = { name : '合成黄金' , payer : 'owner' , quantity : 1000 , costParts : { material : 101 , labor : 0 , accessories : 0 , other : 0 }, costPayers : { material : 'owner' , labor : 'assistant2' }};
const pooled = {... base , costMaterial : { mode : 'pool' , poolId : D }, materialPool : { averageRate : 101 , allocations : [{ payer : 'owner' , amount : 34 },{ payer : 'assistant' , amount : 34 },{ payer : 'assistant2' , amount : 33 }]}};
let result = Calc . orderCosts ({ status : 'delivered' , lines : [ pooled ]}); assert . equal ( result . byPayer . assistant2 . goods , 33 ); assert . equal ( result . total . goods , 101 );
const locked = {... base , materialAllocations : [{ source : 'original' , payer : 'assistant2' , amount : 100 , quantity : 999 , rate : 100 },{ source : 'extra' , payer : 'assistant' , amount : 1 , quantity : 1 , rate : 1000 }]}; result = Calc . orderCosts ({ status : 'delivered' , lines : [ locked ]}); assert . equal ( result . byPayer . assistant2 . goods , 100 );
assert . throws (()=> Calc . orderCosts ({ status : 'delivered' , lines : [{... pooled , materialPool : { allocations : [{ payer : 'assistant2' , amount : 100 }]}}]}), /分项成本/ );
});
test ( '助理2开单归属、默认收款与快递跟随本人,包装仍默认麦麦' ,()=>{
const h = harness ( 'assistant2' ); assert . equal ( h . run ( 'currentMember()' ), 'assistant2' ); assert . equal ( h . run ( 'teamDefaultPayer()' ), 'assistant2' );
2026-11-03 01:15:41 +08:00
const account = h . run ( 'accountFields()' ); assert . match ( account , /<option value="助理2" selected>小昊/ ); assert . match ( account , /<option value="助理" >娜娜/ ); assert . match ( h . run ( 'orderMemberField()' ), /name="member" value="assistant2"/ );
2026-10-25 14:19:24 +08:00
const defaults = Fees . sync ([],[{ charges : [{ id : randomUUID (), name : '包装' },{ id : randomUUID (), name : '证书' }]}],{ addShipping : true , defaultPayer : 'assistant2' }); assert . equal ( defaults . find ( row => row . key === 'shipping' ). payer , 'assistant2' ); assert . equal ( defaults . find ( row => row . note === '包装' ). payer , 'owner' );
2026-11-03 01:15:41 +08:00
assert . equal ( defaults . find ( row => row . note === '证书' ). payer , 'assistant2' ); assert . deepEqual ( h . json ( 'peopleParts()' ),[[ 'assistant2' , '小昊人数' ]]);
2026-10-25 14:19:24 +08:00
});
test ( '老板代录明确选择三人,归属与开单人文本分别保存,助理不能选择其他归属' ,()=>{
2026-11-03 01:15:41 +08:00
const owner = harness (); const html = owner . run ( 'orderMemberField("assistant2")' ); assert . match ( html , /<select name="member">/ ); for ( const label of [ '麦麦' , '娜娜' , '小昊' ]) assert . ok ( html . includes ( '>' + label + '</option>' ));
const assistant = harness ( 'assistant' ); assert . doesNotMatch ( assistant . run ( 'orderMemberField()' ), /<select/ ); assert . match ( assistant . run ( 'orderMemberField()' ), /娜娜/ );
assert . deepEqual ( owner . json ( 'teamMemberOptions()' ),[[ 'owner' , '麦麦' ],[ 'assistant' , '娜娜' ],[ 'assistant2' , '小昊' ]]);
2026-10-25 14:19:24 +08:00
});
test ( '购料只录实际付款,旧草稿分配忽略并保留五项原值,不再校验承担合计' ,()=>{
const h = harness ( 'assistant2' ), input = { date : D , grams : '1' , total : '100' , payer : 'assistant2' , note : '合成旧草稿' , allocations : [{ member : 'owner' , amount : '99' }], allocationManual : true }; h . saved . set ( 'mm-material-purchase-' + h . user . id , JSON . stringify ( input )); h . context . __input = input ;
const html = h . run ( 'materialPurchaseForm()' ); assert . doesNotMatch ( html , /这笔料款由谁承担|allocation_|material-allocations|全额承担/ ); for ( const [ name , value ] of Object . entries ( input ). slice ( 0 , 5 )) assert . ok ( html . includes ( name === 'payer' ? '<option value="assistant2" selected>' : `name=" ${ name } " value=" ${ value } "` )); assert . match ( html , /付款当天记支出/ ); assert . match ( html , /未用完的料结转/ ); assert . match ( html , /实际耗用自动计算料费/ ); assert . match ( html , /不再重复记现金支出/ );
const expected = { date : D , grams : '1' , total : '100' , payer : 'assistant2' , note : '合成旧草稿' }; assert . deepEqual ( h . json ( 'validateMaterialPurchase(__input)' ), expected ); assert . deepEqual ( input . allocations ,[{ member : 'owner' , amount : '99' }]);
h . context . __form = { elements : Object . fromEntries ( Object . entries ( expected ). map (([ name , value ])=>[ name ,{ value }])), querySelector (){ throw new Error ( '不应读取已删除的承担输入' );}}; h . nodes . set ( '#material-purchase-form' , h . context . __form ); assert . deepEqual ( h . json ( 'materialPurchaseData(__form)' ), expected ); h . run ( 'rememberMaterialPurchaseDraft()' ); assert . deepEqual ( JSON . parse ( h . saved . get ( 'mm-material-purchase-' + h . user . id )), expected );
});
test ( '旧购料响应只显示实际付款人,编辑不依赖已移除的承担DOM' , async ()=>{
const h = harness ( 'assistant2' ), id = randomUUID (), purchase = { id , date : D , mg : 1000 , amount : 10000 , actualpayer : 'assistant2' , revision : 2 , note : '合成历史购料' , allocations : [{ member : 'owner' , amount : 10000 }]}, dialog = { open : false , innerHTML : '' , showModal (){ this . open = true ;}}; h . context . __purchase = purchase ; h . nodes . set ( '#material-purchase-dialog' , dialog ); h . run ( 'api=async function(){return {purchase:__purchase};};' ); await h . run ( `showMaterialPurchaseChange(' ${ id } ')` );
2026-11-03 01:15:41 +08:00
assert . match ( dialog . innerHTML , /id="material-purchase-edit-form"/ ); assert . match ( dialog . innerHTML , /<option value="assistant2" selected>小昊/ ); assert . doesNotMatch ( dialog . innerHTML , /allocation_|material-allocations|承担/ ); h . context . __pool = { date : D , purchases : [ purchase ], usages : []}; const html = h . run ( 'materialPoolDetailHTML(__pool)' ); assert . match ( html , /<td>小昊<\/td>/ ); assert . doesNotMatch ( html , /承担分配|承担 ¥|allocation_/ );
2026-10-25 14:19:24 +08:00
});
test ( '购料新增与编辑无需承担,响应丢失后原操作可安全重试' , async ()=>{
const h = harness ( 'assistant2' ), input = { date : D , grams : '1' , total : '100' , payer : 'assistant2' , note : '' }, id = randomUUID (), form = { elements : Object . fromEntries ( Object . entries ( input ). map (([ name , value ])=>[ name ,{ value }])), dataset : { id , revision : '2' , kind : 'edit' }, querySelector (){ throw new Error ( '不应读取已删除的承担输入' );}}; h . context . __form = form ; h . nodes . set ( '#material-purchase-error' ,{ innerHTML : '' }); h . nodes . set ( '#material-purchase-change-error' ,{ innerHTML : '' }); h . run ( 'finishMaterialPurchaseSave=async function(){return {saved:true};};finishMaterialPurchaseChange=async function(){return {saved:true};};api=async function(url,data,key){__posts.push({url,data,key});throw new Error("响应丢失");};' );
await assert . rejects ( h . run ( 'submitMaterialPurchase(__form)' ), /提交结果待确认/ ); const job = JSON . parse ( h . saved . get ( 'mm-pending-' + h . user . id )); assert . deepEqual ( job . data , input ); assert . equal ( job . url , '/api/material-purchases' ); h . context . __job = job ; h . run ( 'api=async function(url,data,key){__posts.push({url,data,key});return {saved:true};};' ); await h . run ( 'mutate(__job.url,__job.data,__job)' ); assert . equal ( h . posts [ 0 ]. key , h . posts [ 1 ]. key ); assert . deepEqual ( JSON . parse ( JSON . stringify ( h . posts [ 0 ]. data )), JSON . parse ( JSON . stringify ( h . posts [ 1 ]. data ))); assert . equal ( h . saved . size , 0 );
h . context . __purchase = { id , revision : 2 }; h . run ( 'materialPurchaseEntry={purchase:__purchase,kind:"edit",user:state.user.id};' ); await h . run ( 'submitMaterialPurchaseChange(__form)' ); assert . equal ( h . posts [ 2 ]. url , '/api/material-purchases/' + id + '/edit' ); assert . deepEqual ( JSON . parse ( JSON . stringify ( h . posts [ 2 ]. data )),{... input , revision : 2 });
});
test ( '团队往来展示两人方向、已转与剩余,历史利润交款不混入新债务' ,()=>{
const h = harness (); h . context . __report = report (); assert . equal ( h . json ( 'validateTeamFunds(__report)' ). pairs . length , 3 ); h . context . __pair = pair ( 'assistant' , 'assistant2' ,{ net :- 2500 , due : 2500 , fromMember : 'assistant2' , toMember : 'assistant' , obligationNet : 2500 , transferred : 5000 }); const html = h . run ( 'teamPairHTML(__pair)' );
2026-11-03 01:15:41 +08:00
assert . match ( html , /小昊 → 娜娜 ¥25.00/ ); for ( const text of [ '代收' , '垫付' , '抵扣' , '实际已转' , '剩余待转' , '利润留在店里' ]) assert . ok ( html . includes ( text )); assert . doesNotMatch ( html , /利润月底交|麦麦全转助理/ );
2026-10-25 14:19:24 +08:00
const assistant = harness ( 'assistant2' ); assistant . context . __report = report ( 'assistant2' ); assert . doesNotThrow (()=> assistant . run ( 'validateTeamFunds(__report)' )); assistant . context . __report . pairs . push ( pair ( 'owner' , 'assistant' )); assert . throws (()=> assistant . run ( 'validateTeamFunds(__report)' ), /其他成员/ );
});
test ( '转账未确认不提交,丢失响应保留原操作号,恢复不重复登记' , async ()=>{
const h = harness ( 'assistant2' ); h . context . __report = report ( 'assistant2' ); h . run ( `teamFundsReport=__report;teamTransferPair={pair:__report.pairs[0],revision:__report.revision,user:state.user.id,date:' ${ D } '};finishTeamTransferSave=async function(){return {saved:true};};` );
const form = { dataset : {}, values : { date : D , fromMember : 'assistant2' , toMember : 'owner' , amount : '50' , note : '合成转账' }}; h . context . __form = form ; h . nodes . set ( '#team-transfer-error' ,{ innerHTML : '' });
await assert . rejects ( h . run ( 'submitTeamTransfer(__form)' ), /勾选确认/ ); assert . equal ( h . posts . length , 0 ); form . values . verified = 'on' ; h . run ( `api=async function(url,data,key){__posts.push({url,data,key});throw new Error('响应丢失');};` ); await assert . rejects ( h . run ( 'submitTeamTransfer(__form)' ), /提交结果待确认/ );
const job = JSON . parse ( h . saved . get ( 'mm-pending-' + h . user . id )); assert . equal ( job . url , '/api/team-funds/transfers' ); assert . equal ( job . data . verified , true ); assert . equal ( h . posts . length , 1 );
h . run ( `api=async function(url,data,key){__posts.push({url,data,key});return {saved:true};};` ); h . context . __job = job ; await h . run ( 'mutate(__job.url,__job.data,__job)' ); assert . equal ( h . posts . length , 2 ); assert . equal ( h . posts [ 0 ]. key , h . posts [ 1 ]. key ); assert . deepEqual ( JSON . parse ( JSON . stringify ( h . posts [ 0 ]. data )), JSON . parse ( JSON . stringify ( h . posts [ 1 ]. data ))); assert . equal ( h . saved . size , 0 );
});
2026-10-25 17:50:26 +08:00
test ( '工费与附加费用不再显示报销抵用,加载开单也不读取报销来源' ,()=>{
const h = harness ( 'assistant2' );
assert . equal ( h . run ( 'reimbursementFundingHTML("labor")' ), '' ); assert . equal ( h . run ( 'reimbursementFundingHTML("fee")' ), '' );
for ( const html of [ h . run ( 'costFields()' ), h . run ( 'feeRowHTML({key:"shipping",note:"快递",amount:"8",payer:"assistant2"})' )]) assert . doesNotMatch ( html , /cost-funding|使用已批准报销款|成本付款来源|fundingAmount|刷新已报销款/ );
h . nodes . set ( '#order-form' ,{}); h . run ( 'loadReimbursementFundingOptions(true)' ); assert . equal ( h . posts . length , 0 );
});
test ( '历史报销引用以隐藏资料保留原金额和版本,付款人继续锁定且坏资料不静默丢失' ,()=>{
const h = harness ( 'assistant2' ), reference = { reimbursementId : randomUUID (), itemId : randomUUID (), amount : '100.01' , revision : 3 }, payer = { value : 'assistant2' , disabled : false }; h . context . __reference = reference ;
for ( const component of [ 'labor' , 'fee' ]){
h . context . __component = component ; const html = h . run ( 'reimbursementFundingHTML(__component,__reference)' ); assert . match ( html , /<input type="hidden" class="cost-funding"/ ); assert . doesNotMatch ( html , /<details|<select|fundingAmount|报销款/ );
const encoded = html . match ( /data-reference="([^"]*)"/ )[ 1 ]. replace ( /"/g , '"' ). replace ( /&/g , '&' );
const container = { dataset : { component , reference : encoded }, closest : ()=>({ querySelector : ()=> payer })}; h . context . __container = container ;
assert . deepEqual ( h . json ( 'readReimbursementFunding(__container)' ), reference );
h . context . document . querySelectorAll = ()=>[ container ]; h . run ( 'syncReimbursementFundingControls()' ); assert . equal ( payer . value , 'assistant2' ); assert . equal ( payer . disabled , true );
container . dataset . reference = 'broken' ; assert . throws (()=> h . run ( 'readReimbursementFunding(__container)' ), /资料缺失/ );
}
2026-10-25 14:19:24 +08:00
});
2026-11-03 01:15:41 +08:00
test ( '小昊人数视图只展示本人,老板保留两项,不把未提供当0' ,()=>{
const h = harness ( 'assistant2' ); h . context . __summary = { from : D , date : D , assistant2 : { total : 0 , endTotal : 0 , baselineTotal : null , netChange : null , netChangeReason : 'missing-previous' , recordedDays : 1 , baselineDate : null }}; const html = h . run ( 'peopleCountHTML(__summary)' ); assert . match ( html , /小昊当日总人数/ ); assert . match ( html , /0 人(已记录)/ ); assert . match ( html , /暂无上次记录/ ); assert . doesNotMatch ( html , /娜娜当日总人数/ );
const owner = harness (); assert . deepEqual ( owner . json ( 'peopleParts()' ),[[ 'assistant1' , '娜娜人数' ],[ 'assistant2' , '小昊人数' ]]);
2026-10-25 14:19:24 +08:00
});
test ( '三人模板保留助理2付款人与收款账户,不继承已批准抵用身份' ,()=>{
const id = randomUUID (), preset = Templates . fromDraft ({ payment_account : '助理2微信' , credit_card_fee_payer : 'assistant2' , lines : [{ name : '测试款' , unit : 'g' , quantity : '1' , payer : 'assistant2' , pricingMode : 'manual' , baseSale : '100' , costParts : { material : '10' , labor : '5' , accessories : '0' , other : '0' }, costPayers : { material : 'assistant2' , labor : 'assistant2' }, costFundings : { labor : { reimbursementId : id , itemId : id , amount : '5' , revision : 1 }}}], fee_items : []}); assert . equal ( preset . payment_account , '助理2微信' ); assert . equal ( preset . lines [ 0 ]. costPayers . labor , 'assistant2' ); assert . equal ( preset . lines [ 0 ]. costFundings , undefined );
});
test ( '助理设置页允许后端隐藏备份对象,仍可切换身份并查看成员入口' ,()=>{
2026-11-03 01:15:41 +08:00
const h = harness ( 'assistant2' ), main = { innerHTML : '' , insertAdjacentHTML ( position , html ){ this . innerHTML = html + this . innerHTML ;}}; h . nodes . set ( '#main' , main ); h . run ( `state={...state,printing:{store:'合成店名',subtitle:'销售单',contact:'',rows:3,offsetX:0,offsetY:0,contentTop:5,rowHeight:8},orders:[],backup:null,sync:{enabled:false}};syncPrintSettingsPreview=function(){};renderSettings();` ); assert . match ( main . innerHTML , /三人功能预览·虚构数据/ ); assert . match ( main . innerHTML , /切换娜娜/ ); assert . match ( main . innerHTML , /本人只查看自己的订单/ );
});
test ( '娜娜和小昊统一显示,姓名与账户转换不更改选项值、提交账户或历史开单人' ,()=>{
const h = harness ( 'assistant2' ); assert . deepEqual ( h . json ( 'teamMemberOptions()' ),[[ 'owner' , '麦麦' ],[ 'assistant' , '娜娜' ],[ 'assistant2' , '小昊' ]]); assert . equal ( h . run ( 'accountDisplayName("助理微信")' ), '娜娜微信' ); assert . equal ( h . run ( 'accountDisplayName("助理2支付宝")' ), '小昊支付宝' ); assert . equal ( h . run ( 'accountDisplayName("历史助理2")' ), '历史助理2' );
const options = h . run ( 'opts(["助理微信","助理2支付宝"],"助理2支付宝")' ); assert . match ( options , /<option value="助理微信" >娜娜微信/ ); assert . match ( options , /<option value="助理2支付宝" selected>小昊支付宝/ ); h . context . __form = { querySelector ( selector ){ return selector . includes ( 'payment_recipient' ) ? { value : '助理2' } : selector . includes ( 'payment_method' ) ? { value : '支付宝' } : null ;}}; assert . equal ( h . run ( 'readPaymentAccount(__form)' ), '助理2支付宝' ); assert . match ( h . run ( 'field("开单人","salesperson","历史开单人助理2")' ), /value="历史开单人助理2"/ );
h . nodes . set ( '#shell' ,{ hidden : false }); h . nodes . set ( '#login' ,{ innerHTML : '' }); h . run ( "session.mode='trial';session.setup=false;login();" ); const login = h . nodes . get ( '#login' ). innerHTML ; assert . match ( login , /<option value="助理1" >娜娜/ ); assert . match ( login , /<option value="助理2" >小昊/ ); assert . doesNotMatch ( login , />助理[12]<\/option>/ );
2026-10-25 14:19:24 +08:00
});