'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),vm=require('node:vm');
const {randomUUID}=require('node:crypto'),Calc=require('../public/calculations');
const D='2026-10-22',TODAY='2026-10-23',RID='11111111-1111-4111-8111-111111111111';
const clone=value=>JSON.parse(JSON.stringify(value));
const sixItems=()=>[80,90,173,63,80,10].map((value,index)=>({name:'报销项目'+(index+1),amount:value*100}));
function claim(extra={}){return {id:RID,date:D,items:sixItems(),total:49600,note:'合成报销',status:'pending',revision:1,requester_id:'assistant',requester_name:'助理',reviewer_id:null,reviewer_name:null,reviewed:null,review_note:'',created:D+'T01:00:00Z',updated:D+'T01:00:00Z',canEdit:true,canApprove:true,...extra};}
function data(extra={}){
const date=extra.date||D,from=extra.from||date,sources={revision:'source-v1',total:20000,items:[{id:'payment-one',sourceType:'materialPurchase',sourceId:'one',date,amount:20000,payer:'owner',name:'未售现货实际采购',note:'合成付款参考'}]},ownerReceipts={receipt:110000,refund:10000,net:100000};
const result={date,from,readOnly:from!==date,hasRecords:false,pendingCount:0,ownerReceipts,reimbursements:[],approvedReimbursements:0,actualOutlay:null,confirmation:null,sources,ready:false,transferAmount:null,direction:null,missingDates:[date],staleDates:[],days:[],transfersNotDeducted:true,...extra};
if(result.ready){result.actualOutlay=result.actualOutlay??80000;result.confirmation=result.confirmation||{date,amount:result.actualOutlay,revision:1,sourceRevision:result.sources.revision,note:'已核对全部支出',actor:'麦麦',created:D,updated:D,stale:false};result.transferAmount=result.ownerReceipts.net-result.actualOutlay+result.approvedReimbursements;result.direction=result.transferAmount>0?'toAssistant':result.transferAmount<0?'toOwner':'none';result.missingDates=[];}
if(!extra.days)result.days=[{date,ownerReceipts:result.ownerReceipts,approvedReimbursements:result.approvedReimbursements,actualOutlay:result.actualOutlay,confirmation:result.confirmation,sources:result.sources,ready:result.ready,transferAmount:result.transferAmount,direction:result.direction,hasActivity:true}];
return result;
}
function node(extra={}){return {innerHTML:'',textContent:'',disabled:false,hidden:false,dataset:{},checked:false,value:'',classList:{toggle(){}},setAttribute(){},scrollIntoView(){},querySelector(){return null;},querySelectorAll(){return [];},insertAdjacentHTML(position,html){this.innerHTML+=html;},...extra};}
function reportForFunds(funds){
const person=(recipient,name)=>({recipient,name,receipt:recipient==='owner'?funds.ownerReceipts.receipt:0,refund:recipient==='owner'?funds.ownerReceipts.refund:0,net:recipient==='owner'?funds.ownerReceipts.net:0,items:recipient==='owner'?['receipt','refund'].filter(kind=>funds.ownerReceipts[kind]).map(kind=>({id:kind,date:funds.date,order_date:funds.date,order_id:'synthetic-order',kind,amount:funds.ownerReceipts[kind],account:'麦麦微信'})):[]});
const cost=name=>({name,goods:0,paidFees:0,total:0,missingCount:0,pendingCount:0,items:[]});
const recipientReceipts={owner:person('owner','麦麦'),assistant:person('assistant','助理')},member='owner',items=recipientReceipts.owner.items;
const owned={member,name:member==='owner'?'麦麦':'助理',...funds.ownerReceipts,items,accounts:items.length?[{account:'麦麦微信',recipient:'owner',channel:'wechat',...funds.ownerReceipts,entryCount:items.length}]:[]};
const ownershipReceipts={owner:owned,assistant:{member:'assistant',name:'助理',receipt:0,refund:0,net:0,accounts:[],items:[]}};
const ownershipBusiness=Object.fromEntries(Object.entries(ownershipReceipts).map(([member,person])=>[member,{member,name:person.name,basis:'orderDate',from:funds.from,date:funds.date,sales:0,netReceipts:person.net,totalCost:0,knownTotalCost:0,selfCost:0,knownSelfCost:0,otherCost:0,knownOtherCost:0,profit:0,knownProfit:0,incomplete:false,missingCostCount:0,pendingCostCount:0,unknownProfitCount:0,draftCount:0,recordCount:0,orderCount:0,afterSaleCount:0,hasActivity:person.items.length>0,costByPayer:Object.fromEntries(['owner','assistant','assistant2'].map(key=>[key,{member:key,name:key,totalCost:0,knownTotalCost:0,missingCount:0,pendingCount:0}])),difference:{amount:person.net,reconciled:person.net===0,reasons:[]},equation:{basis:'sales',revenue:0,totalCost:0,profit:0,complete:true},settlement:{available:false,basis:'cumulative-through-date',from:funds.from,date:funds.date,dueOut:null,dueIn:null,partial:false,pendingCount:0,legacyCount:0,notice:'旧双人结算请核对原单。',counterparts:[]}}]));
for(const b of Object.values(ownershipBusiness))b.poolMaterial={mg:0,amount:0,knownAmount:0,missingCount:0,hasPriceLocks:false,byPayer:Object.fromEntries(['owner','assistant','assistant2'].map(key=>[key,{amount:0,knownAmount:0}])),days:[],otherCosts:{amount:0,knownAmount:0}};
for(const b of Object.values(ownershipBusiness))b.ownerAdvances={basis:'orderDate',from:funds.from,date:funds.date,days:[]};
return {basis:'orderDate',date:funds.date,from:funds.from,summary:{orderCount:0,completedCount:0,returnedCount:0,cancelledCount:0,draftCount:0,afterSaleCount:0,sale:0,profit:0,totalCost:0,missingCosts:0},orderRows:[],accounts:[],receiptsByOrderDate:funds.ownerReceipts,recipientReceipts,ownershipReceipts,ownershipBusiness,payerCosts:{owner:cost('麦麦'),assistant:cost('助理')},goods:0,expense:0,inventory:[],unsettled:[],warnings:[],customerBalance:0,settlementDue:0,close:null,dailyFunds:funds};
}
function attrs(tag){const result={};for(const match of tag.matchAll(/([\w-]+)="([^"]*)"/g))result[match[1]]=match[2].replace(/"/g,'"').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');return result;}
function deferred(){let resolve,reject;const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});return {promise,resolve,reject};}
function harness(initial=data(),role='owner'){
const nodes=new Map(),saved=new Map(),calls=[],toasts=[],handlers={},responses=new Map([[initial.date,clone(initial)]]),postResults=new Map();let forms=[];
const user={id:role,name:role==='owner'?'麦麦':'助理',role};
for(const key of ['#main','#daily-funds-content','#report-content','#daily-reimbursements-list','#pending','#toast','#reimbursement-edit-total'])nodes.set(key,node());
nodes.set('#daily-reimbursements-dialog',node({open:false,showModal(){this.open=true;},close(){this.open=false;}}));
function parseForms(html){
for(const old of forms)nodes.delete('#'+old.id);forms=[];
for(const match of html.matchAll(/