Files

236 lines
34 KiB
JavaScript

'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
const {Ledger}=require('../ledger');
const D='2026-09-30',D2='2026-10-01',D3='2026-10-02';
const line=(sale='100',cost='60',payer='owner')=>({name:'合成普通商品',unit:'件',quantity:'1',pocket:'',payer,sale,cost});
function fixture(t,{team=true}={}){
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);
}
if(team)ledger.enableTeamMode();
const run=(input,fn)=>ledger.scope(actors.owner,()=>ledger.transact(randomUUID(),actors.owner,input,fn));
const save=(member='assistant',extra={},issued=true)=>{
const input={date:D,member,customer:member+'私有客户',salesperson:'合成开单人',payment_account:'助理微信',rounding_mode:'cent',fee_items:[],lines:[line()],...extra};
return run(input,()=>issued?ledger.issueOrder(input,actors.owner):ledger.saveOrder(input,actors.owner)).id;
};
const action=(id,kind,extra={})=>{const input={date:D,...extra};return run({id,kind,input},()=>ledger.action(id,kind,input,actors.owner));};
const after=(member='assistant',extra={})=>{const input={date:D,member,customer:member+'售后客户',project:'合成售后',amount:'12.34',payer:'owner',...extra};return run(input,()=>ledger.saveAfterSale(input,actors.owner)).after_sale_id;};
const lock=(extra={})=>{
const input={date:D,member:'assistant',customer:'合成锁价客户',salesperson:'合成开单人',line:{name:'足金合成挂件',quantity:'2.000',goldPrice:'1000',laborRate:'20',laborMode:'gram'},material:{rate:'900',payer:'owner',verified:true},payment:{amount:'1000',account:'麦麦微信',verified:true},...extra};
return run(input,()=>ledger.createPriceLock(input,actors.owner)).id;
};
const deliver=id=>{
const input={date:D2,revision:ledger.priceLockDetail(id).revision,verified:true,line:{quantity:'2.200',laborRate:'20',laborMode:'gram',payer:'assistant',costParts:{labor:'20',accessories:'0',other:'0'}},inventory:{pocket:'现货',original:'receive',extra:'receive'},extraMaterial:{rate:'950',payer:'owner',verified:true},fee_items:[],settlement:{amount:'1244',account:'助理支付宝',verified:true}};
return run({id,input},()=>ledger.deliverPriceLock(id,input,actors.owner)).order_id;
};
const purchase=(extra={})=>{const input={date:D,grams:'10',total:'9000',payer:'owner',note:'合成采购',...extra};return run(input,()=>ledger.createMaterialPurchase(input,actors.owner));};
const transfer=(date,fromMember,toMember,amount)=>{const input={date,fromMember,toMember,amount,verified:true,revision:ledger.teamFunds({date},actors.owner).revision};return run(input,()=>ledger.transferTeamFunds(input,actors.owner));};
const report=(date=D,from=date,member='owner',filter)=>ledger.asActor(actors[member]).reportFor({date,from,basis:'orderDate',...(filter?{member:filter}:{})},actors[member]);
const close=(date=D)=>run({date},()=>ledger.closeDay(date,actors.owner,'orderDate'));
const voidOrder=id=>{
const input={revision:ledger.detail(id).revision,reason:'合成录错作废'},request=run(input,()=>ledger.requestOrderCancellation(id,input,actors.owner));
const decision={revision:request.request.order_revision,verified:true,note:'合成核实'};return run(decision,()=>ledger.approveOrderCancellation(request.requestId,decision,actors.owner));
};
return {ledger,actors,run,save,action,after,lock,deliver,purchase,transfer,report,close,voidOrder};
}
const contents=ledger=>JSON.stringify(ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,ledger.rows('SELECT * FROM "'+name+'"')]));
function check(report){
assert.deepEqual(Object.keys(report.ownershipBusiness),Object.keys(report.ownershipReceipts));
for(const group of Object.values(report.ownershipBusiness)){
assert.equal(group.netReceipts,report.ownershipReceipts[group.member].net);assert.equal(group.knownSelfCost+group.knownOtherCost,group.knownTotalCost);
assert.equal(Object.values(group.costByPayer).reduce((sum,row)=>sum+row.knownTotalCost,0),group.knownTotalCost);
if(group.totalCost!==null){assert.equal(group.totalCost,group.knownTotalCost);assert.equal(group.selfCost+group.otherCost,group.totalCost);}
if(group.profit!==null){assert.notEqual(group.totalCost,null);assert.equal(group.sales-group.totalCost,group.profit);}
assert.equal(group.equation.revenue-group.sales,group.equation.basis==='netReceipts'?group.netReceipts-group.sales:0);
assert.equal(group.currentAccount.from,report.from);assert.equal(group.currentAccount.date,report.date);
assert.equal(group.currentAccount.days.reduce((sum,day)=>sum+day.knownProfit,0),group.knownProfit);
for(const day of group.currentAccount.days){
assert.ok(day.date>=report.from&&day.date<=report.date);assert.equal(day.knownAmount,day.knownMaterialCost+day.knownOtherCost+day.knownProfit-day.ownerNetReceipts);
assert.equal(day.amount,day.incomplete?null:day.knownAmount);
}
for(const pair of group.settlement.counterparts){assert.equal(pair.openingDue+pair.periodNew-pair.periodTransferred,pair.closingDue);assert.equal(pair.dueOut,Math.max(0,pair.closingDue));assert.equal(pair.dueIn,Math.max(0,-pair.closingDue));assert.notEqual(pair.member,group.member);}
if(group.settlement.available){assert.equal(group.settlement.dueOut,group.settlement.counterparts.reduce((sum,row)=>sum+row.dueOut,0));assert.equal(group.settlement.dueIn,group.settlement.counterparts.reduce((sum,row)=>sum+row.dueIn,0));}
}
const groups=Object.values(report.ownershipBusiness);assert.equal(groups.reduce((sum,row)=>sum+row.sales,0),report.sales);assert.equal(groups.reduce((sum,row)=>sum+row.knownTotalCost,0),report.totalCost);assert.equal(groups.reduce((sum,row)=>sum+row.knownProfit,0),report.knownProfit);
return report;
}
function demo(f,date=D){
return [['1000','500','助理微信'],['300','100','助理支付宝'],['200','80','麦麦支付宝']].map(([sale,cost,payment_account])=>f.save('assistant',{date,payment_account,lines:[line(sale,cost)]}));
}
test('普通所属订单净收1500减原成本680等于利润820,代收抵扣后应转480,自己付费用单独归集',t=>{
const f=fixture(t),[id]=demo(f),report=check(f.report()),own=report.ownershipBusiness.assistant;
assert.equal(own.sales,150000);assert.equal(own.netReceipts,150000);assert.equal(own.totalCost,68000);assert.equal(own.selfCost,0);assert.equal(own.otherCost,68000);assert.equal(own.profit,82000);assert.equal(own.equation.basis,'netReceipts');assert.equal(own.equation.complete,true);
assert.equal(own.settlement.dueOut,48000);assert.equal(own.settlement.dueIn,0);assert.equal(own.settlement.counterparts.find(row=>row.member==='owner').periodNew,48000);assert.notEqual(own.settlement.dueOut,own.otherCost);
f.action(id,'expense',{amount:'20',payer:'assistant',note:'合成自己付运费'});const updated=check(f.report()).ownershipBusiness.assistant;
assert.equal(updated.totalCost,70000);assert.equal(updated.selfCost,2000);assert.equal(updated.otherCost,68000);assert.equal(updated.profit,80000);assert.equal(updated.settlement.dueOut,48000);assert.equal(updated.costByPayer.assistant.knownTotalCost,2000);
});
test('逐人累计待转复用原账:期初1800+本期480-已转200=2080,对方应转入不跨人互抵',t=>{
const f=fixture(t);f.save('assistant',{lines:[line('2000','1800')]});demo(f,D2);f.transfer(D2,'assistant','owner','200');
f.save('assistant',{date:D2,payment_account:'助理2微信',lines:[line('50','0','assistant')]});
const report=check(f.report(D2)),own=report.ownershipBusiness.assistant,pair=own.settlement.counterparts.find(row=>row.member==='owner'),third=own.settlement.counterparts.find(row=>row.member==='assistant2');
assert.deepEqual([pair.openingDue,pair.periodNew,pair.periodTransferred,pair.closingDue],[180000,48000,20000,208000]);assert.equal(pair.dueOut,208000);assert.equal(third.dueIn,5000);assert.equal(third.periodNew,-5000);assert.equal(own.settlement.dueOut,208000);assert.equal(own.settlement.dueIn,5000);
const source=report.dailyFunds.team.pairs.find(row=>row.id==='owner:assistant');assert.equal(pair.closingDue,-source.net);assert.equal(pair.offset,source.offset);
const next=check(f.report(D3)).ownershipBusiness.assistant;assert.equal(next.netReceipts,0);assert.equal(next.recordCount,0);assert.equal(next.hasActivity,true);const carried=next.settlement.counterparts.find(row=>row.member==='owner');assert.equal(carried.openingDue,208000);assert.equal(carried.periodNew,0);assert.equal(carried.periodTransferred,0);assert.equal(carried.closingDue,208000);
});
test('售后按业务归属计入成本与负利润,真实0元售后也有活动,不按付款人误归属',t=>{
const f=fixture(t);f.after('assistant2');f.after('assistant2',{amount:'20',payer:'assistant2'});f.after('assistant',{amount:'0',payer:'owner'});
const report=check(f.report()),own=report.ownershipBusiness.assistant2,zero=report.ownershipBusiness.assistant;
assert.equal(own.orderCount,0);assert.equal(own.afterSaleCount,2);assert.equal(own.netReceipts,0);assert.equal(own.totalCost,3234);assert.equal(own.selfCost,2000);assert.equal(own.otherCost,1234);assert.equal(own.profit,-3234);assert.equal(own.settlement.dueOut,1234);
assert.equal(zero.afterSaleCount,1);assert.equal(zero.hasActivity,true);assert.equal(zero.totalCost,0);assert.equal(report.ownershipBusiness.owner.totalCost,0);
assert.deepEqual(Object.keys(check(f.report(D,D,'assistant2')).ownershipBusiness),['assistant2']);
});
test('锁价定金与跨日尾款不能代替销售额,成本只用交付消耗并保留原利润',t=>{
const f=fixture(t),lock=f.lock(),original=check(f.report()).ownershipBusiness.assistant;
assert.equal(original.netReceipts,100000);assert.equal(original.sales,0);assert.equal(original.totalCost,0);assert.equal(original.profit,0);assert.equal(original.settlement.dueOut,80000);assert.equal(original.equation.basis,'sales');assert.ok(original.difference.reasons.some(row=>row.code==='price_lock_timing'));
f.close();f.deliver(lock);const delivery=check(f.report(D2)).ownershipBusiness.assistant;
assert.equal(delivery.netReceipts,124400);assert.equal(delivery.sales,224400);assert.equal(delivery.totalCost,201000);assert.equal(delivery.selfCost,2000);assert.equal(delivery.otherCost,199000);assert.equal(delivery.profit,23400);assert.equal(delivery.equation.revenue,224400);assert.equal(delivery.equation.basis,'sales');assert.equal(delivery.difference.amount,-100000);
const combined=check(f.report(D2,D)).ownershipBusiness.assistant;assert.equal(combined.netReceipts,224400);assert.equal(combined.totalCost,201000);assert.equal(combined.profit,23400);assert.equal(combined.equation.basis,'netReceipts');assert.equal(check(f.report()).close.stale,false);
});
test('退货与退款未清不强算现金利润,真实垫付仍按原往来;录错作废沿原账冲零',t=>{
const f=fixture(t),id=f.save('assistant',{fee_items:[{key:'shipping',note:'合成实付运费',amount:'5',payer:'assistant'}]});f.action(id,'return',{reason:'合成已退回',verified:true});
const returned=check(f.report()).ownershipBusiness.assistant;assert.equal(returned.sales,0);assert.equal(returned.netReceipts,10000);assert.equal(returned.totalCost,500);assert.equal(returned.selfCost,500);assert.equal(returned.otherCost,0);assert.equal(returned.profit,-500);assert.equal(returned.settlement.dueOut,6000);assert.equal(returned.equation.basis,'sales');assert.ok(returned.difference.reasons.some(row=>row.code==='refund_or_cancellation'));
f.action(id,'refund',{amount:'100',account:'助理微信',verified:true});const refunded=check(f.report()).ownershipBusiness.assistant;assert.equal(refunded.netReceipts,0);assert.equal(refunded.profit,-500);assert.equal(refunded.equation.basis,'netReceipts');assert.equal(refunded.settlement.dueOut,6000);
const cancelled=f.save('assistant',{lines:[line('200','100')],fee_items:[{key:'box',note:'合成误记包装',amount:'10',payer:'owner'}]});f.voidOrder(cancelled);const all=check(f.report()).ownershipBusiness.assistant;assert.equal(all.totalCost,500);assert.equal(all.profit,-500);assert.equal(all.netReceipts,0);
});
test('日购料只把所属订单耗用计成本,不重复加整日采购;退货成本与往来沿原回料规则',t=>{
const f=fixture(t);f.purchase();const id=f.save('assistant',{date:D2,lines:[{name:'足金合成挂件',unit:'g',quantity:'3.000',pocket:'',payer:'assistant',sale:'3000',costParts:{material:'',labor:'30',accessories:'5',other:'1'},costMaterial:{mode:'pool',poolId:D}}],fee_items:[{key:'shipping',note:'合成实付运费',amount:'6',payer:'owner'}]});
const paid=check(f.report()).ownershipBusiness.assistant;assert.equal(paid.totalCost,0);assert.equal(paid.profit,0);
const report=check(f.report(D2)),own=report.ownershipBusiness.assistant;assert.equal(own.totalCost,274200);assert.equal(own.selfCost,3600);assert.equal(own.otherCost,270600);assert.equal(own.profit,25800);assert.equal(own.settlement.dueOut,270600);assert.notEqual(own.totalCost,900000);assert.equal(report.outlayTotal,4200);
f.action(id,'return',{date:D3,reason:'合成池料退回',returnPockets:['金料'],verified:true});const returned=check(f.report(D2)).ownershipBusiness.assistant;assert.equal(returned.totalCost,600);assert.equal(returned.profit,-600);assert.equal(check(f.report(D3)).ownershipBusiness.assistant.settlement.dueOut,600);
assert.equal(returned.poolMaterial.mg,0);assert.equal(returned.poolMaterial.amount,0);assert.deepEqual(returned.poolMaterial.days,[]);assert.equal(returned.poolMaterial.otherCosts.amount,600);
});
test('所属订单料池明细克重不随多人FIFO分摊重复,分币用原金额,应转已经含麦麦垫付料费',t=>{
const f=fixture(t);f.purchase({grams:'1',total:'900',payer:'assistant'});f.purchase({grams:'2',total:'2000',payer:'owner'});
const pooled=(quantity,labor,accessories)=>({name:'足金合成挂件',unit:'g',quantity,pocket:'',payer:'assistant',sale:'3000',costParts:{material:'',labor,accessories,other:'0'},costPayers:{material:'owner',labor:'owner'},costMaterial:{mode:'pool',poolId:D}});
f.save('assistant',{lines:[pooled('1.001','10','1')],fee_items:[{key:'shipping',note:'合成实付运费',amount:'6',payer:'owner'}]});f.save('assistant',{lines:[pooled('0.999','20','2')]});
const report=check(f.report()),own=report.ownershipBusiness.assistant,pool=own.poolMaterial;
assert.equal(pool.mg,2000);assert.equal(pool.amount,193333);assert.equal(pool.days.length,1);assert.equal(pool.days[0].averageRate,96667);assert.equal(pool.days[0].mg,2000);assert.equal(pool.days[0].amount,193333);
assert.notEqual(pool.amount,pool.days[0].averageRate*2,'不能拿两位展示均价重新乘克重');assert.equal(pool.byPayer.assistant.amount,90000);assert.equal(pool.byPayer.owner.amount,103333);assert.equal(pool.byPayer.assistant2.amount,0);
assert.equal(pool.otherCosts.amount,3900);assert.equal(own.totalCost,197233);assert.equal(own.settlement.dueOut,106933);assert.equal(own.settlement.counterparts.find(row=>row.member==='owner').periodNew,103333+3600);assert.equal(report.outlayGoods,293300,'采购现金保留原口径,未重复加耗用料费');
const old=own.totalCost;f.save('assistant',{lines:[line('100','60')]});const mixed=check(f.report()).ownershipBusiness.assistant;assert.equal(mixed.poolMaterial.amount,193333);assert.equal(mixed.poolMaterial.otherCosts.amount,9900);assert.equal(mixed.totalCost,old+6000);assert.equal(mixed.settlement.dueOut,112933);
const foreign=f.save('assistant2',{customer:'不可见池料客户',lines:[pooled('0.500','0','0')]});
const personal=check(f.report(D,D,'assistant')).ownershipBusiness.assistant,filtered=check(f.report(D,D,'owner','assistant')).ownershipBusiness.assistant;
assert.deepEqual(personal.poolMaterial,filtered.poolMaterial);assert.equal(personal.poolMaterial.mg,2000);assert.equal(personal.poolMaterial.amount,193333);assert.ok(!JSON.stringify(personal).includes(foreign));assert.ok(!JSON.stringify(personal).includes('不可见池料客户'));
});
test('跨日多料池分别列原料价,未使用的采购及录错作废不计已用料费',t=>{
const f=fixture(t);f.purchase();f.purchase({date:D2,grams:'10',total:'9500'});
const pooled=(poolId,quantity)=>({name:'足金合成挂件',unit:'g',quantity,pocket:'',payer:'owner',sale:'3000',costParts:{material:'',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'pool',poolId}});
assert.deepEqual(check(f.report()).ownershipBusiness.assistant.poolMaterial.days,[]);
f.save('assistant',{date:D3,lines:[pooled(D,'1'),pooled(D2,'2')]});const pool=check(f.report(D3)).ownershipBusiness.assistant.poolMaterial;
assert.equal(pool.mg,3000);assert.equal(pool.amount,280000);assert.deepEqual(pool.days.map(row=>[row.date,row.mg,row.averageRate,row.amount]),[[D,1000,90000,90000],[D2,2000,95000,190000]]);
const mistaken=f.save('assistant',{date:D3,lines:[pooled(D2,'1')]});f.voidOrder(mistaken);const after=check(f.report(D3)).ownershipBusiness.assistant.poolMaterial;assert.equal(after.mg,3000);assert.equal(after.amount,280000);assert.equal(after.otherCosts.amount,0);
});
test('成本缺失、料池待补与旧单未入账费用保留null和已知数,不能显示完整利润或结清',t=>{
const f=fixture(t);f.save('assistant',{date:D2,lines:[{name:'足金合成待补',unit:'g',quantity:'1.000',pocket:'',payer:'owner',costPayers:{material:'owner',labor:'assistant'},sale:'1000',costParts:{material:'',labor:'30',accessories:'0',other:'0'},costMaterial:{mode:'pool',poolId:D}}],fee_items:[{key:'shipping',note:'合成实付运费',amount:'5',payer:'owner'}]});
let own=check(f.report(D2)).ownershipBusiness.assistant;assert.equal(own.totalCost,null);assert.equal(own.knownTotalCost,3500);assert.equal(own.selfCost,3000);assert.equal(own.otherCost,null);assert.equal(own.knownOtherCost,500);assert.equal(own.profit,null);assert.equal(own.knownProfit,0);assert.equal(own.incomplete,true);assert.equal(own.missingCostCount,1);assert.equal(own.unknownProfitCount,1);assert.equal(own.equation.complete,false);assert.equal(own.settlement.partial,true);assert.ok(own.settlement.pendingCount>0);
assert.equal(own.poolMaterial.mg,1000);assert.equal(own.poolMaterial.amount,null);assert.equal(own.poolMaterial.byPayer.owner.amount,null);assert.equal(own.poolMaterial.byPayer.assistant.amount,null);assert.equal(own.poolMaterial.otherCosts.amount,3500);assert.equal(own.poolMaterial.days[0].averageRate,null);
f.purchase();own=check(f.report(D2)).ownershipBusiness.assistant;assert.equal(own.totalCost,93500);assert.equal(own.profit,6500);assert.equal(own.incomplete,false);
assert.equal(own.poolMaterial.amount,90000);assert.equal(own.poolMaterial.byPayer.owner.amount,90000);assert.equal(own.poolMaterial.otherCosts.amount,3500);
const old=f.save('assistant',{date:D2,lines:[line('100','60')],fee_items:[{key:'shipping',note:'合成旧单待核费',amount:'',payer:'owner',status:'estimated'}]},false);f.action(old,'confirm',{date:D2});
own=check(f.report(D2)).ownershipBusiness.assistant;assert.equal(own.totalCost,null);assert.equal(own.profit,null);assert.equal(own.pendingCostCount,1);assert.equal(own.costByPayer.owner.pendingCount,1);assert.equal(own.settlement.partial,true);assert.ok(own.difference.reasons.some(row=>row.code==='unfinalized_orders'));
f.save('assistant',{date:D2},false);own=check(f.report(D2)).ownershipBusiness.assistant;assert.equal(own.draftCount,1);assert.equal(own.costByPayer.assistant.totalCost,null);assert.equal(own.hasActivity,true);
});
test('信用卡手续费与未分项成本沿原成本项目汇总,已知利润恒等于原销售净额减成本',t=>{
const f=fixture(t),id=f.save('assistant',{payment_account:'助理信用卡',lines:[line('100.01','60.02','assistant2')]}),source=f.ledger.detail(id),own=check(f.report()).ownershipBusiness.assistant;
assert.equal(own.totalCost,6002+source.directCost);assert.equal(own.profit,source.profit);assert.equal(own.costByPayer.assistant2.knownTotalCost,6002);assert.equal(own.costByPayer.owner.knownTotalCost,source.directCost);assert.equal(own.otherCost,own.totalCost);assert.equal(own.equation.basis,'netReceipts');
});
test('置换抵扣与余料实付款不冒充现金收入或额外订单成本,利润继续沿原销售单',t=>{
const f=fixture(t);f.run({},()=>f.ledger.stock({date:D,kind:'opening',pocket:'现货',grams:'20',note:'合成置换库存'},f.actors.owner));
const input={mode:'exchange',date:D,member:'assistant',customer:'合成置换客户',salesperson:'合成开单人',old_lines:[{name:'合成旧料',incoming_weight:'3',melted_weight:'3',purity:'100'}],buy_rate:'900',payer:'owner',payment_account:'麦麦微信',verified:true,
exchange:{name:'足金999',quantity:'2',pocket:'现货',gold_price:'0',labor_rate:'20',depreciation_rate:'10',cost_labor:{mode:'total',amount:'10'},cost_payer:'owner',rounding_mode:'cent'}};
const recovery=f.run(input,()=>f.ledger.createRecovery(input,f.actors.owner)),source=f.ledger.detail(recovery.order_id),own=check(f.report()).ownershipBusiness.assistant;
assert.equal(source.nonCashOffset,6000);assert.equal(source.cashPaid,84000);assert.equal(own.netReceipts,0);assert.equal(own.sales,6000);assert.equal(own.totalCost,1000);assert.equal(own.profit,5000);assert.equal(own.profit,source.profit);assert.equal(own.equation.basis,'sales');assert.equal(own.equation.revenue,6000);assert.equal(own.difference.amount,-6000);assert.ok(own.difference.reasons.some(row=>row.code==='exchange_offset'));
});
test('个人只见自己利润成本与本人双方余额,老板筛选一致;旧双人来源不把团队0余额当已结清',t=>{
const f=fixture(t);f.save('assistant',{lines:[line('100','60')]});const foreign=f.save('assistant2',{customer:'绝不可见另一位客户',lines:[line('900','700')]});
const own=check(f.report(D,D,'assistant')).ownershipBusiness.assistant,filtered=check(f.report(D,D,'owner','assistant')).ownershipBusiness.assistant;assert.deepEqual(own,filtered);assert.equal(own.profit,4000);assert.equal(own.totalCost,6000);assert.ok(!JSON.stringify(own).includes(foreign));assert.ok(!JSON.stringify(own).includes('绝不可见'));assert.ok(own.settlement.counterparts.every(row=>!Object.hasOwn(row,'entries')));
assert.deepEqual(Object.keys(f.report(D,D,'assistant').ownershipBusiness),['assistant']);assert.throws(()=>f.report(D,D,'assistant','assistant2'),error=>error.status===403);
const old=fixture(t,{team:false});old.save();const before=check(old.report()).ownershipBusiness.assistant;assert.equal(before.settlement.available,false);assert.equal(before.settlement.dueOut,null);assert.equal(before.settlement.dueIn,null);assert.ok(before.settlement.legacyCount>0);old.ledger.enableTeamMode();
const migrated=check(old.report()).ownershipBusiness.assistant;assert.equal(migrated.totalCost,6000);assert.equal(migrated.profit,4000);assert.equal(migrated.settlement.available,true);assert.equal(migrated.settlement.dueOut,0);assert.equal(migrated.settlement.partial,true);assert.ok(migrated.settlement.legacyCount>0);assert.match(migrated.settlement.notice,/历史单待结请核对原结算/);
});
test('新增个人经营展示不改变旧字段、原hash和核对状态,读取不写任何账表或资金来源',t=>{
const f=fixture(t);demo(f);f.after();f.purchase();const report=check(f.report());f.close();
const stored=JSON.parse(f.ledger.one('SELECT report FROM closes WHERE date=?',D).report);delete stored.ownershipBusiness;f.ledger.run('UPDATE closes SET report=? WHERE date=?',JSON.stringify(stored),D);
const before=contents(f.ledger),changes=f.ledger.one('SELECT total_changes() AS count').count;
const current=check(f.report());assert.equal(current.reportRevision,report.reportRevision);assert.equal(current.reportRevision,stored.reportRevision);assert.equal(current.close.stale,false);
for(const key of Object.keys(stored).filter(key=>key!=='close'))assert.deepEqual(JSON.parse(JSON.stringify(current[key])),stored[key],key+'原返回值保持不变');
assert.deepEqual(f.report(),current);f.report(D,D,'assistant');f.report(D,D,'assistant2');f.report(D3,D);f.report(D3);assert.equal(f.ledger.one('SELECT total_changes() AS count').count,changes);assert.equal(contents(f.ledger),before);
});
test('麦麦垫付逐笔只列所选日所属订单和原分摊金额,昨日垫付与另一助理客户不混入',t=>{
const f=fixture(t);f.purchase();const yesterday=f.save('assistant',{customer:'昨日垫付客户',lines:[line('100','60')]});
const pooled=f.save('assistant',{date:D2,customer:'本日池料客户',lines:[{name:'足金合成挂件',unit:'g',quantity:'3',pocket:'',payer:'assistant',sale:'3000',costParts:{material:'',labor:'30',accessories:'5',other:'0'},costPayers:{material:'owner',labor:'owner'},costMaterial:{mode:'pool',poolId:D}}],fee_items:[{key:'shipping',note:'本日实付运费',amount:'6',payer:'owner'}]});
const manual=f.save('assistant',{date:D2,customer:'本日配件客户',lines:[line('100','10')]});f.save('assistant2',{date:D2,customer:'另一助理秘密客户',payment_account:'助理2微信',lines:[line('1000','700')]});
const report=check(f.report(D2,D2,'assistant')),own=report.ownershipBusiness.assistant,advances=own.ownerAdvances,day=advances.days[0];
assert.deepEqual(advances.days.map(row=>row.date),[D2]);assert.equal(day.amount,274600);assert.equal(day.poolAmount,270000);assert.equal(day.otherAmount,4600);assert.equal(day.items.length,4);assert.deepEqual([...new Set(day.items.map(row=>row.id))].sort(),[pooled,manual].sort());
const material=day.items.find(row=>row.poolMaterial);assert.equal(material.date,D2);assert.equal(material.poolId,D);assert.equal(material.name,'料池料费 · 麦麦垫付部分');assert.equal(material.amount,270000);assert.ok(!Object.hasOwn(material,'calculation'),'付款子行不携带整商品克重乘均价的误导公式');
assert.ok(!JSON.stringify(advances).includes(yesterday));assert.ok(!JSON.stringify(advances).includes('另一助理'));assert.equal(own.settlement.dueOut,280600,'团队原累计余额继续保留,不能当成本日垫付');assert.deepEqual(advances,f.report(D2,D2,'owner','assistant').ownershipBusiness.assistant.ownerAdvances);
f.action(pooled,'return',{date:D3,reason:'合成本日退回',returnPockets:['金料'],verified:true});const returned=check(f.report(D2,D2,'assistant')).ownershipBusiness.assistant.ownerAdvances.days[0];assert.equal(returned.amount,1600);assert.equal(returned.poolAmount,0);assert.ok(returned.items.every(row=>row.name!=='进货工费'&&!row.poolMaterial));
});
test('月汇总麦麦垫付按开单日逐日展开,费用付款日仍可追溯,空日不从历史累计造垫付',t=>{
const f=fixture(t),id=f.save('assistant',{customer:'月内第一天',lines:[line('100','60')]});f.save('assistant',{date:D2,customer:'月内第二天',lines:[line('100','70')]});f.action(id,'expense',{date:D3,amount:'5',payer:'owner',note:'跨日实际运费'});
const before=contents(f.ledger),changes=f.ledger.one('SELECT total_changes() AS count').count,monthly=check(f.report(D2,D)).ownershipBusiness.assistant.ownerAdvances;
assert.deepEqual(monthly.days.map(day=>[day.date,day.amount]),[[D,6500],[D2,7000]]);const fee=monthly.days[0].items.find(item=>item.name==='跨日实际运费');assert.equal(fee.date,D);assert.equal(fee.source,D3);assert.equal(fee.amount,500);
assert.deepEqual(check(f.report(D3)).ownershipBusiness.assistant.ownerAdvances.days,[]);assert.equal(f.ledger.one('SELECT total_changes() AS count').count,changes);assert.equal(contents(f.ledger),before);
});
test('未知池料归属不猜麦麦份额,预估未付只提示不计已垫付,零元和作废成本不列明细',t=>{
const f=fixture(t);f.save('assistant',{date:D2,lines:[{name:'足金待补料',unit:'g',quantity:'1',pocket:'',payer:'assistant',sale:'1000',costParts:{material:'',labor:'30',accessories:'0',other:'0'},costPayers:{material:'assistant',labor:'owner'},costMaterial:{mode:'pool',poolId:D}}]});
const pending=check(f.report(D2)).ownershipBusiness.assistant.ownerAdvances.days[0];assert.equal(pending.amount,null);assert.equal(pending.knownAmount,3000);assert.equal(pending.poolAmount,null);assert.equal(pending.otherAmount,3000);const missing=pending.items.find(item=>item.allocationPending);assert.equal(missing.amount,null);assert.equal(missing.name,'料池料费 · 麦麦份额待补');
const other=fixture(t),old=other.save('assistant',{lines:[line('100','60')],fee_items:[{key:'shipping',note:'尚未实际付款运费',amount:'10',payer:'owner',status:'estimated'}]},false);other.action(old,'confirm');
const estimate=check(other.report()).ownershipBusiness.assistant.ownerAdvances.days[0];assert.equal(estimate.amount,0);assert.equal(estimate.knownAmount,0);assert.equal(estimate.pendingCount,1);assert.equal(estimate.items[0].amount,null);assert.equal(estimate.items[0].estimatedAmount,1000);assert.equal(estimate.items[0].status,'pending');
const zero=fixture(t);zero.after('assistant',{amount:'0'});const cancelled=zero.save('assistant');zero.voidOrder(cancelled);assert.deepEqual(check(zero.report()).ownershipBusiness.assistant.ownerAdvances.days,[]);
zero.after('assistant',{amount:'12.34',project:'合成维修'});const after=check(zero.report()).ownershipBusiness.assistant.ownerAdvances.days[0];assert.equal(after.amount,1234);assert.equal(after.items[0].kind,'afterSale');assert.equal(after.items[0].name,'合成维修');
});
test('当日往来包含本人净利润与麦麦代收,只取所选日,不受期初余额和实际已转影响',t=>{
const f=fixture(t);f.save('assistant',{lines:[line('2000','1800')]});demo(f,D2);f.transfer(D2,'assistant','owner','200');
const own=check(f.report(D2)).ownershipBusiness.assistant,day=own.currentAccount.days[0];
assert.deepEqual([day.date,day.materialCost,day.otherCost,day.profit,day.ownerNetReceipts,day.amount],[D2,0,68000,82000,20000,130000]);
assert.equal(own.settlement.dueOut,208000,'历史原余额不改变');assert.equal(day.amount,68000+82000-20000,'不能改成原团队不含利润的待转480或余额2080');
const monthly=check(f.report(D2,D)).ownershipBusiness.assistant.currentAccount;assert.deepEqual(monthly.days.map(day=>[day.date,day.amount]),[[D,200000],[D2,130000]]);
assert.deepEqual(check(f.report(D3)).ownershipBusiness.assistant.currentAccount.days,[],'空日不能带入以前的余额、利润或转账');
});
test('当日料费使用真实手填与料池耗用分摊,其他付款人成本不当作麦麦垫付,绝不叠加采购',t=>{
const f=fixture(t);f.purchase({grams:'1',total:'900',payer:'assistant'});f.purchase({grams:'2',total:'2000',payer:'owner'});
f.save('assistant',{lines:[{name:'足金池料',unit:'g',quantity:'2',pocket:'',payer:'assistant',sale:'3000',costParts:{material:'',labor:'30',accessories:'2',other:'0'},costPayers:{material:'assistant',labor:'owner'},costMaterial:{mode:'pool',poolId:D}}],fee_items:[{key:'shipping',note:'实付运费',amount:'6',payer:'owner'}]});
f.save('assistant',{payment_account:'麦麦支付宝',lines:[{name:'手填料费商品',unit:'件',quantity:'1',pocket:'',payer:'owner',sale:'1000',costParts:{material:'600',labor:'10',accessories:'2',other:'0'},costPayers:{material:'owner',labor:'assistant2'}}]});
const own=check(f.report()).ownershipBusiness.assistant,day=own.currentAccount.days[0];
assert.equal(day.materialCost,103333+60000);assert.equal(day.otherCost,3000+600+200);assert.equal(day.profit,own.profit);assert.equal(day.ownerNetReceipts,100000);
assert.equal(day.amount,day.materialCost+day.otherCost+own.profit-100000);assert.notEqual(day.materialCost,290000+60000,'未用采购不计入');assert.equal(own.ownerAdvances.days[0].knownAmount,day.materialCost+day.otherCost);
assert.deepEqual(day,check(f.report(D,D,'assistant')).ownershipBusiness.assistant.currentAccount.days[0]);
});
test('代收超过当日垫付和利润时应返款,跨日锁价收退款与交付分开逐日归集',t=>{
const f=fixture(t);f.save('assistant',{payment_account:'麦麦微信',lines:[line('100','60','assistant')]});
let day=check(f.report()).ownershipBusiness.assistant.currentAccount.days[0];assert.equal(day.materialCost,0);assert.equal(day.otherCost,0);assert.equal(day.profit,4000);assert.equal(day.ownerNetReceipts,10000);assert.equal(day.amount,-6000);
const locked=fixture(t),id=locked.lock();day=check(locked.report()).ownershipBusiness.assistant.currentAccount.days[0];assert.equal(day.materialCost,0);assert.equal(day.ownerNetReceipts,100000);assert.equal(day.amount,-100000);
locked.close();locked.deliver(id);const delivery=check(locked.report(D2)).ownershipBusiness.assistant.currentAccount.days[0];assert.equal(delivery.materialCost,199000);assert.equal(delivery.otherCost,0);assert.equal(delivery.profit,23400);assert.equal(delivery.ownerNetReceipts,0);assert.equal(delivery.amount,222400);
const monthly=check(locked.report(D2,D)).ownershipBusiness.assistant.currentAccount.days;assert.deepEqual(monthly.map(row=>[row.date,row.ownerNetReceipts,row.amount]),[[D,100000,-100000],[D2,0,222400]]);assert.equal(check(locked.report()).close.stale,false);
});
test('当日成本待补或费用未入账时应转保持null,预估未付不计已垫付',t=>{
const f=fixture(t);f.save('assistant',{lines:[{name:'待补池料',unit:'g',quantity:'1',pocket:'',payer:'assistant',sale:'1000',costParts:{material:'',labor:'30',accessories:'0',other:'0'},costPayers:{material:'assistant',labor:'owner'},costMaterial:{mode:'pool',poolId:D}}]});
let day=check(f.report()).ownershipBusiness.assistant.currentAccount.days[0];assert.equal(day.materialCost,null);assert.equal(day.knownMaterialCost,0);assert.equal(day.otherCost,3000);assert.equal(day.profit,null);assert.equal(day.amount,null);assert.equal(day.incomplete,true);
f.purchase();day=check(f.report()).ownershipBusiness.assistant.currentAccount.days[0];assert.equal(day.materialCost,90000);assert.equal(day.profit,7000);assert.equal(day.amount,100000);
const estimated=fixture(t),id=estimated.save('assistant',{fee_items:[{key:'shipping',note:'预估运费',amount:'100',payer:'owner',status:'estimated'}]},false);estimated.action(id,'confirm');
day=check(estimated.report()).ownershipBusiness.assistant.currentAccount.days[0];assert.equal(day.knownOtherCost,0);assert.equal(day.pendingCostCount,1);assert.equal(day.profit,null);assert.equal(day.amount,null);
});