增加订单退货退款售后、原成本回料及跨日损益核算

This commit is contained in:
summer committed 2026-11-10 02:54:58 +08:00
1 parent b6a0213a0c
commit dab735423e
24 files changed
+1048 -82

No files matched your search

+8 -6
View File
@@ -80,7 +80,7 @@ function readPool(ledger,id,env,{internal=false,member=null}={}){
let usages=ledger.rows(`SELECT u.*,u.rowid AS fifo_sequence,o.number,o.customer,o.status AS order_status,o.lines FROM material_pool_usages u JOIN orders o ON o.id=u.order_id WHERE u.pool_id=? ORDER BY u.created,u.rowid`,date)
.map(({lines,...row})=>{const third=ledger.one('SELECT assistant2_amount FROM material_usage_parties WHERE usage_id=?',row.id);return {...row,...(third?{assistant2_amount:third.assistant2_amount}:{}),member:ledger.entityMember('order',row.order_id),...(Allocation.usageSources(ledger,row.id)?{materialSources:Allocation.usageSources(ledger,row.id)}:{}),product:JSON.parse(lines)[row.line_index]?.name??''};});
purchases.splice(0,purchases.length,...purchases.map(row=>actualPurchase(ledger,row)));
const lockReturns=LockPools.returns(ledger,date).filter(r=>!r.sameDay);purchases.push(...lockReturns);usages=LockPools.combined(ledger,date,usages);
const lockReturns=LockPools.returns(ledger,date).filter(r=>!r.sameDay),orderReturns=Rolling.returnsFor(ledger,date).filter(row=>!row.sameDay&&require('./order-after-sales').read(ledger,row.order_id)).flatMap(row=>Allocation.expandSource(row)).map(row=>({...row,id:'return:'+row.id,sourceKind:'return',cashAmount:0,canEdit:false,payer:row.allocations[0]?.payer??'owner'}));purchases.push(...lockReturns,...orderReturns);usages=LockPools.combined(ledger,date,usages);
const settlements=ledger.rows('SELECT * FROM material_pool_settlements WHERE pool_id=? ORDER BY date,created,rowid',date);
const materialGroups=Allocation.groups(purchases),segmented=materialGroups.some(g=>g.kind==='personal_recovery');
const active=usages.filter(row=>row.active),totalMg=sum(purchases,'mg'),totalAmount=purchases.some(row=>row.amount===null)?null:sum(purchases,'amount'),usedMg=sum(active,'mg');
@@ -132,14 +132,15 @@ function quote(ledger,input,actor,env){
const ordered=priceLockId?pool.usages.filter(row=>row.kind==='priceLock'&&row.price_lock_id===priceLockId):LockPools.decorate(ledger,originals),last=ledger.one('SELECT COALESCE(MAX(sequence),0) AS sequence FROM material_usage_order').sequence,created=env.now(),rows=[...base];
for(const entry of entries.filter(value=>value.poolId===poolId)){const old=ordered.find(row=>entry.lineId&&locked?locked.lines[row.line_index]?.id===entry.lineId:row.line_index===entry.lineIndex);rows.push({...old,...(priceLockId?{kind:'priceLock',reserved_mg:entry.mg,snapshot:old?.snapshot??{}}:{}),member,mg:entry.mg,previewIndex:entry.lineIndex,created:old?.created??created,fifo_sequence:old?.fifo_sequence??last+entry.lineIndex+1});}
rows.sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);
const allocated=Allocation.allocate(allocationPool,rows),after=Allocation.balances(allocationPool,allocated),before=Allocation.balances(allocationPool,Allocation.allocate(allocationPool,base));
const frozen=(value,usages)=>require('./order-after-sales').allocateFrozen(ledger,value,usages,(source,items)=>Allocation.allocate(source,items));
const allocated=frozen(allocationPool,rows),after=Allocation.balances(allocationPool,allocated),before=Allocation.balances(allocationPool,frozen(allocationPool,base));
const summary=groups=>{const common=groups.find(g=>g.kind==='public'),personal=groups.find(g=>g.member===member&&g.kind==='personal_recovery');return {publicRemainingMg:common?.remainingMg??0,publicRemainingAmount:common?common.remainingCost:0,personalRemainingMg:personal?.remainingMg??0,personalRemainingAmount:personal?personal.remainingCost:0,eligibleRemainingMg:(common?.remainingMg??0)+(personal?.remainingMg??0)};};
pools.push({poolId,revision:pool.revision,...summary(after),before:summary(before)});
for(const row of allocated.filter(row=>row.previewIndex!==undefined))result.push({lineIndex:row.previewIndex,poolId,mg:row.mg,amount:row.amount,status:row.amount===null?'pending':'allocated',allocations:row.allocations,materialSources:row.materialSources});
}
return {date,member,entries:result.sort((a,b)=>a.lineIndex-b.lineIndex),pools};
}
function allIds(ledger){return ledger.rows("SELECT pool_id AS id FROM material_purchases WHERE deleted_at='' UNION SELECT pool_id AS id FROM material_pool_usages UNION SELECT pool_id AS id FROM material_pool_settlements ORDER BY id DESC").map(row=>row.id);}
function allIds(ledger){return ledger.rows("SELECT pool_id AS id FROM material_purchases WHERE deleted_at='' UNION SELECT pool_id AS id FROM material_pool_usages UNION SELECT pool_id AS id FROM material_pool_settlements UNION SELECT date AS id FROM material_rolling_returns WHERE order_id IN (SELECT order_id FROM order_after_sales) ORDER BY id DESC").map(row=>row.id);}
function settlement(ledger,env){
if(Rolling.enabled(ledger))return {legacyReadOnly:true,settlementDue:0,knownSettlementDue:0,pendingCount:Rolling.readPool(ledger,env.today(),env,{internal:true}).status==='pending'?1:0,pools:[]};
const pools=allIds(ledger).map(id=>internalPool(ledger,id,env)),pendingCount=pools.filter(row=>row.settlement.pending).length;
@@ -195,7 +196,7 @@ function allocatePayers(purchases,fromAmount,amount){
if(skip||left)throw new Error('日购料垫付金额不足,无法分配料费');
return {owner_amount:ownerAmount,assistant_amount:assistantAmount,...(includesThird?{assistant2_amount:assistant2Amount}:{}),zero_payer:zeroPayer};
}
function allocateUsages(pool,usages){return LockPools.allocate(pool,usages,allocatePayers).map((row,index)=>({usage:row.kind==='priceLock'?row:usages[index],...row}));}
function allocateUsages(pool,usages,ledger=null){const base=(value,rows)=>LockPools.allocate(value,rows,allocatePayers);return (ledger?require('./order-after-sales').allocateFrozen(ledger,pool,usages,base):base(pool,usages)).map((row,index)=>({usage:row.kind==='priceLock'?row:usages[index],...row}));}
function prepareLines(ledger,lines,businessDate,env,{orderId=null,member=null}={}){
if(Rolling.isDay(ledger,businessDate))return Rolling.prepareLines(ledger,lines,businessDate,env,{orderId,member});
if(Rolling.enabled(ledger)&&lines.some(line=>line.costMaterial?.mode==='pool'))Rolling.assertDate(ledger,businessDate,env);
@@ -221,7 +222,7 @@ function prepareLines(ledger,lines,businessDate,env,{orderId=null,member=null}={
usages.push({...original,member:member??(orderId?ledger.entityMember('order',orderId):null)??ledger.memberFor(ledger.actor),mg:consumptionMg(line),created:original?.created??created,fifo_sequence:original?.fifo_sequence??lastSequence+index+1,preview_index:index});
}
usages.sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);
for(const {usage,...allocation} of allocateUsages(pool,usages))if(usage.preview_index!==undefined)
for(const {usage,...allocation} of allocateUsages(pool,usages,ledger))if(usage.preview_index!==undefined)
applySnapshot(lines[usage.preview_index],{mg:usage.mg,...allocation},pool,'preview');
}
return lines;
@@ -237,8 +238,9 @@ function reconcileInternal(ledger,id,date,actor,env,{skipJournalOrder=null,alloc
if(Rolling.enabled(ledger))Rolling.assertDate(ledger,id,env);
const beforePool=internalPool(ledger,id,env),active=beforePool.usages.filter(row=>row.active||row.kind==='priceLock'&&row.reservedPublicSubstitutionMg>0),pending=beforePool.shortageMg>0;
const orders=new Map();
for(const {usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,assistant2_amount:assistant2Amount,zero_payer,materialSources} of allocateUsages(beforePool,active)){
for(const {usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,assistant2_amount:assistant2Amount,zero_payer,materialSources} of allocateUsages(beforePool,active,ledger)){
if(usage.kind==='priceLock'){LockPools.update(ledger,usage,beforePool,actor,env,{skipJournalOrder});continue;}
if(require('./order-after-sales').read(ledger,usage.order_id))continue;
if(allocationOnly&&usage.amount!==amount)env.fail('历史日购料料费与加权成本不一致,升级已撤回,请维护者核对');
if(!orders.has(usage.order_id))orders.set(usage.order_id,{order:ledger.rawOrder(usage.order_id),deltas:0,changes:[]});
const update=orders.get(usage.order_id),line=update.order.lines[usage.line_index];