日购料垫款按采购先后扣减并迁移历史归属

This commit is contained in:
summer committed 2026-10-23 00:14:29 +08:00
1 parent 34781b6cd1
commit 499b84a7a6
13 files changed
+608 -90

No files matched your search

+148 -33
View File
@@ -4,6 +4,7 @@ const {randomUUID,createHash}=require('node:crypto');
const Calc=require('./public/calculations');
const sum=(rows,key)=>rows.reduce((total,row)=>total+(row[key]??0),0);
const LIMIT=100000000000;
const ALLOCATION_VERSION=2,ALLOCATION_KEY='material-pool-allocation-version';
function initialize(ledger){
ledger.db.exec(`
CREATE TABLE IF NOT EXISTS material_purchases(
@@ -38,7 +39,7 @@ function activeActor(actor,env){if(!actor||!['owner','assistant'].includes(actor
function poolId(value,env){return env.day(value);}
function readPool(ledger,id,env){
const date=poolId(id,env),purchases=ledger.rows("SELECT * FROM material_purchases WHERE pool_id=? AND deleted_at='' ORDER BY created,rowid",date);
const usages=ledger.rows(`SELECT u.*,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)
const 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})=>({...row,product:JSON.parse(lines)[row.line_index]?.name??''}));
const settlements=ledger.rows('SELECT * FROM material_pool_settlements WHERE pool_id=? ORDER BY date,created,rowid',date);
const active=usages.filter(row=>row.active),totalMg=sum(purchases,'mg'),totalAmount=sum(purchases,'amount'),usedMg=sum(active,'mg');
@@ -51,7 +52,8 @@ function readPool(ledger,id,env){
byPayer[payer]={purchased,consumed,remaining:pending?null:purchased-consumed};
}
const transferred=sum(settlements,'amount'),credit=pending?null:byPayer.assistant.remaining;
const revision=createHash('sha256').update(JSON.stringify({purchases,usages:usages.map(({lines,...row})=>row),settlements})).digest('hex');
// fifo_sequence 仅供跨池预估排序;新增响应字段不能改变既有料池版本及财务核对哈希。
const revision=createHash('sha256').update(JSON.stringify({purchases,usages:usages.map(({lines,fifo_sequence,...row})=>row),settlements})).digest('hex');
return {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}};
@@ -71,10 +73,14 @@ function list(ledger,query,env){
return {from,date,rows,summary:{totalMg:sum(rows,'totalMg'),totalAmount:sum(rows,'totalAmount'),usedMg:sum(rows,'usedMg'),remainingMg:sum(rows,'remainingMg'),shortageMg:sum(rows,'shortageMg'),
consumedCost:pendingCount?null:sum(rows,'consumedCost'),remainingCost:pendingCount?null:sum(rows,'remainingCost'),pendingCount,purchaseCount:rows.reduce((n,row)=>n+row.purchases.length,0)},settlement:settlement(ledger,env)};
}
function applySnapshot(line,row,pool,status){
function snapshotAllocations(row,pool){
const amount=row.amount??null,allocations=amount===null?[]:[{payer:'owner',amount:row.owner_amount??0},{payer:'assistant',amount:row.assistant_amount??0}].filter(part=>part.amount>0);
// 金额为0的极小克重仍保留一条来源,不能被误判为未分配。
if(amount===0&&!allocations.length)allocations.push({payer:pool.byPayer.assistant.purchased&&!pool.byPayer.owner.purchased?'assistant':'owner',amount:0});
if(amount===0&&!allocations.length)allocations.push({payer:row.zero_payer??(pool.byPayer.assistant.purchased&&!pool.byPayer.owner.purchased?'assistant':'owner'),amount:0});
return allocations;
}
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.costParts={...line.costParts,material:amount};
const knownCost=sum(Object.values(line.costParts).map(amount=>({amount})),'amount');
@@ -82,49 +88,101 @@ function applySnapshot(line,row,pool,status){
line.cost=Object.keys(Calc.costLabels).some(key=>line.costParts[key]==null)?null:knownCost;
return line;
}
function prepareLine(ledger,line,businessDate,env){
if(line.costMaterial?.mode!=='pool')return line;
if(line.unit!=='g'||Calc.isSilver(line.name))env.fail('日购料成本只支持按克黄金商品');
const id=poolId(line.costMaterial.poolId,env);
if(businessDate&&id>businessDate)env.fail('日购料日期不能晚于订单日期');
const pool=readPool(ledger,id,env),canAllocate=pool.totalMg>=pool.usedMg+line.quantity;
const amount=canAllocate?Calc.poolMaterialAmount(pool.totalAmount,pool.totalMg,line.quantity):null;
const assistantAmount=amount===null?null:pool.totalAmount?Calc.poolMaterialAmount(pool.byPayer.assistant.purchased,pool.totalAmount,amount):0;
return applySnapshot(line,{mg:line.quantity,amount,owner_amount:amount===null?null:amount-assistantAmount,assistant_amount:assistantAmount},pool,'preview');
// 当天料费仍按总金额/总克重加权。FIFO 只切整数分金额区间,不使用采购批次的克价或克重。
// purchases 必须沿用 created,rowid 的稳定顺序;fromAmount 是前序商品已结转的加权料费。
function allocatePayers(purchases,fromAmount,amount){
for(const value of [fromAmount,amount])if(!Number.isSafeInteger(value)||value<0||value>LIMIT)throw new Error('日购料垫付分配金额无效');
let skip=fromAmount,left=amount,ownerAmount=0,assistantAmount=0,zeroPayer='owner',foundZero=false;
for(const purchase of purchases){
if(!Number.isSafeInteger(purchase.amount)||purchase.amount<=0||!['owner','assistant'].includes(purchase.payer))throw new Error('日购料采购垫付记录无效');
zeroPayer=foundZero?zeroPayer:purchase.payer;
if(skip>=purchase.amount){skip-=purchase.amount;continue;}
if(!foundZero){zeroPayer=purchase.payer;foundZero=true;}
const allocated=Math.min(left,purchase.amount-skip);
if(purchase.payer==='owner')ownerAmount+=allocated;else assistantAmount+=allocated;
left-=allocated;skip=0;
}
if(skip||left)throw new Error('日购料垫付金额不足,无法分配料费');
return {owner_amount:ownerAmount,assistant_amount:assistantAmount,zero_payer:zeroPayer};
}
function allocateUsages(pool,usages){
const pending=sum(usages,'mg')>pool.totalMg;
let cumulativeMg=0,previousAmount=0;
return usages.map(usage=>{
cumulativeMg+=usage.mg;
const cumulativeAmount=pending?null:Calc.poolMaterialAmount(pool.totalAmount,pool.totalMg,cumulativeMg);
const amount=pending?null:cumulativeAmount-previousAmount;
const allocation=amount===null?{owner_amount:null,assistant_amount:null}:allocatePayers(pool.purchases,previousAmount,amount);
previousAmount=cumulativeAmount??0;
return {usage,amount,...allocation};
});
}
function prepareLines(ledger,lines,businessDate,env,{orderId=null}={}){
const groups=new Map();
lines.forEach((line,index)=>{
if(line.costMaterial?.mode!=='pool')return;
if(line.unit!=='g'||Calc.isSilver(line.name))env.fail('日购料成本只支持按克黄金商品');
const id=poolId(line.costMaterial.poolId,env);
if(businessDate&&id>businessDate)env.fail('日购料日期不能晚于订单日期');
if(!groups.has(id))groups.set(id,[]);
groups.get(id).push({line,index});
});
if(!groups.size)return lines;
// 整单修改按原行身份替换用量,原 created,rowid 保持原位;新增行与正式交付一样追加。
const originals=orderId?ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId):[];
const lastSequence=ledger.one('SELECT COALESCE(MAX(rowid),0) AS value FROM material_pool_usages').value,created=env.now();
for(const [id,group] of groups){
const pool=readPool(ledger,id,env);
const usages=ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE pool_id=? AND active=1 ORDER BY created,rowid',id)
.filter(usage=>usage.order_id!==orderId);
for(const {line,index} of group){
const original=originals.find(usage=>usage.line_index===index);
usages.push({...original,mg:line.quantity,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)
applySnapshot(lines[usage.preview_index],{mg:usage.mg,...allocation},pool,'preview');
}
return lines;
}
function prepareLine(ledger,line,businessDate,env){return prepareLines(ledger,[line],businessDate,env)[0];}
function usageValue(row){return {poolId:row.pool_id,mg:row.mg,active:row.active,amount:row.amount,ownerAmount:row.owner_amount,assistantAmount:row.assistant_amount,revision:row.revision};}
function usageEvent(ledger,row,before,after,kind,date,actor,env){
ledger.run('INSERT INTO material_pool_events VALUES (?,?,?,?,?,?,?,?,?,?)',randomUUID(),row.pool_id,row.id,row.order_id,date,kind,JSON.stringify(before),JSON.stringify(after),actor.name,env.now());
}
function reconcile(ledger,id,date,actor,env,{skipJournalOrder=null}={}){
function reconcile(ledger,id,date,actor,env,{skipJournalOrder=null,allocationOnly=false,migration=null}={}){
const beforePool=readPool(ledger,id,env),active=beforePool.usages.filter(row=>row.active),pending=beforePool.shortageMg>0;
let cumulative=0,previousAmount=0,previousAssistant=0;
const orders=new Map();
for(const usage of active){
cumulative+=usage.mg;
const cumulativeAmount=pending?null:Calc.poolMaterialAmount(beforePool.totalAmount,beforePool.totalMg,cumulative);
const cumulativeAssistant=pending?null:beforePool.totalAmount?Calc.poolMaterialAmount(beforePool.byPayer.assistant.purchased,beforePool.totalAmount,cumulativeAmount):0;
const amount=pending?null:cumulativeAmount-previousAmount,assistantAmount=pending?null:cumulativeAssistant-previousAssistant,ownerAmount=pending?null:amount-assistantAmount;
const changed=usage.amount!==amount||usage.owner_amount!==ownerAmount||usage.assistant_amount!==assistantAmount;
const next={...usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,revision:usage.revision+(changed?1:0)};
if(changed){
ledger.run('UPDATE material_pool_usages SET amount=?,owner_amount=?,assistant_amount=?,revision=?,updated=? WHERE id=?',amount,ownerAmount,assistantAmount,next.revision,env.now(),usage.id);
usageEvent(ledger,usage,usageValue(usage),usageValue(next),pending?'成本转待补':usage.amount===null?'补齐料费':'加权料费调整',date,actor,env);
}
if(!orders.has(usage.order_id))orders.set(usage.order_id,{order:ledger.rawOrder(usage.order_id),deltas:0,changes:[],fresh:false});
for(const {usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,zero_payer} of allocateUsages(beforePool,active)){
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,zero_payer},beforePool);
const sourceChanged=JSON.stringify(beforeAllocations)!==JSON.stringify(afterAllocations);
const changed=usage.amount!==amount||usage.owner_amount!==ownerAmount||usage.assistant_amount!==assistantAmount||sourceChanged;
const next={...usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,revision:usage.revision+(changed?1:0)};
const beforeValue={...usageValue(usage),allocations:beforeAllocations},afterValue={...usageValue(next),allocations:afterAllocations};
if(changed){
ledger.run('UPDATE material_pool_usages SET amount=?,owner_amount=?,assistant_amount=?,revision=?,updated=? WHERE id=?',amount,ownerAmount,assistantAmount,next.revision,env.now(),usage.id);
usageEvent(ledger,usage,beforeValue,afterValue,allocationOnly?'垫付归属FIFO升级':pending?'成本转待补':usage.amount===null?'补齐料费':'加权料费调整',date,actor,env);
}
// 订单快照中原先的料费是上次已经计入利润的值;新交付单的整单交付流水稍后统一记录。
const oldAmount=line.costParts?.material??0;
applySnapshot(line,{...next,mg:usage.mg},beforePool,'allocated');
if(allocationOnly&&(line.costParts?.material??null)!==amount)env.fail('历史订单料费快照与日购料用量不一致,升级已撤回,请维护者核对');
applySnapshot(line,{...next,mg:usage.mg,zero_payer},beforePool,'allocated');
update.deltas+=(amount??0)-oldAmount;
if(changed)update.changes.push({line:usage.line_index,before:usageValue(usage),after:usageValue(next)});
previousAmount=cumulativeAmount??0;previousAssistant=cumulativeAssistant??0;
if(changed)update.changes.push({line:usage.line_index,before:beforeValue,after:afterValue});
}
for(const [orderId,update] of orders){
ledger.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(update.order.lines),orderId);
if(update.order.status==='delivered'&&orderId!==skipJournalOrder&&update.deltas)ledger.journal(orderId,update.order.delivered_date||update.order.date,'日购料成本调整',0,update.deltas,0);
if(update.changes.length&&orderId!==skipJournalOrder){ledger.touch(orderId);ledger.dirty(update.order.date);ledger.audit(orderId,'日购料自动重算',actor,{poolId:id,changes:update.changes,goodsDelta:update.deltas,accountingDate:update.order.delivered_date||update.order.date});}
if(allocationOnly&&update.deltas)env.fail('垫付归属升级不能改变订单总成本,升级已撤回');
if(!allocationOnly&&update.order.status==='delivered'&&orderId!==skipJournalOrder&&update.deltas)ledger.journal(orderId,update.order.delivered_date||update.order.date,'日购料成本调整',0,update.deltas,0);
if(update.changes.length&&orderId!==skipJournalOrder){
ledger.touch(orderId);ledger.dirty(update.order.date);
if(allocationOnly&&update.order.delivered_date)ledger.dirty(update.order.delivered_date);
ledger.audit(orderId,allocationOnly?'日购料垫付归属升级':'日购料自动重算',actor,{poolId:id,changes:update.changes,goodsDelta:update.deltas,accountingDate:update.order.delivered_date||update.order.date,...(migration?{migration}:{})});
}
}
// 让所有快照使用最终分配后的同一版本,展示版本本身不参与财务改写。
const finalPool=readPool(ledger,id,env);
@@ -134,6 +192,63 @@ function reconcile(ledger,id,date,actor,env,{skipJournalOrder=null}={}){
}
ledger.dirty(id);return finalPool;
}
function allocationStatus(ledger){
const saved=ledger.meta(ALLOCATION_KEY),version=typeof saved==='number'?saved:saved?.version??1;
const usageCount=ledger.one('SELECT COUNT(*) AS count FROM material_pool_usages').count;
const activeUsageCount=ledger.one('SELECT COUNT(*) AS count FROM material_pool_usages WHERE active=1').count;
return {version,targetVersion:ALLOCATION_VERSION,migrationRequired:version<ALLOCATION_VERSION,usageCount,activeUsageCount};
}
function hash(value){return createHash('sha256').update(JSON.stringify(value)).digest('hex');}
// 只允许归属、版本、同步任务和关账过期标志变化;原采购、实际转账、库存及利润流水均受保护。
function migrationSnapshot(ledger,env){
const active=ledger.rows('SELECT order_id,line_index FROM material_pool_usages WHERE active=1');
const allowed=new Set(['orders','material_pool_usages','material_pool_events','audit','meta','sync','closes']);
const tables=ledger.rows("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").map(row=>row.name);
const protectedTables=Object.fromEntries(tables.filter(name=>!allowed.has(name)).map(name=>[name,ledger.rows('SELECT * FROM "'+name.replaceAll('"','""')+'" ORDER BY rowid')]));
const orders=ledger.rows('SELECT * FROM orders ORDER BY rowid').map(({revision,lines,...order})=>({...order,lines:JSON.parse(lines).map((line,index)=>{
if(!active.some(usage=>usage.order_id===order.id&&usage.line_index===index)||!line.materialPool)return line;
const {allocations,revision,...materialPool}=line.materialPool;
return {...line,materialPool};
})}));
const usages=ledger.rows('SELECT * FROM material_pool_usages ORDER BY rowid').map(row=>{
if(!row.active)return row;
const {owner_amount,assistant_amount,revision,updated,...protectedRow}=row;return protectedRow;
});
const closes=ledger.rows('SELECT * FROM closes ORDER BY rowid').map(({stale,...row})=>row);
const meta=ledger.rows('SELECT * FROM meta WHERE key<>? ORDER BY key',ALLOCATION_KEY);
const details=orders.map(order=>ledger.detail(order.id));
const poolSettlement=settlement(ledger,env),pendingOrders=details.filter(order=>order.settlementDue===null).map(order=>order.id);
const knownNet=sum(details,'knownSettlementDue')+poolSettlement.knownSettlementDue;
const financial=details.map(order=>Object.fromEntries(['id','total','goodsCost','knownGoodsCost','directCost','profit','knownProfit','netReceived','balance','materialCostPending'].map(key=>[key,order[key]])));
const pools=allIds(ledger).map(id=>readPool(ledger,id,env));
const totals=pools.map(pool=>Object.fromEntries(['id','totalMg','totalAmount','usedMg','remainingMg','shortageMg','consumedCost','remainingCost','status'].map(key=>[key,pool[key]])));
return {protectedHash:hash({protectedTables,orders,usages,closes,meta}),financial,totals,
globalSettlement:{pendingOrders,pendingPoolCount:poolSettlement.pendingCount,knownNet,net:pendingOrders.length||poolSettlement.pendingCount?null:knownNet},
allocation:{orders:details.filter(order=>active.some(usage=>usage.order_id===order.id)).map(order=>({id:order.id,number:order.number,date:order.date,deliveredDate:order.delivered_date,ownerCost:order.ownerCost,settlementDue:order.settlementDue})),
pools:pools.map(pool=>({id:pool.id,byPayer:pool.byPayer,settlement:pool.settlement}))}};
}
function migrateAllocation(ledger,actor,env,{backupName=null}={}){return atomic(ledger,()=>{
const status=allocationStatus(ledger);
if(!status.migrationRequired)return {changed:false,...status,migration:ledger.meta(ALLOCATION_KEY)};
if(!actor?.name||!['owner','system'].includes(actor.role))env.fail('日购料垫付升级需要明确的维护身份',403);
const before=migrationSnapshot(ledger,env),auditLimit=ledger.one('SELECT COALESCE(MAX(id),0) AS value FROM audit').value,
eventLimit=ledger.one('SELECT COALESCE(MAX(rowid),0) AS value FROM material_pool_events').value;
const previousAudit=hash(ledger.rows('SELECT * FROM audit WHERE id<=? ORDER BY id',auditLimit));
const previousEvents=hash(ledger.rows('SELECT * FROM material_pool_events WHERE rowid<=? ORDER BY rowid',eventLimit));
const migration={fromVersion:status.version,version:ALLOCATION_VERSION,rule:'weighted-cost-amount-fifo',backupName,created:env.now()};
const ids=ledger.rows('SELECT DISTINCT pool_id FROM material_pool_usages WHERE active=1 ORDER BY pool_id').map(row=>row.pool_id);
for(const id of ids)reconcile(ledger,id,env.today(),actor,env,{allocationOnly:true,migration});
const after=migrationSnapshot(ledger,env);
if(before.protectedHash!==after.protectedHash||hash(before.financial)!==hash(after.financial)||hash(before.totals)!==hash(after.totals)||hash(before.globalSettlement)!==hash(after.globalSettlement)
||previousAudit!==hash(ledger.rows('SELECT * FROM audit WHERE id<=? ORDER BY id',auditLimit))||previousEvents!==hash(ledger.rows('SELECT * FROM material_pool_events WHERE rowid<=? ORDER BY rowid',eventLimit)))
env.fail('日购料垫付升级核对未通过,原采购、实付、成本、利润或全局净应结发生变化,升级已撤回');
const result={...migration,poolCount:ids.length,usageCount:status.activeUsageCount,affectedOrderCount:after.allocation.orders.length,
changedUsageCount:ledger.one("SELECT COUNT(*) AS count FROM material_pool_events WHERE rowid>? AND kind='垫付归属FIFO升级'",eventLimit).count,
invariants:{protectedHash:after.protectedHash,financialHash:hash(after.financial),poolTotalsHash:hash(after.totals),globalSettlement:after.globalSettlement}};
ledger.audit('system:material-pool-allocation','日购料垫付FIFO版本升级',actor,{...result,before:before.allocation,after:after.allocation,notice:'当天加权料费保持原值;仅按采购录入顺序重分已耗料款归属;原采购、实际交款、库存及利润流水原样保留;已退订单快照保留'});
ledger.setMeta(ALLOCATION_KEY,result);
return {changed:true,...allocationStatus(ledger),migration:result};
});}
function purchase(ledger,input,actor,env){return atomic(ledger,()=>{
activeActor(actor,env);const date=env.day(input.date),mg=env.weight(input.grams,'采购克重'),amount=env.money(input.total,'采购总金额');
if(mg<=0||amount<=0)env.fail('采购克重和采购总金额必须大于0');
@@ -287,4 +402,4 @@ function reporting(ledger,query,env){
settlements:ledger.rows('SELECT * FROM material_pool_settlements WHERE date>=? AND date<=? ORDER BY date,created,rowid',from,to),
events:ledger.rows('SELECT * FROM material_pool_events WHERE date>=? AND date<=? ORDER BY date,created,rowid',from,to).map(row=>({...row,before_value:JSON.parse(row.before_value),after_value:JSON.parse(row.after_value)}))};
}
module.exports={initialize,prepareLine,readPool,list,purchase,purchaseDetail,editPurchase,deletePurchase,deliver,release,adjust,reassign,settle,reporting,settlement};
module.exports={initialize,allocatePayers,prepareLine,prepareLines,readPool,list,purchase,purchaseDetail,editPurchase,deletePurchase,deliver,release,adjust,reassign,settle,reporting,settlement,allocationStatus,migrateAllocation};