Files
weiguang-jewelry-ledger/新账系统/price-lock-pools.js
T

156 lines
20 KiB
JavaScript
Raw Normal View History

'use strict';
// 锁价预留只占用已有料池;不生成采购、现金、销售或实物流水。
const {randomUUID}=require('node:crypto'),Calc=require('./public/calculations'),Allocation=require('./material-pool-allocation');
const PARTIES=['owner','assistant','assistant2'],sum=(rows,key)=>rows.reduce((n,r)=>n+(r[key]??0),0);
function initialize(l){l.db.exec(`
CREATE TABLE IF NOT EXISTS price_lock_pool_reservations(id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL UNIQUE REFERENCES price_locks(id),pool_id TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),amount INTEGER,allocations TEXT NOT NULL DEFAULT '[]',snapshot TEXT NOT NULL DEFAULT '{}',revision INTEGER NOT NULL DEFAULT 1,created TEXT NOT NULL,updated TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS price_lock_pool_returns(id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),kind TEXT NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL,amount INTEGER,allocations TEXT NOT NULL,origin_pool_id TEXT NOT NULL,same_day INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,UNIQUE(price_lock_id,kind));
CREATE TABLE IF NOT EXISTS material_usage_order(sequence INTEGER PRIMARY KEY AUTOINCREMENT,kind TEXT NOT NULL,source_id TEXT NOT NULL,UNIQUE(kind,source_id));
INSERT INTO material_usage_order(kind,source_id) SELECT 'order',u.id FROM material_pool_usages u WHERE NOT EXISTS(SELECT 1 FROM material_usage_order s WHERE s.kind='order' AND s.source_id=u.id) ORDER BY u.created,u.rowid;
`);}
function sequence(l,kind,id){if(!l.one('SELECT sequence FROM material_usage_order WHERE kind=? AND source_id=?',kind,id))l.run('INSERT INTO material_usage_order(kind,source_id) VALUES (?,?)',kind,id);return l.one('SELECT sequence FROM material_usage_order WHERE kind=? AND source_id=?',kind,id).sequence;}
function decorate(l,rows){return rows.map(r=>({...r,fifo_sequence:l.one("SELECT sequence FROM material_usage_order WHERE kind='order' AND source_id=?",r.id)?.sequence??r.fifo_sequence}));}
function find(l,id){const r=l.one('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=?',id);return r?{...r,allocations:JSON.parse(r.allocations),snapshot:JSON.parse(r.snapshot)}:null;}
function splitParts(parts,amount){let left=amount;const taken=[],rest=[];for(const part of parts){const n=Math.min(left,part.amount);if(n)taken.push({payer:part.payer,amount:n});if(part.amount>n)rest.push({payer:part.payer,amount:part.amount-n});left-=n;}if(left)throw new Error('锁价料池付款归属不足');if(!amount&&!taken.length)taken.push({payer:parts[0]?.payer??'owner',amount:0});return {taken,rest};}
function split(snapshot,used){
if(snapshot.materialSources){const parts=Allocation.splitSources(snapshot.materialSources,used),actual=Allocation.paidAmounts(parts.taken),leftover=Allocation.paidAmounts(parts.rest);return {usedMg:used,amount:actual.amount,leftoverMg:snapshot.quantity-used,leftoverCost:leftover.amount,allocations:actual.allocations,leftoverAllocations:leftover.allocations,materialSources:parts.taken,leftoverMaterialSources:parts.rest};}
if(snapshot.amount===null)return {usedMg:used,amount:null,leftoverMg:snapshot.quantity-used,leftoverCost:null,allocations:[],leftoverAllocations:[]};
const amount=Calc.poolMaterialAmount(snapshot.basisAmount,snapshot.basisMg,snapshot.prefixMg+used)-snapshot.prefixAmount;
const parts=splitParts(snapshot.allocations,amount);return {usedMg:used,amount,leftoverMg:snapshot.quantity-used,leftoverCost:snapshot.amount-amount,allocations:parts.taken,leftoverAllocations:parts.rest};
}
function detail(l,id,env){const r=find(l,id);if(!r)return null;return {...r.snapshot,revision:r.revision,frozen:r.pool_id!==env.today()};}
function reservations(l,date){return l.rows(`SELECT r.*,s.sequence AS fifo_sequence,p.number,p.customer,p.line,p.status,p.delivery,p.final_order_id,o.status AS order_status,o.returned_date FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id LEFT JOIN material_usage_order s ON s.kind='priceLock' AND s.source_id=r.id LEFT JOIN orders o ON o.id=p.final_order_id WHERE r.pool_id=? ORDER BY r.created,r.rowid`,date).map(r=>{
const snapshot=JSON.parse(r.snapshot),delivery=r.delivery?JSON.parse(r.delivery):null;
let mg=r.mg;if(delivery?.date===date)mg=delivery.original_used_mg;if(r.order_status==='returned'&&r.returned_date===date)mg=0;
const effective=snapshot.amount===undefined?{amount:null,allocations:[]}:mg===r.mg?{amount:r.amount,allocations:JSON.parse(r.allocations),...(snapshot.materialSources?{materialSources:snapshot.materialSources}:{})}:split(snapshot,mg);
return {...r,kind:'priceLock',member:l.entityMember('price_lock',r.price_lock_id),...(effective.materialSources?{materialSources:effective.materialSources}:{}),date,price_lock_id:r.price_lock_id,order_id:r.final_order_id,line_index:0,reserved_mg:r.mg,mg,active:mg>0?1:0,amount:effective.amount,snapshot,allocations:effective.allocations,product:JSON.parse(r.line).name,...Object.fromEntries(PARTIES.map(p=>[p+'_amount',effective.amount===null?null:sum(effective.allocations.filter(a=>a.payer===p),'amount')]))};
});}
function combined(l,date,rows){return [...decorate(l,rows),...reservations(l,date)].sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);}
function returns(l,date){return l.rows('SELECT r.*,p.number,p.customer,p.line FROM price_lock_pool_returns r JOIN price_locks p ON p.id=r.price_lock_id WHERE r.date=? ORDER BY r.created,r.rowid',date).map(r=>({...r,allocations:JSON.parse(r.allocations),...(Allocation.returnSources(l,'lock',r.id)?{materialSources:Allocation.returnSources(l,'lock',r.id)}:{}),product:JSON.parse(r.line).name,sourceKind:'return',cashAmount:0,payer:JSON.parse(r.allocations)[0]?.payer??'owner',sameDay:!!r.same_day,note:r.kind==='leftover'?'锁价余料回池':'锁价退货回料',source_sequence:l.one("SELECT sequence FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?",r.id)?.sequence??0}));}
function fundingParts(purchases,start,amount){let skip=start,left=amount;const result=[];for(const p of purchases)for(const part of (p.allocations??[{payer:p.payer,amount:p.amount}])){if(skip>=part.amount){skip-=part.amount;continue;}const n=Math.min(left,part.amount-skip);if(n)result.push({payer:part.payer,amount:n});left-=n;skip=0;}if(left)throw new Error('锁价料池来源金额不足');return result;}
function allocate(pool,rows,allocatePayers){
if(Allocation.enabled(pool))return Allocation.allocate(pool,rows);
const missing=pool.totalAmount===null||sum(rows,'mg')>pool.totalMg;let mg=0,previous=0;
return rows.map(row=>{
const prefixMg=mg,prefixAmount=previous;mg+=row.mg;const cumulative=missing?null:Calc.poolMaterialAmount(pool.totalAmount,pool.totalMg,mg),amount=cumulative===null?null:cumulative-previous;
const paid=amount===null?{owner_amount:null,assistant_amount:null,assistant2_amount:null}:allocatePayers(pool.purchases.filter(p=>p.amount>0),previous,amount);
let lockSnapshot;
if(row.kind==='priceLock'){
const full=missing?null:Calc.poolMaterialAmount(pool.totalAmount,pool.totalMg,prefixMg+row.reserved_mg)-prefixAmount;
let parts=[];
if(full!==null){
if(prefixMg+row.reserved_mg<=pool.totalMg)parts=fundingParts(pool.purchases.filter(p=>p.amount>0),prefixAmount,full);
else {
// 短交已经释放的尾料可以被前序订单使用;只要求本单实际耗用有真实资金来源。
// 原预留与同日回料的尾段保持相同归属,二者净额为零,不能再次占用可用料。
parts=fundingParts(pool.purchases.filter(p=>p.amount>0),prefixAmount,amount);let tail=full-amount;
const oldTail=row.snapshot.amount===null?[]:split(row.snapshot,row.mg).leftoverAllocations;
for(const p of oldTail){const n=Math.min(tail,p.amount);if(n)parts.push({payer:p.payer,amount:n});tail-=n;}
if(tail)parts.push({payer:oldTail.at(-1)?.payer??row.snapshot.allocations?.at(-1)?.payer??paid.zero_payer??'owner',amount:tail});
}
if(full===0&&!parts.length)parts.push({payer:paid.zero_payer??'owner',amount:0});
}
lockSnapshot={poolId:pool.id,date:pool.date,quantity:row.reserved_mg,amount:full,averageRate:pool.averageRate,allocations:parts,status:full===null?'pending':'allocated',basisAmount:pool.totalAmount,basisMg:pool.totalMg,prefixMg,prefixAmount,rolling:!!pool.rolling};
}
previous=cumulative??0;const result={...row,amount,...paid,...(lockSnapshot?{lockSnapshot}:{})};if(paid.assistant2_amount===undefined)delete result.assistant2_amount;return result;
});
}
function returnRow(l,lock,kind,date,mg,amount,allocations,origin,actor,env,materialSources=null){
if(!mg)return;const old=l.one('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind=?',lock.id,kind),id=old?.id??randomUUID();
if(old)l.run('UPDATE price_lock_pool_returns SET date=?,mg=?,amount=?,allocations=?,origin_pool_id=?,same_day=? WHERE id=?',date,mg,amount,JSON.stringify(allocations),origin,origin===date?1:0,id);
else {l.run('INSERT INTO price_lock_pool_returns VALUES (?,?,?,?,?,?,?,?,?,?,?)',id,lock.id,kind,date,mg,amount,JSON.stringify(allocations),origin,origin===date?1:0,actor.name,env.now());require('./rolling-material-pools').registerSource(l,'lock_return',id);}
Allocation.saveReturn(l,'lock',id,materialSources);
}
function materialAllocations(snapshot,used){const part=split(snapshot,used);if(part.materialSources)return part.materialSources.flatMap(s=>s.allocations.map(p=>({source:'original',quantity:s.quantity,rate:s.averageRate??snapshot.averageRate,amount:p.amount,payer:p.payer,weighted:true,poolId:s.poolId??snapshot.poolId,materialKind:s.kind,materialOwner:s.member})));return part.amount===null?[]:part.allocations.map(p=>({source:'original',quantity:used,rate:snapshot.averageRate,amount:p.amount,payer:p.payer,weighted:true,poolId:snapshot.poolId}));}
function update(l,row,pool,actor,env,{skipJournalOrder=null}={}){
const snapshot=row.lockSnapshot,old=row.snapshot,changed=JSON.stringify(snapshot)!==JSON.stringify(old);if(!changed)return;
const revision=row.revision+1;l.run('UPDATE price_lock_pool_reservations SET amount=?,allocations=?,snapshot=?,revision=?,updated=? WHERE id=?',snapshot.amount,JSON.stringify(snapshot.allocations),JSON.stringify(snapshot),revision,env.now(),row.id);
l.run('UPDATE price_locks SET material_amount=COALESCE(?,material_amount),buy_rate=COALESCE(?,buy_rate),revision=revision+1,updated=? WHERE id=?',snapshot.amount,snapshot.averageRate,env.now(),row.price_lock_id);
const lock=l.one('SELECT * FROM price_locks WHERE id=?',row.price_lock_id),lockedLine=JSON.parse(lock.line);lockedLine.costParts={...lockedLine.costParts,material:snapshot.amount};lockedLine.cost=Object.values(lockedLine.costParts).some(v=>v===null)?null:sum(Object.values(lockedLine.costParts).map(amount=>({amount})),'amount');l.run('UPDATE price_locks SET line=? WHERE id=?',JSON.stringify(lockedLine),lock.id);
if(lock.final_order_id){
const order=l.rawOrder(lock.final_order_id),line=order.lines[0],delivery=JSON.parse(lock.delivery),part=split(snapshot,delivery.original_used_mg),before=line.costParts.material;
const extra=(line.materialAllocations??[]).filter(a=>a.source==='extra');line.materialAllocations=[...materialAllocations(snapshot,delivery.original_used_mg),...extra];line.priceLockPool={...snapshot,quantity:delivery.original_used_mg,amount:part.amount,allocations:part.allocations,...(part.materialSources?{materialSources:part.materialSources}:{}),priceLockId:lock.id};
line.costParts.material=part.amount===null?null:part.amount+sum(extra,'amount');line.cost=Object.values(line.costParts).some(v=>v===null)?null:sum(Object.values(line.costParts).map(amount=>({amount})),'amount');
l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),order.id);
const nextDelivery={...delivery,leftover_cost:part.leftoverCost};l.run('UPDATE price_locks SET delivery=? WHERE id=?',JSON.stringify(nextDelivery),lock.id);
returnRow(l,lock,'leftover',delivery.date,part.leftoverMg,part.leftoverCost,part.leftoverAllocations,snapshot.poolId,actor,env,part.leftoverMaterialSources);
if(order.status==='returned')returnRow(l,lock,'goods',order.returned_date,delivery.original_used_mg,part.amount,part.allocations,snapshot.poolId,actor,env,part.materialSources);
const delta=(line.costParts.material??0)-(before??0);if(order.id!==skipJournalOrder){if(delta&&order.status==='delivered')l.journal(order.id,order.delivered_date,'锁价料池成本调整',0,delta,0);if(delta&&order.status==='returned'){l.journal(order.id,order.delivered_date,'锁价料池原耗用调整',0,delta,0);l.journal(order.id,order.returned_date,'锁价退货成本冲回调整',0,-delta,0);}l.touch(order.id);l.dirty(order.date);}
}
l.dirty(lock.date);l.audit('price-lock:'+lock.id,'锁价料池加权更新',actor,{poolId:pool.id,before:old,after:snapshot});
}
function reserve(l,lock,pool,actor,env){
const available=Allocation.eligible(pool,l.entityMember('price_lock',lock.id)??l.memberFor(actor));
if(available.eligibleRemainingMg<lock.locked_mg)env.fail('当日料池可用克重不足或成本待补,请先核实购料');
const id=randomUUID(),created=env.now();l.run('INSERT INTO price_lock_pool_reservations(id,price_lock_id,pool_id,mg,created,updated) VALUES (?,?,?,?,?,?)',id,lock.id,pool.id,lock.locked_mg,created,created);sequence(l,'priceLock',id);
}
function prepareDelivery(l,lock,date,used,actor,env){const reservation=find(l,lock.id);if(!reservation)return null;const snapshot=reservation.snapshot;if(snapshot.amount===null||snapshot.amount===undefined)env.fail('锁价原料池成本待补,请先核实购料后交付',409);const part=split(snapshot,used);return {...part,snapshot};}
function finishDelivery(l,lock,delivery,actor,env){const r=find(l,lock.id);if(!r)return;const part=split(r.snapshot,delivery.original_used_mg);returnRow(l,lock,'leftover',delivery.date,part.leftoverMg,part.leftoverCost,part.leftoverAllocations,r.pool_id,actor,env,part.leftoverMaterialSources);}
function recordReturn(l,order,date,input,actor,env){
const lock=l.one('SELECT * FROM price_locks WHERE final_order_id=?',order.id),r=lock?find(l,lock.id):null;if(!r)return false;
const line=order.lines[0],destination=input.returnPockets?.[0]??line.pocket;if(!env.selfPockets?.includes(destination))env.fail('料池锁价黄金须退回自有货盘');
const delivery=JSON.parse(lock.delivery),part=split(r.snapshot,delivery.original_used_mg);if(part.amount===null)env.fail('锁价原料池成本待补,不能退货回料',409);
returnRow(l,lock,'goods',date,delivery.original_used_mg,part.amount,part.allocations,r.pool_id,actor,env,part.materialSources);
const extra=(line.materialAllocations??[]).filter(a=>a.source==='extra');if(delivery.extra_mg)returnRow(l,lock,'extra',date,delivery.extra_mg,sum(extra,'amount'),extra.map(a=>({payer:a.payer,amount:a.amount})),'',actor,env);return true;
}
function atomicEdit(l,fn){
l.db.exec('SAVEPOINT price_lock_pool_order_edit');
try{const value=fn();l.db.exec('RELEASE price_lock_pool_order_edit');return value;}
catch(error){l.db.exec('ROLLBACK TO price_lock_pool_order_edit');l.db.exec('RELEASE price_lock_pool_order_edit');throw error;}
}
function editableLock(l,value,actor,env){
if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号修改锁价料池',403);
const id=typeof value==='string'?value:value?.id;l.assertAccess('price_lock',id,actor);
const lock=l.one('SELECT * FROM price_locks WHERE id=?',id);if(!lock)env.fail('锁价单不存在',404);return lock;
}
function affectedDates(reservation,rows,extra=[]){return [...new Set([reservation?.pool_id,...rows.flatMap(row=>[row.origin_pool_id,row.date]),...extra].filter(Boolean))].sort();}
function assertEditDates(l,dates,actor,env){
const rolling=require('./rolling-material-pools');if(!rolling.enabled(l))return;
if(actor.role!=='owner'&&dates.some(date=>date!==env.today()))env.fail('历史锁价料池更正须由麦麦复核',403);
for(const date of dates)rolling.assertDate(l,date,env);
}
function rebuildAffected(l,dates,actor,env,options={}){
if(!dates.length)return;const rolling=require('./rolling-material-pools');
// 共同料池重算需要读取所有成员来源,写入权限仍在外层按本单及日期检查。
return l.scope(null,()=>{
if(rolling.enabled(l)){
for(const date of dates)if(!rolling.isDay(l,date))require('./material-pools').reconcile(l,date,date,actor,env,options);
return rolling.rebuildFrom(l,dates[0],actor,env,{...options,ensureDates:dates});
}
for(const date of dates)require('./material-pools').reconcile(l,date,date,actor,env,options);
},null);
}
// 调用方先保存独立手填的最终成本与商品行;此处只解除池关系,不造采购、现金或实物。
function releaseForOrderEdit(l,value,actor,env,options={}){return atomicEdit(l,()=>{
const lock=editableLock(l,value,actor,env),reservation=find(l,lock.id),rows=l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY rowid',lock.id),dates=affectedDates(reservation,rows);
if(!reservation&&!rows.length)return {released:false,reservation:null,returns:[],affectedDates:[],earliestDate:null};
assertEditDates(l,dates,actor,env);
for(const row of rows)l.run("DELETE FROM material_return_sources WHERE return_kind='lock' AND return_id=?",row.id);
for(const row of rows)l.run("DELETE FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?",row.id);
l.run('DELETE FROM price_lock_pool_returns WHERE price_lock_id=?',lock.id);
if(reservation){l.run("DELETE FROM material_usage_order WHERE kind='priceLock' AND source_id=?",reservation.id);l.run('DELETE FROM price_lock_pool_reservations WHERE price_lock_id=?',lock.id);}
rebuildAffected(l,dates,actor,env,options);
for(const date of dates)l.dirty(date);
return {released:true,reservation,returns:rows,affectedDates:dates,earliestDate:dates[0]};
});}
// 仅挪动交付日时原锁定分厘和付款归属冻结;余料沿原回料身份移日,不能成为第二笔采购。
function moveDeliveryDate(l,value,nextDate,actor,env,{skipJournalOrder=null}={}){return atomicEdit(l,()=>{
const lock=editableLock(l,value,actor,env),reservation=find(l,lock.id);
if(!reservation)return {moved:false,affectedDates:[],earliestDate:null};
const delivery=lock.delivery?JSON.parse(lock.delivery):null;if(!delivery||!lock.final_order_id)env.fail('只有已交付锁价单可以调整交付日期');
const date=env.day(nextDate,lock.date);if(date<lock.date)env.fail('交付日期不能早于锁价日期');
if(date===delivery.date)return {moved:false,affectedDates:[],earliestDate:null};
// 两个交付日都跨过原锁日时,原预留占用完全相同;只从余料实际变动的最早日重建。
const rows=l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY rowid',lock.id),dates=[...new Set([delivery.date,date])].sort();
assertEditDates(l,dates,actor,env);
const updated={...delivery,date};l.run('UPDATE price_locks SET delivery=?,updated=? WHERE id=?',JSON.stringify(updated),env.now(),lock.id);
for(const row of rows.filter(row=>row.kind==='leftover'))l.run('UPDATE price_lock_pool_returns SET date=?,same_day=? WHERE id=?',date,row.origin_pool_id===date?1:0,row.id);
rebuildAffected(l,dates,actor,env,{skipJournalOrder,preservePriceLockIds:[lock.id]});
const rolling=require('./rolling-material-pools');
if(rolling.enabled(l))for(const row of l.rows('SELECT date FROM material_rolling_days WHERE date>=? ORDER BY date',dates[0])){
const pool=rolling.readPool(l,row.date,env,{internal:true});if(pool.shortageMg>0)env.fail('调整交付日期后,'+row.date+'料池短料;原日余料已被其他订单使用,请先核实金料来源后再改交付日期',409);
}
for(const date of dates)l.dirty(date);
return {moved:true,affectedDates:dates,earliestDate:dates[0],delivery:updated};
});}
module.exports={initialize,sequence,decorate,find,detail,reservations,combined,returns,allocate,update,reserve,split,materialAllocations,prepareDelivery,finishDelivery,recordReturn,releaseForOrderEdit,moveDeliveryDate};