支持回收单修改取消、按归属人优先用料及锁价交付改单

This commit is contained in:
summer committed 2026-11-04 22:18:56 +08:00
1 parent 0e146739bc
commit 19b1b0263c
41 files changed
+1814 -203

No files matched your search

+46 -18
View File
@@ -7,7 +7,7 @@ const Rolling=require('./rolling-material-pools');
const PARTIES=['owner','assistant','assistant2'];
const sum=(rows,key)=>rows.reduce((total,row)=>total+(row[key]??0),0);
const LIMIT=100000000000;
const LockPools=require('./price-lock-pools');
const LockPools=require('./price-lock-pools'),Allocation=require('./material-pool-allocation');
const ALLOCATION_VERSION=2,ALLOCATION_KEY='material-pool-allocation-version';
function initialize(ledger){
ledger.db.exec(`
@@ -54,7 +54,7 @@ function initialize(ledger){
});}finally{if(foreignKeys)ledger.db.exec('PRAGMA foreign_keys=ON');}
}
Rolling.initialize(ledger);
LockPools.initialize(ledger);
LockPools.initialize(ledger);Allocation.initialize(ledger);
}
function atomic(ledger,fn){
ledger.db.exec('SAVEPOINT material_pool_action');
@@ -64,7 +64,8 @@ function atomic(ledger,fn){
function activeActor(actor,env){if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号登记日购料',403);}
function poolId(value,env){return env.day(value);}
function actualPurchase(ledger,row){
const purchase={...row,payer:TeamFunds.actualPurchasePayer(ledger,row)};
const personal=ledger.one("SELECT name FROM sqlite_master WHERE type='table' AND name='recovery_material_batches'")?require('./recovery-material').purchaseSource(ledger,row.id):null;
const purchase={...row,payer:TeamFunds.actualPurchasePayer(ledger,row),...(personal??{})};
const source=ledger.one('SELECT * FROM recovery_purchase_sources WHERE purchase_id=?',row.id);
return source?{...purchase,recovery_id:source.recovery_id,cashAmount:source.cash_amount,offsetAmount:source.offset_amount,allocations:JSON.parse(source.allocations),canEdit:false}:purchase;
}
@@ -72,15 +73,16 @@ const purchaseAllocations=purchase=>purchase.allocations??[{payer:purchase.payer
// consumptionMg只由服务器在关联置换单建立后保存,普通validateLines不会接纳这个字段。
const consumptionMg=line=>line.costMaterial?.consumptionMg??line.quantity;
function markPurchasePayer(ledger,id){ledger.run("INSERT OR IGNORE INTO material_purchase_payment_origins VALUES (?,'purchase')",id);}
function readPool(ledger,id,env,{internal=false}={}){
if(Rolling.isDay(ledger,id))return Rolling.readPool(ledger,id,env,{internal});
function readPool(ledger,id,env,{internal=false,member=null}={}){
if(Rolling.isDay(ledger,id))return Rolling.readPool(ledger,id,env,{internal,member});
if(!internal&&Rolling.enabled(ledger)){const saved=Rolling.legacySnapshot(ledger,id);if(saved)return visiblePool(ledger,saved);}
const date=poolId(id,env),purchases=ledger.rows("SELECT * FROM material_purchases WHERE pool_id=? AND deleted_at='' ORDER BY created,rowid",date);
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}:{}),product:JSON.parse(lines)[row.line_index]?.name??''};});
.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 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=sum(purchases,'amount'),usedMg=sum(active,'mg');
const shortageMg=Math.max(0,usedMg-totalMg),remainingMg=Math.max(0,totalMg-usedMg),pending=shortageMg>0;
const consumedCost=pending?null:sum(active,'amount'),remainingCost=pending?null:totalAmount-consumedCost;
@@ -92,11 +94,12 @@ function readPool(ledger,id,env,{internal=false}={}){
}
const transferred=sum(settlements,'amount'),credit=pending?null:byPayer.assistant.remaining;
// fifo_sequence 仅供跨池预估排序;新增响应字段不能改变既有料池版本及财务核对哈希。
const revision=createHash('sha256').update(JSON.stringify({purchases,usages:usages.map(({lines,fifo_sequence,...row})=>row),settlements})).digest('hex');
const revision=createHash('sha256').update(JSON.stringify({purchases,usages:usages.map(({lines,fifo_sequence,member,materialSources,...row})=>({...row,...(segmented?{member,materialSources}:{})})),settlements})).digest('hex');
const pool={id:date,date,totalMg,totalAmount,averageRate:totalMg?Calc.poolMaterialAmount(totalAmount,totalMg,1000):null,usedMg,remainingMg,shortageMg,consumedCost,remainingCost,
status:pending?'pending':usedMg===0?'unused':remainingMg===0?'exhausted':'using',revision,purchases,usages,settlements,byPayer,
settlement:{assistantInventoryCredit:credit,transferred,settlementDue:credit===null?null:-credit-transferred,pending}};
return internal?pool:visiblePool(ledger,pool);
if(segmented){const source={...pool,materialGroups},groups=Allocation.balances(source,active),common=groups.find(g=>g.kind==='public');Object.assign(pool,{totalMg:common.totalMg,totalAmount:common.totalAmount,averageRate:common.averageRate,purchases:common.purchases,usedMg:common.usedMg,remainingMg:common.remainingMg,shortageMg:common.shortageMg,consumedCost:common.consumedCost,remainingCost:common.remainingCost,byPayer:common.byPayer,status:common.status,materialGroups,personalPools:Object.fromEntries(groups.filter(g=>g.kind==='personal_recovery').map(g=>[g.member,{...g,date,id:date}])),remainingMaterialGroups:Allocation.remainingGroups(source,active)});pool.settlement={...pool.settlement,pending:common.status==='pending'};}
const result=member?Allocation.eligible(pool,member):pool;return internal?result:visiblePool(ledger,result);
}
function visiblePool(ledger,pool){
if(!ledger.teamMode)return pool;
@@ -107,10 +110,33 @@ function visiblePool(ledger,pool){
const usages=pool.usages.map(row=>own(row.kind==='priceLock'?'price_lock':'order',row.kind==='priceLock'?row.price_lock_id:row.order_id)?{...row,member:self}:{active:row.active,mg:row.mg,amount:row.amount,created:row.created,fifo_sequence:row.fifo_sequence,anonymous:true});
const purchases=pool.purchases.map(row=>own('material_purchase',row.id)?{...row,member:self,...permissions(row)}:{id:row.id,date:row.date,mg:row.mg,amount:row.amount,payer:row.payer,...(row.allocations?{allocations:row.allocations}:{}),shared:true,canEdit:false,canRequestChange:false,...(pool.rolling?{sourceKind:row.sourceKind,allocations:row.allocations,cashAmount:row.cashAmount}:{})});
// 全池重量和均价用于共同料池预估;不公开另一成员的客户、单号、产品、备注和历史结算。
const {returns,opening,...safePool}=pool;
return {...safePool,...(pool.rolling?{opening:{mg:opening.mg,amount:opening.amount,allocations:opening.allocations},todayPurchases:{...pool.todayPurchases,items:purchases.filter(row=>row.sourceKind==='purchase')},returns:(returns||[]).map(row=>own(row.price_lock_id?'price_lock':'order',row.price_lock_id??row.order_id)?row:{id:row.id,date:row.date,mg:row.mg,amount:row.amount,sameDay:row.sameDay,allocations:row.allocations,anonymous:true})}:{}),purchases,usages,settlements:[],settlement:{legacyReadOnly:true,pending:pool.settlement.pending,settlementDue:null},legacyReadOnly:true};
const {returns,opening,materialGroups,remainingMaterialGroups,personalPools,...safePool}=pool;
return {...safePool,...(personalPools?{personalPools:personalPools[self]?{[self]:personalPools[self]}:{}}:{}),...(pool.rolling?{opening:{mg:opening.mg,amount:opening.amount,allocations:opening.allocations},todayPurchases:{...pool.todayPurchases,items:purchases.filter(row=>row.sourceKind==='purchase')},returns:(returns||[]).map(row=>own(row.price_lock_id?'price_lock':'order',row.price_lock_id??row.order_id)?row:{id:row.id,date:row.date,mg:row.mg,amount:row.amount,sameDay:row.sameDay,allocations:row.allocations,anonymous:true})}:{}),purchases,usages,settlements:[],settlement:{legacyReadOnly:true,pending:pool.settlement.pending,settlementDue:null},legacyReadOnly:true};
}
function internalPool(ledger,id,env){return readPool(ledger,id,env,{internal:true});}
function quote(ledger,input,actor,env){
activeActor(actor,env);if(!input||typeof input!=='object'||Array.isArray(input))env.fail('料费试算资料无效');
const orderId=input.orderId??null;if(orderId!==null&&(typeof orderId!=='string'||!orderId))env.fail('原订单身份无效');
let existing=null;if(orderId){ledger.assertAccess('order',orderId,actor);existing=ledger.rawOrder(orderId,actor);}
const member=ledger.selectedMember(input,actor,existing?ledger.entityMember('order',orderId):null),date=env.day(input.date??existing?.date??env.today());
if(existing&&ledger.entityMember('order',orderId)!==member)env.fail('料费试算须沿用原订单归属',403);
if(!Array.isArray(input.entries)||!input.entries.length||input.entries.length>60)env.fail('请提供1~60行料池耗用');
const indices=new Set(),entries=input.entries.map(value=>{
if(!value||!Number.isSafeInteger(value.lineIndex)||value.lineIndex<0||value.lineIndex>=60||indices.has(value.lineIndex)||!Number.isSafeInteger(value.mg)||value.mg<=0||value.mg>LIMIT)env.fail('料费试算克重或商品行无效');
indices.add(value.lineIndex);const poolId=env.day(value.poolId??date);if(poolId>date)env.fail('料池日期不能晚于订单日期');if(Rolling.isDay(ledger,date)&&poolId!==date)env.fail('滚动日料池须使用订单当天日期');return {lineIndex:value.lineIndex,poolId,mg:value.mg};
}),pools=[],result=[];
for(const poolId of [...new Set(entries.map(value=>value.poolId))]){
const pool=readPool(ledger,poolId,env,{internal:true,member}),allocationPool={...pool,materialGroups:pool.materialGroups??Allocation.groups(pool.purchases)},originals=orderId?ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId):[],base=pool.usages.filter(row=>row.active&&!(row.kind!=='priceLock'&&orderId&&row.order_id===orderId));
const ordered=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=>row.line_index===entry.lineIndex);rows.push({...old,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 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 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:[]};
@@ -137,7 +163,7 @@ function snapshotAllocations(row,pool){
}
function applySnapshot(line,row,pool,status){
const amount=row.amount??null,allocations=snapshotAllocations(row,pool);
line.materialPool={poolId:pool.id,date:pool.date,status:amount===null?'pending':status,amount,quantity:row.mg,averageRate:pool.averageRate,allocations,revision:pool.revision};
line.materialPool={...(row.materialSources?{materialSources:row.materialSources}:{}),poolId:pool.id,date:pool.date,status:amount===null?'pending':status,amount,quantity:row.mg,averageRate:row.materialSources?(amount===null?null:Calc.poolMaterialAmount(amount,row.mg,1000)):pool.averageRate,allocations,revision:pool.revision};
line.costParts={...line.costParts,material:amount};
const knownCost=sum(Object.values(line.costParts).map(amount=>({amount})),'amount');
if(knownCost>LIMIT)throw new Error('货品成本超出支持范围');
@@ -168,8 +194,8 @@ function allocatePayers(purchases,fromAmount,amount){
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 prepareLines(ledger,lines,businessDate,env,{orderId=null}={}){
if(Rolling.isDay(ledger,businessDate))return Rolling.prepareLines(ledger,lines,businessDate,env,{orderId});
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);
const groups=new Map();
lines.forEach((line,index)=>{
@@ -190,7 +216,7 @@ function prepareLines(ledger,lines,businessDate,env,{orderId=null}={}){
.filter(usage=>!orderId||usage.order_id!==orderId);
for(const {line,index} of group){
const original=originals.find(usage=>usage.line_index===index);
usages.push({...original,mg:consumptionMg(line),created:original?.created??created,fifo_sequence:original?.fifo_sequence??lastSequence+index+1,preview_index:index});
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)
@@ -209,14 +235,14 @@ 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),pending=beforePool.shortageMg>0;
const orders=new Map();
for(const {usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,assistant2_amount:assistant2Amount,zero_payer} of allocateUsages(beforePool,active)){
for(const {usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,assistant2_amount:assistant2Amount,zero_payer,materialSources} of allocateUsages(beforePool,active)){
if(usage.kind==='priceLock'){LockPools.update(ledger,usage,beforePool,actor,env,{skipJournalOrder});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];
if(!line||line.costMaterial?.mode!=='pool'||line.costMaterial.poolId!==id)env.fail('日购料关联与订单不一致,请联系维护者');
const beforeAllocations=line.materialPool?.allocations??[],afterAllocations=snapshotAllocations({amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,assistant2_amount:assistant2Amount,zero_payer},beforePool);
const sourceChanged=JSON.stringify(beforeAllocations)!==JSON.stringify(afterAllocations);
const sourceChanged=JSON.stringify(beforeAllocations)!==JSON.stringify(afterAllocations)||JSON.stringify(line.materialPool?.materialSources)!==JSON.stringify(materialSources);
const changed=usage.amount!==amount||usage.owner_amount!==ownerAmount||usage.assistant_amount!==assistantAmount||usage.assistant2_amount!==assistant2Amount||sourceChanged;
const next={...usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,...(assistant2Amount!==undefined?{assistant2_amount:assistant2Amount}:{}),revision:usage.revision+(changed?1:0)};
if(assistant2Amount===undefined)delete next.assistant2_amount;
@@ -230,7 +256,8 @@ function reconcileInternal(ledger,id,date,actor,env,{skipJournalOrder=null,alloc
// 订单快照中原先的料费是上次已经计入利润的值;新交付单的整单交付流水稍后统一记录。
const oldAmount=line.costParts?.material??0;
if(allocationOnly&&(line.costParts?.material??null)!==amount)env.fail('历史订单料费快照与日购料用量不一致,升级已撤回,请维护者核对');
applySnapshot(line,{...next,mg:usage.mg,zero_payer},beforePool,'allocated');
Allocation.saveUsage(ledger,usage.id,materialSources);
applySnapshot(line,{...next,mg:usage.mg,zero_payer,materialSources},beforePool,'allocated');
update.deltas+=(amount??0)-oldAmount;
if(changed)update.changes.push({line:usage.line_index,before:beforeValue,after:afterValue});
}
@@ -327,6 +354,7 @@ function purchase(ledger,input,actor,env,{member=null,source=null}={}){return at
if(source){
if(source.cashAmount+source.offsetAmount!==amount||sum(source.allocations,'amount')!==amount)env.fail('回收购料的现金与抵扣金额不守恒');
ledger.run('INSERT INTO recovery_purchase_sources VALUES (?,?,?,?,?)',id,source.recoveryId,source.cashAmount,source.offsetAmount,JSON.stringify(source.allocations));
require('./recovery-material').registerSource(ledger,id,{recoveryId:source.recoveryId,member:source.member??member??ledger.memberFor(actor)});
}
if(ledger.teamMode)ledger.assignMember('material_purchase',id,member??ledger.memberFor(actor));
startPurchaseFunds(ledger,readPurchase(ledger,id,env),actor,env);
@@ -501,4 +529,4 @@ function reporting(ledger,query,env){
settlements:restricted?[]:ledger.rows('SELECT * FROM material_pool_settlements WHERE date>=? AND date<=? ORDER BY date,created,rowid',from,to),
events:ledger.visibleRows('order',ledger.rows('SELECT * FROM material_pool_events WHERE date>=? AND date<=? ORDER BY date,created,rowid',from,to),'order_id').map(row=>({...row,before_value:JSON.parse(row.before_value),after_value:JSON.parse(row.after_value)}))};
}
module.exports={initialize,allocatePayers,prepareLine,prepareLines,readPool,visiblePool,list,purchase,purchaseDetail,editPurchase,deletePurchase,deliver,release,adjust,reassign,settle,reporting,settlement,allocationStatus,migrateAllocation,actualPurchase,reconcile};
module.exports={initialize,allocatePayers,prepareLine,prepareLines,readPool,visiblePool,list,purchase,purchaseDetail,editPurchase,deletePurchase,deliver,release,adjust,reassign,settle,reporting,settlement,allocationStatus,migrateAllocation,actualPurchase,reconcile,quote};