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

533 lines
52 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
// 日购料只记录实际采购与成本归属;货盘出入仍由独立库存流水管理。
const {randomUUID,createHash}=require('node:crypto');
const Calc=require('./public/calculations');
const TeamFunds=require('./team-funds');
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'),Allocation=require('./material-pool-allocation');
const ALLOCATION_VERSION=2,ALLOCATION_KEY='material-pool-allocation-version';
function initialize(ledger){
ledger.db.exec(`
CREATE TABLE IF NOT EXISTS material_purchases(
id TEXT PRIMARY KEY,pool_id TEXT NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),amount INTEGER NOT NULL CHECK(amount>0),
payer TEXT NOT NULL CHECK(payer IN ('owner','assistant','assistant2')),note TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,
revision INTEGER NOT NULL DEFAULT 1,deleted_at TEXT NOT NULL DEFAULT '',updated TEXT NOT NULL DEFAULT '');
CREATE TABLE IF NOT EXISTS material_pool_usages(
id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),line_index INTEGER NOT NULL,pool_id TEXT NOT NULL,date TEXT NOT NULL,
mg INTEGER NOT NULL CHECK(mg>0),active INTEGER NOT NULL CHECK(active IN (0,1)),amount INTEGER,owner_amount INTEGER,assistant_amount INTEGER,
revision INTEGER NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL,UNIQUE(order_id,line_index));
CREATE TABLE IF NOT EXISTS material_pool_events(
id TEXT PRIMARY KEY,pool_id TEXT NOT NULL,usage_id TEXT NOT NULL REFERENCES material_pool_usages(id),order_id TEXT NOT NULL REFERENCES orders(id),
date TEXT NOT NULL,kind TEXT NOT NULL,before_value TEXT NOT NULL,after_value TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS material_pool_settlements(
id TEXT PRIMARY KEY,pool_id TEXT NOT NULL,date TEXT NOT NULL,amount INTEGER NOT NULL,note TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS ix_material_purchases_date ON material_purchases(date,created);
CREATE INDEX IF NOT EXISTS ix_material_usages_pool ON material_pool_usages(pool_id,active);
CREATE INDEX IF NOT EXISTS ix_material_settlements_date ON material_pool_settlements(date,created);
CREATE TABLE IF NOT EXISTS material_purchase_shares(purchase_id TEXT PRIMARY KEY REFERENCES material_purchases(id),payer TEXT NOT NULL CHECK(payer IN ('owner','assistant','assistant2')),allocations TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS material_purchase_payment_origins(purchase_id TEXT PRIMARY KEY REFERENCES material_purchases(id),payer_source TEXT NOT NULL CHECK(payer_source IN ('purchase')));
CREATE TABLE IF NOT EXISTS material_usage_parties(usage_id TEXT PRIMARY KEY REFERENCES material_pool_usages(id),assistant2_amount INTEGER);
`);
// 旧采购的原始金额、日期、录入人和时间保持原值,只增补并发版本及软删除字段。
const columns=ledger.rows('PRAGMA table_info(material_purchases)').map(row=>row.name);
for(const [name,definition] of Object.entries({revision:'INTEGER NOT NULL DEFAULT 1',deleted_at:"TEXT NOT NULL DEFAULT ''",updated:"TEXT NOT NULL DEFAULT ''"})){
if(!columns.includes(name))ledger.db.exec(`ALTER TABLE material_purchases ADD COLUMN ${name} ${definition}`);
}
const schema=ledger.one("SELECT sql FROM sqlite_master WHERE type='table' AND name='material_purchases'").sql;
if(!schema.includes("'assistant2'")){
if(ledger.db.isTransaction)throw new Error('购料付款人结构升级须在启动阶段完成');
const foreignKeys=ledger.one('PRAGMA foreign_keys').foreign_keys;
if(foreignKeys)ledger.db.exec('PRAGMA foreign_keys=OFF');
try{atomic(ledger,()=>{
// 只扩展原表的付款人约束;保留所有字段、原始值与rowid,确保旧FIFO顺序不变。
const upgraded=schema.replace(/CREATE TABLE\s+(?:"material_purchases"|material_purchases)/i,'CREATE TABLE material_purchases_team_upgrade').replace(/payer\s+IN\s*\(\s*'owner'\s*,\s*'assistant'\s*\)/i,"payer IN ('owner','assistant','assistant2')");
if(upgraded===schema||!upgraded.includes("'assistant2'"))throw new Error('购料付款人表结构不兼容,未修改原采购');
const supporting=ledger.rows("SELECT sql FROM sqlite_master WHERE tbl_name='material_purchases' AND type IN ('index','trigger') AND sql IS NOT NULL ORDER BY type,name");
ledger.db.exec(upgraded);
ledger.db.exec('INSERT INTO material_purchases_team_upgrade(rowid,'+ledger.rows('PRAGMA table_info(material_purchases)').map(row=>'"'+row.name+'"').join(',')+') SELECT rowid,* FROM material_purchases');
ledger.db.exec('DROP TABLE material_purchases;ALTER TABLE material_purchases_team_upgrade RENAME TO material_purchases');
for(const row of supporting)ledger.db.exec(row.sql);
if(ledger.rows('PRAGMA foreign_key_check').length)throw new Error('购料付款人升级关联核对失败,原采购已回滚');
});}finally{if(foreignKeys)ledger.db.exec('PRAGMA foreign_keys=ON');}
}
Rolling.initialize(ledger);
LockPools.initialize(ledger);Allocation.initialize(ledger);
}
function atomic(ledger,fn){
ledger.db.exec('SAVEPOINT material_pool_action');
try{const value=fn();ledger.db.exec('RELEASE material_pool_action');return value;}
catch(error){ledger.db.exec('ROLLBACK TO material_pool_action');ledger.db.exec('RELEASE material_pool_action');throw error;}
}
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 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;
}
const purchaseAllocations=purchase=>purchase.allocations??[{payer:purchase.payer,amount:purchase.amount}];
// 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,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}:{}),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;
const byPayer={};
for(const payer of (purchases.some(row=>purchaseAllocations(row).some(part=>part.payer==='assistant2'))||usages.some(row=>row.assistant2_amount)?PARTIES:['owner','assistant'])){
const purchased=sum(purchases.flatMap(purchaseAllocations).filter(row=>row.payer===payer),'amount');
const consumed=pending?null:sum(active,payer+'_amount');
byPayer[payer]={purchased,consumed,remaining:pending?null:purchased-consumed};
}
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,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}};
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;
const historical=Rolling.enabled(ledger)&&pool.date<new Intl.DateTimeFormat('sv-SE',{timeZone:'Asia/Shanghai'}).format(new Date());
const permissions=row=>({canEdit:!historical&&!row.recovery_id&&(!row.sourceKind||row.sourceKind==='purchase'),canRequestChange:historical&&!row.recovery_id&&(!row.sourceKind||row.sourceKind==='purchase'),ownerReviewRequired:historical});
if(!ledger.actor||ledger.actor.role==='owner'){const purchases=pool.purchases.map(row=>({...row,...permissions(row),...(ledger.entityMember('material_purchase',row.id)?{member:ledger.entityMember('material_purchase',row.id)}:{})}));return {...pool,purchases,...(pool.rolling?{todayPurchases:{...pool.todayPurchases,items:purchases.filter(row=>row.sourceKind==='purchase')}}:{}),legacyReadOnly:true};}
const self=ledger.memberFor(ledger.actor),own=(kind,id)=>ledger.entityMember(kind,id)===self;
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,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:[]};
const pools=allIds(ledger).map(id=>internalPool(ledger,id,env)),pendingCount=pools.filter(row=>row.settlement.pending).length;
const known=pools.filter(row=>!row.settlement.pending),assistantInventoryCredit=sum(known.map(row=>row.settlement),'assistantInventoryCredit'),transferred=sum(pools.map(row=>row.settlement),'transferred');
if(ledger.teamMode&&ledger.actor?.role==='assistant')return {legacyReadOnly:true,settlementDue:null,knownSettlementDue:null,pendingCount,pools:[]};
return {...(ledger.teamMode?{legacyReadOnly:true}:{}),assistantInventoryCredit:pendingCount?null:assistantInventoryCredit,knownAssistantInventoryCredit:assistantInventoryCredit,transferred,
settlementDue:pendingCount?null:-assistantInventoryCredit-transferred,knownSettlementDue:-assistantInventoryCredit-transferred,pendingCount,
pools:pools.map(row=>({id:row.id,date:row.date,...row.settlement}))};
}
function list(ledger,query,env){
if(Rolling.enabled(ledger))return Rolling.list(ledger,query,env);
const date=env.day(query.date??query.to??env.today()),from=env.day(query.from??(query.date||query.to?date:'2000-01-01'));
if(from>date)env.fail('开始日期不能晚于结束日期');
const rows=allIds(ledger).filter(id=>id>=from&&id<=date).map(id=>readPool(ledger,id,env)),pendingCount=rows.filter(row=>row.status==='pending').length;
return {from,date,rows,rolling:Rolling.status(ledger,env),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 snapshotAllocations(row,pool){
const amount=row.amount??null,allocations=amount===null?[]:PARTIES.map(payer=>({payer,amount:row[payer+'_amount']??0})).filter(part=>part.amount>0);
// 金额为0的极小克重仍保留一条来源,不能被误判为未分配。
if(amount===0&&!allocations.length)allocations.push({payer:row.zero_payer??PARTIES.find(payer=>pool.byPayer[payer]?.purchased)??'owner',amount:0});
return allocations;
}
function applySnapshot(line,row,pool,status){
const amount=row.amount??null,allocations=snapshotAllocations(row,pool);
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('货品成本超出支持范围');
line.cost=Object.keys(Calc.costLabels).some(key=>line.costParts[key]==null)?null:knownCost;
return line;
}
// 当天料费仍按总金额/总克重加权。FIFO 只切整数分金额区间,不使用采购批次的克价或克重。
// purchases 必须沿用 created,rowid 的稳定顺序;fromAmount 是前序商品已结转的加权料费。
function allocatePayers(purchases,fromAmount,amount){
const includesThird=purchases.some(purchase=>purchaseAllocations(purchase).some(part=>part.payer==='assistant2'));
purchases=purchases.flatMap(purchase=>{
const parts=purchaseAllocations(purchase);
if(!Array.isArray(parts)||parts.some(part=>!PARTIES.includes(part.payer)||!Number.isSafeInteger(part.amount)||part.amount<=0)||sum(parts,'amount')!==purchase.amount)throw new Error('日购料资金份额不守恒');
return parts;
});
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,assistant2Amount=0,zeroPayer='owner',foundZero=false;
for(const purchase of purchases){
if(!Number.isSafeInteger(purchase.amount)||purchase.amount<=0||!PARTIES.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 if(purchase.payer==='assistant')assistantAmount+=allocated;else assistant2Amount+=allocated;
left-=allocated;skip=0;
}
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 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)=>{
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?LockPools.decorate(ledger,ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId)):[];
const lastSequence=ledger.one('SELECT COALESCE(MAX(sequence),0) AS value FROM material_usage_order').value,created=env.now();
for(const [id,group] of groups){
const pool=internalPool(ledger,id,env);
const usages=pool.usages.filter(usage=>usage.active)
.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,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)
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,...(row.assistant2_amount!==undefined?{assistant2Amount:row.assistant2_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,...args){const run=()=>reconcileInternal(ledger,...args);return typeof ledger.scope==='function'?ledger.scope(null,run,null):run();}
function reconcileInternal(ledger,id,date,actor,env,{skipJournalOrder=null,allocationOnly=false,migration=null}={}){
if(Rolling.isDay(ledger,id))return Rolling.reconcile(ledger,id,actor,env,{skipJournalOrder});
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,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)||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;
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);
if(assistant2Amount!==undefined)ledger.run('INSERT INTO material_usage_parties VALUES (?,?) ON CONFLICT(usage_id) DO UPDATE SET assistant2_amount=excluded.assistant2_amount',usage.id,assistant2Amount);
else ledger.run('DELETE FROM material_usage_parties WHERE usage_id=?',usage.id);
usageEvent(ledger,usage,beforeValue,afterValue,allocationOnly?'垫付归属FIFO升级':pending?'成本转待补':usage.amount===null?'补齐料费':'加权料费调整',date,actor,env);
}
// 订单快照中原先的料费是上次已经计入利润的值;新交付单的整单交付流水稍后统一记录。
const oldAmount=line.costParts?.material??0;
if(allocationOnly&&(line.costParts?.material??null)!==amount)env.fail('历史订单料费快照与日购料用量不一致,升级已撤回,请维护者核对');
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});
}
for(const [orderId,update] of orders){
ledger.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(update.order.lines),orderId);
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=internalPool(ledger,id,env);
for(const {order} of orders.values()){
for(const line of order.lines)if(line.materialPool?.poolId===id)line.materialPool.revision=finalPool.revision;
ledger.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),order.id);
}
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 startPurchaseFunds(ledger,row,actor,env,{legacy=false}={}){
if(!ledger.teamMode)return;
if(!ledger.entityMember('material_purchase',row.id))ledger.assignMember('material_purchase',row.id,ledger.memberFor(actor));
TeamFunds.activate(ledger,'material_purchase',row.id,{legacy},actor,env);
}
function purchase(ledger,input,actor,env,{member=null,source=null}={}){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');
if(Rolling.enabled(ledger))Rolling.assertDate(ledger,date,env);
const payer=env.pick(input.payer,PARTIES,'采购付款人'),note=env.text(input.note,'采购备注',200,true),id=randomUUID();
const previous=internalPool(ledger,date,env);if(previous.totalMg+mg>LIMIT||previous.totalAmount+amount>LIMIT)env.fail('同日购料累计超出支持范围');
const created=env.now();
ledger.run('INSERT INTO material_purchases(id,pool_id,date,mg,amount,payer,note,actor,created,updated) VALUES (?,?,?,?,?,?,?,?,?,?)',id,date,date,mg,amount,payer,note,actor.name,created,created);
if(Rolling.enabled(ledger))Rolling.registerSource(ledger,'purchase',id);
markPurchasePayer(ledger,id);
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);
const pool=reconcile(ledger,date,date,actor,env);
ledger.audit('material-pool:'+date,'登记实际购料',actor,{id,date,mg,amount,payer,note,averageRate:pool.averageRate,
...(source?{recovery_id:source.recoveryId,cashAmount:source.cashAmount,offsetAmount:source.offsetAmount,allocations:source.allocations}:{}),
notice:source?'回收购料按最终总额入池;实际现金仅记净付款,非现金抵扣按业务成员计入库存资金份额':'实际采购支出只记本条;订单仅结转消耗成本,不重复记付款'});
ledger.audit('material-purchase:'+id,'登记实际购料',actor,{before:null,after:purchaseValue(readPurchase(ledger,id,env))});
TeamFunds.syncSource(ledger,'material_purchase',id,actor,env);
return {id,poolId:date,pool:visiblePool(ledger,pool)};
});}
function purchaseValue(row){
return {...Object.fromEntries(['id','pool_id','date','mg','amount','payer','note','actor','created','revision','deleted_at','updated'].map(key=>[key,row[key]]))};
}
function readPurchase(ledger,id,env){
const row=ledger.one('SELECT * FROM material_purchases WHERE id=?',id);
if(!row)env.fail('这笔购料记录不存在',404);
return actualPurchase(ledger,row);
}
function purchaseDetail(ledger,id,env){
if(ledger.teamMode&&ledger.actor)ledger.assertAccess('material_purchase',id,ledger.actor);
const row=readPurchase(ledger,id,env),purchase={...purchaseValue(row),...(row.recovery_id?{recovery_id:row.recovery_id,cashAmount:row.cashAmount,offsetAmount:row.offsetAmount,actualRate:Math.round(row.amount*1000/row.mg),canEdit:false}:{} )};
const history=ledger.rows('SELECT action,actor,detail,created FROM audit WHERE entity=? ORDER BY id DESC LIMIT 100','material-purchase:'+id)
.map(row=>({...row,detail:JSON.parse(row.detail)}));
return {purchase:{...purchase,...(Rolling.enabled(ledger)&&purchase.date!==env.today()?{ownerReviewRequired:true,canRequestChange:!purchase.recovery_id}:{})},pool:readPool(ledger,purchase.pool_id,env),history};
}
function changeablePurchase(ledger,id,input,actor,env){
activeActor(actor,env);
if(ledger.teamMode)ledger.assertAccess('material_purchase',id,actor);
if(!input||typeof input!=='object'||Array.isArray(input))env.fail('购料记录格式无效');
const row=readPurchase(ledger,id,env);
if(row.recovery_id)env.fail('这笔购料关联回收/置换单,不能独立修改或删除,请保留原关联记录',409);
if(row.deleted_at)env.fail('这笔购料记录已删除,请刷新列表',409);
if(Rolling.enabled(ledger))Rolling.assertDate(ledger,row.date,env);
if(!Number.isSafeInteger(input.revision)||input.revision!==row.revision)env.fail('这笔购料记录有新变动,请重新打开后操作',409);
return row;
}
function editPurchase(ledger,id,input,actor,env){return atomic(ledger,()=>{
const before=changeablePurchase(ledger,id,input,actor,env),date=env.day(input.date),mg=env.weight(input.grams,'采购克重'),amount=env.money(input.total,'采购总金额');
if(mg<=0||amount<=0)env.fail('采购克重和采购总金额必须大于0');
if(Rolling.enabled(ledger))Rolling.assertDate(ledger,date,env);
const payer=env.pick(input.payer,PARTIES,'采购付款人'),note=env.text(input.note,'采购备注',200,true),target=internalPool(ledger,date,env);
const sameDate=before.pool_id===date;
if(target.totalMg-(sameDate?before.mg:0)+mg>LIMIT||target.totalAmount-(sameDate?before.amount:0)+amount>LIMIT)env.fail('同日购料累计超出支持范围');
startPurchaseFunds(ledger,before,actor,env,{legacy:true});
ledger.run('UPDATE material_purchases SET pool_id=?,date=?,mg=?,amount=?,payer=?,note=?,revision=revision+1,updated=? WHERE id=?',date,date,mg,amount,payer,note,env.now(),id);
markPurchasePayer(ledger,id);
// 改采购日不迁移已交付用量。原池不足时关联单待补,新日期的料留在新池。
if(!sameDate)reconcile(ledger,before.pool_id,date,actor,env);
const pool=reconcile(ledger,date,date,actor,env),after=readPurchase(ledger,id,env);
ledger.dirty(before.date);ledger.dirty(date);
ledger.audit('material-purchase:'+id,'修改实际购料',actor,{before:purchaseValue(before),after:purchaseValue(after)});
TeamFunds.syncSource(ledger,'material_purchase',id,actor,env);
return {id,poolId:date,previousPoolId:before.pool_id,pool:visiblePool(ledger,pool)};
});}
function deletePurchase(ledger,id,input,actor,env){return atomic(ledger,()=>{
const before=changeablePurchase(ledger,id,input,actor,env),deleted=env.now();
startPurchaseFunds(ledger,before,actor,env,{legacy:true});
ledger.run('UPDATE material_purchases SET deleted_at=?,revision=revision+1,updated=? WHERE id=?',deleted,deleted,id);
const pool=reconcile(ledger,before.pool_id,env.today(),actor,env),after=readPurchase(ledger,id,env);
ledger.dirty(before.date);
ledger.audit('material-purchase:'+id,'删除实际购料',actor,{before:purchaseValue(before),after:purchaseValue(after)});
TeamFunds.syncSource(ledger,'material_purchase',id,actor,env);
return {id,poolId:before.pool_id,previousPoolId:before.pool_id,pool:visiblePool(ledger,pool),deleted:true};
});}
function deliver(ledger,order,date,actor,env){
const pools=new Set();
order.lines.forEach((line,index)=>{
if(line.costMaterial?.mode!=='pool')return;
if(line.materialAllocations)env.fail('锁价采购与日购料不能混用');
const id=poolId(line.costMaterial.poolId,env);if(id>order.date)env.fail('日购料日期不能晚于订单日期');
if(ledger.one('SELECT id FROM material_pool_usages WHERE order_id=? AND line_index=?',order.id,index))env.fail('本商品已登记日购料消耗,不能重复交付',409);
const usage={id:randomUUID(),order_id:order.id,line_index:index,pool_id:id,date,mg:consumptionMg(line),active:1,amount:null,owner_amount:null,assistant_amount:null,revision:1,created:env.now(),updated:env.now()};
ledger.run('INSERT INTO material_pool_usages VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',...Object.values(usage));
LockPools.sequence(ledger,'order',usage.id);
usageEvent(ledger,usage,null,usageValue(usage),'交付占用',date,actor,env);pools.add(id);
});
for(const id of pools)reconcile(ledger,id,date,actor,env,{skipJournalOrder:order.id});
return ledger.rawOrder(order.id);
}
function release(ledger,order,date,actor,env,{kind='实物退回释放'}={}){
if(Rolling.enabled(ledger))return Rolling.release(ledger,order,date,actor,env,{kind});
const usages=ledger.rows('SELECT * FROM material_pool_usages WHERE order_id=? AND active=1',order.id),pools=new Set();
for(const usage of usages){
const next={...usage,active:0,revision:usage.revision+1};
ledger.run('UPDATE material_pool_usages SET active=0,revision=revision+1,updated=? WHERE id=?',env.now(),usage.id);
usageEvent(ledger,usage,usageValue(usage),usageValue(next),kind,date,actor,env);pools.add(usage.pool_id);
}
if(ledger.one('SELECT r.id FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id WHERE p.final_order_id=?',order.id))pools.add(date);
for(const id of pools)reconcile(ledger,id,date,actor,env);
}
// 整单修改复用原行的消耗身份;删除、重排、换池和手填成本都留前后事件。
function adjust(ledger,order,date,actor,env){
if(Rolling.enabled(ledger)&&order.lines.some(line=>line.costMaterial?.mode==='pool'))Rolling.assertDate(ledger,order.date,env);
const existing=ledger.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY line_index',order.id),affected=new Set();let consumptionChanged=false;
const indices=new Set([...existing.map(row=>row.line_index),...order.lines.map((_,index)=>index)]);
for(const index of indices){
const previous=existing.find(row=>row.line_index===index),line=order.lines[index],pooled=line?.costMaterial?.mode==='pool';
if(!pooled){
if(previous?.active){
const next={...previous,active:0,revision:previous.revision+1};
ledger.run('UPDATE material_pool_usages SET active=0,revision=revision+1,updated=? WHERE id=?',env.now(),previous.id);
usageEvent(ledger,previous,usageValue(previous),usageValue(next),'整单修改释放',date,actor,env);affected.add(previous.pool_id);consumptionChanged=true;
}
continue;
}
if(line.materialAllocations)env.fail('锁价采购与日购料不能混用');
const id=poolId(line.costMaterial.poolId,env);if(id>order.date)env.fail('日购料日期不能晚于订单日期');
affected.add(id);if(previous?.active)affected.add(previous.pool_id);
if(previous){
const changed=!previous.active||previous.pool_id!==id||previous.mg!==line.quantity||previous.date!==date;
if(changed){
const next={...previous,pool_id:id,date,mg:line.quantity,active:1,revision:previous.revision+1};
ledger.run('UPDATE material_pool_usages SET pool_id=?,date=?,mg=?,active=1,revision=revision+1,updated=? WHERE id=?',id,date,line.quantity,env.now(),previous.id);
usageEvent(ledger,next,usageValue(previous),usageValue(next),'整单修改消耗',date,actor,env);consumptionChanged=true;
}
}else{
const row={id:randomUUID(),order_id:order.id,line_index:index,pool_id:id,date,mg:line.quantity,active:1,amount:null,owner_amount:null,assistant_amount:null,revision:1,created:env.now(),updated:env.now()};
ledger.run('INSERT INTO material_pool_usages VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',...Object.values(row));
LockPools.sequence(ledger,'order',row.id);
usageEvent(ledger,row,null,usageValue(row),'整单修改新增消耗',date,actor,env);consumptionChanged=true;
}
}
const rebuild=Rolling.enabled(ledger)&&ledger.rollingHistorical&&consumptionChanged;
// 历史改单只在耗用实变时重建一次;旧模式池须先更新原耗用金额,滚动日期由整条结转链统一重算。
for(const id of affected)if(!rebuild||!Rolling.isDay(ledger,id))reconcile(ledger,id,date,actor,env,{skipJournalOrder:order.id});
if(rebuild)Rolling.rebuild(ledger,actor,env);
return ledger.rawOrder(order.id);
}
function reassign(ledger,order,input,actor,env){return atomic(ledger,()=>{
if(Rolling.enabled(ledger)&&!ledger.rollingHistorical)env.fail('统一料池不再切换历史料价日期,历史更正须提交麦麦复核',409);
activeActor(actor,env);
if(order.status!=='delivered')env.fail('只可为已交付订单调整日购料来源');
if(input.revision!==order.revision)env.fail('订单有新变动,请重新打开后调整购料日期',409);
if(!Array.isArray(input.pools)||input.pools.length!==order.lines.length)env.fail('请逐行指定日购料日期');
const date=env.day(input.date||env.today(),order.date),affected=new Set();
for(const [index,line] of order.lines.entries()){
const target=input.pools[index];
if(line.costMaterial?.mode!=='pool'){if(target!==null&&target!==undefined)env.fail('手填成本不能改为日购料,须在开单时选择');continue;}
const id=poolId(target,env);if(id>order.date)env.fail('日购料日期不能晚于订单日期');
const row=ledger.one('SELECT * FROM material_pool_usages WHERE order_id=? AND line_index=? AND active=1',order.id,index);if(!row)env.fail('日购料消耗记录不存在');
if(id===row.pool_id)continue;
affected.add(row.pool_id);affected.add(id);
const next={...row,pool_id:id,revision:row.revision+1};
ledger.run('UPDATE material_pool_usages SET pool_id=?,revision=revision+1,updated=? WHERE id=?',id,env.now(),row.id);
usageEvent(ledger,next,usageValue(row),usageValue(next),'调整购料日期',date,actor,env);line.costMaterial.poolId=id;
}
ledger.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),order.id);
for(const id of affected)reconcile(ledger,id,date,actor,env);
ledger.audit(order.id,'调整日购料来源',actor,{date,pools:input.pools});return {id:order.id};
});}
function settle(ledger,id,input,actor,env){return atomic(ledger,()=>{
if(ledger.teamMode&&ledger.one("SELECT p.id FROM material_purchases p JOIN team_fund_sources s ON s.source_id=p.id AND s.kind='material_purchase' WHERE p.pool_id=?",id))env.fail('三人购料请到成员往来登记双方实际转账',409);
activeActor(actor,env);const pool=readPool(ledger,id,env),date=env.day(input.date||env.today(),pool.date);
if(typeof input.revision!=='string'||input.revision!==pool.revision)env.fail('日购料记录有新变动,请刷新核对后再结算',409);
if(pool.settlement.pending)env.fail('日购料尚有缺口,成本补齐前不能结算垫款');
if(input.verified!==true)env.fail('请核实双方实际转账后登记');
const amount=env.money(input.amount,'购料垫款结算金额'),direction=env.pick(input.direction,['toOwner','toAssistant'],'购料结算方向'),signed=direction==='toOwner'?amount:-amount,due=pool.settlement.settlementDue;
if(amount<=0||Math.sign(due)!==Math.sign(signed)||amount>Math.abs(due))env.fail('购料结算方向或金额超过当前应结余额');
const latest=ledger.one('SELECT MAX(date) AS date FROM material_pool_settlements WHERE pool_id=?',pool.id)?.date;
if(latest&&date<latest)env.fail('购料结算日期不能早于最近转账日期');
const eventId=randomUUID(),note=env.text(input.note,'购料结算备注',150,true);
ledger.run('INSERT INTO material_pool_settlements VALUES (?,?,?,?,?,?,?)',eventId,pool.id,date,signed,note,actor.name,env.now());
ledger.dirty(date);ledger.audit('material-pool:'+pool.id,'购料剩余垫款结算',actor,{id:eventId,date,amount:signed,note});
return {id:eventId,poolId:pool.id,settlement:readPool(ledger,pool.id,env).settlement};
});}
function reporting(ledger,query,env){
const to=env.day(query.to??query.date??env.today()),from=env.day(query.from??to);if(from>to)env.fail('开始日期不能晚于结束日期');
const purchases=ledger.rows("SELECT * FROM material_purchases WHERE date>=? AND date<=? AND deleted_at='' ORDER BY date,created,rowid",from,to).map(row=>actualPurchase(ledger,row));
const restricted=ledger.teamMode&&ledger.actor?.role==='assistant',self=restricted?ledger.memberFor(ledger.actor):null;
return {from,to,purchases:ledger.visibleRows('material_purchase',purchases),
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,quote};