From 499b84a7a679e2d1a7a1e64222d022a119dd771e Mon Sep 17 00:00:00 2001 From: summer Date: Fri, 23 Oct 2026 00:14:29 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=A5=E8=B4=AD=E6=96=99=E5=9E=AB=E6=AC=BE?= =?UTF-8?q?=E6=8C=89=E9=87=87=E8=B4=AD=E5=85=88=E5=90=8E=E6=89=A3=E5=87=8F?= =?UTF-8?q?=E5=B9=B6=E8=BF=81=E7=A7=BB=E5=8E=86=E5=8F=B2=E5=BD=92=E5=B1=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 新账系统/ledger.js | 11 +- 新账系统/material-pools.js | 181 +++++++++++++--- 新账系统/order-edit.js | 2 +- 新账系统/public/calculations.js | 34 ++- 新账系统/public/material-pools-ui.js | 51 +++-- 新账系统/server.js | 38 +++- 新账系统/test/material-pool-fifo.test.js | 195 ++++++++++++++++++ .../test/material-pool-preview-ui.test.js | 109 ++++++++++ 新账系统/test/material-pool-reporting.test.js | 16 +- 新账系统/test/material-pools.test.js | 4 +- 新账系统/test/material-purchase-edit.test.js | 2 +- 新账系统/使用说明.md | 22 +- 新账系统/维护与部署.md | 33 ++- 13 files changed, 608 insertions(+), 90 deletions(-) create mode 100644 新账系统/test/material-pool-fifo.test.js create mode 100644 新账系统/test/material-pool-preview-ui.test.js diff --git a/新账系统/ledger.js b/新账系统/ledger.js index e558523..4605ba6 100644 --- a/新账系统/ledger.js +++ b/新账系统/ledger.js @@ -152,9 +152,9 @@ class Ledger { o.sync=this.one('SELECT revision,done_revision,error,updated FROM sync WHERE entity=?','order:'+id)||null; return o; } - validateLines(lines,historicalLines=[],businessDate=null){ + validateLines(lines,historicalLines=[],businessDate=null,{orderId=null}={}){ if(!Array.isArray(lines)||!lines.length||lines.length>60)fail('每单需要1~60行商品'); - return lines.map((l,i)=>{ + const prepared=lines.map((l,i)=>{ const unit=pick(l.unit,['g','件'],'单位');const qty=unit==='g'?weight(l.quantity,`第${i+1}行克重`):fixed(l.quantity,1,'件数')/10; if(qty<=0||(unit==='件'&&!Number.isInteger(qty)))fail('克重必须大于0,件数必须为正整数'); const pocket=l.pocket?pick(l.pocket,POCKETS,'货盘'):'';if(pocket&&unit!=='g')fail('货盘库存按克重管理,按件商品请选外配/不扣黄金'); @@ -169,8 +169,9 @@ class Ledger { const costPayers=Calc.costPayers(l.costPayers===undefined?historicalLines?.[i]?.costPayers:l.costPayers); const cost=breakdown?breakdown.total:(l.cost===''||l.cost==null?null:money(l.cost,'货品成本')); const priceNote=pricing?`金价 ${(pricing.goldPrice/100).toFixed(2)}元/克 + 工费 ${(pricing.laborRate/100).toFixed(2)}元/${pricing.laborMode==='gram'?'克':`件 × ${pricing.pieces}件`}`:text(l.priceNote,'客户单价说明',100,true); - return MaterialPools.prepareLine(this,{name,code:text(l.code,'商品编号',30,true),unit,quantity:qty,pocket,payer:pick(l.payer,['owner','assistant'],'成本垫资人'),...(costPayers?{costPayers}:{}),cost,...(breakdown?{costParts:breakdown.parts,costMaterial:breakdown.costMaterial,costLabor:breakdown.costLabor}:{}),sale:priced.sale,baseSale:priced.baseSale,charges:priced.charges,pricingMode:mode,...(pricing?{goldPrice:pricing.goldPrice,laborRate:pricing.laborRate,laborMode:pricing.laborMode,pieces:pricing.pieces}:{}),priceNote},businessDate,priceLockEnv); + return {name,code:text(l.code,'商品编号',30,true),unit,quantity:qty,pocket,payer:pick(l.payer,['owner','assistant'],'成本垫资人'),...(costPayers?{costPayers}:{}),cost,...(breakdown?{costParts:breakdown.parts,costMaterial:breakdown.costMaterial,costLabor:breakdown.costLabor}:{}),sale:priced.sale,baseSale:priced.baseSale,charges:priced.charges,pricingMode:mode,...(pricing?{goldPrice:pricing.goldPrice,laborRate:pricing.laborRate,laborMode:pricing.laborMode,pieces:pricing.pieces}:{}),priceNote}; }); + return MaterialPools.prepareLines(this,prepared,businessDate,priceLockEnv,{orderId}); } paperNumber(date,allocate=false){ day(date);const prefix=date.replaceAll('-','');let seq=this.meta('paper-sequence',0); @@ -370,11 +371,11 @@ class Ledger { const result=Calc.purchaseCosts({name:l.name,costParts:value.parts||value,costMaterial:value.costMaterial,costLabor:value.costLabor,unit:l.unit,quantity:l.unit==='g'?(l.quantity/1000).toFixed(3):l.quantity});if(result.total===null&&result.costMaterial.mode!=='pool')fail('请补齐每项成本;没有的项目填0'); l.costParts=result.parts;l.cost=result.total;l.costMaterial=result.costMaterial;l.costLabor=result.costLabor;l.payer=payer;if(costPayers)l.costPayers=costPayers; if(l.costMaterial.mode==='pool'){ - MaterialPools.prepareLine(this,l,o.date,priceLockEnv); if(['labor','accessories','other'].some(key=>l.costParts[key]==null))fail('请补齐每项成本;没有的项目填0'); }else delete l.materialPool; }else{if(l.costParts)fail('这行已拆分成本,请逐项填写');l.cost=money(value,'货品成本');} }); + MaterialPools.prepareLines(this,o.lines,o.date,priceLockEnv,{orderId:id}); this.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(o.lines),id); } else if(action==='complete'){ if(o.status!=='confirmed')fail('只有待交付订单可以完成交付',409); @@ -475,6 +476,8 @@ class Ledger { deliverPriceLock(id,input,actor){return PriceLocks.deliver(this,id,input,actor,priceLockEnv);} priceLockReporting(query={}){return PriceLocks.reporting(this,query,priceLockEnv);} createMaterialPurchase(input,actor){return MaterialPools.purchase(this,input,actor,priceLockEnv);} + materialPoolAllocationStatus(){return MaterialPools.allocationStatus(this);} + migrateMaterialPoolAllocation(actor,options={}){return MaterialPools.migrateAllocation(this,actor,priceLockEnv,options);} materialPurchaseDetail(id){return MaterialPools.purchaseDetail(this,id,priceLockEnv);} editMaterialPurchase(id,input,actor){return MaterialPools.editPurchase(this,id,input,actor,priceLockEnv);} deleteMaterialPurchase(id,input,actor){return MaterialPools.deletePurchase(this,id,input,actor,priceLockEnv);} diff --git a/新账系统/material-pools.js b/新账系统/material-pools.js index 9708373..9118ec3 100644 --- a/新账系统/material-pools.js +++ b/新账系统/material-pools.js @@ -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.createdb.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:versionrow.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}; diff --git a/新账系统/order-edit.js b/新账系统/order-edit.js index 5c3c1c2..6aa92a7 100644 --- a/新账系统/order-edit.js +++ b/新账系统/order-edit.js @@ -145,7 +145,7 @@ function edit(ledger,id,input,actor,env){return atomic(ledger,()=>{ } if(!Array.isArray(input.fee_items))env.fail('请完整带入本单所有实际费用后再修改,不能遗漏额外费用'); if(input.lines?.some(line=>line.materialAllocations!==undefined))env.fail('普通订单不能带入锁价采购分配'); - const date=env.day(input.date),lines=ledger.validateLines(input.lines,order.lines,date),discount=env.money(input.discount??'0','整单优惠'); + const date=env.day(input.date),lines=ledger.validateLines(input.lines,order.lines,date,{orderId:id}),discount=env.money(input.discount??'0','整单优惠'); const rounding=input.rounding_mode??order.rounding_mode,total=Calc.orderTotal(lines.map(line=>line.sale),discount,rounding).total; const fees=ledger.validateFees(input.fee_items.map(fee=>({...fee,status:'estimated'}))); ledger.validateCompletedCosts(lines,fees); diff --git a/新账系统/public/calculations.js b/新账系统/public/calculations.js index ee6abca..c39f32c 100644 --- a/新账系统/public/calculations.js +++ b/新账系统/public/calculations.js @@ -122,6 +122,38 @@ if(amount>100000000000n)throw new Error('日购料成本超出支持范围'); return Number(amount); } + // 同池先按完整耗用顺序累计取整,再取相邻差额;编辑沿用原行身份,新增行追加。 + function poolMaterialPreview(pool,entries,{orderId=null,allUsages=pool.usages||[]}={}){ + const valid=value=>Number.isSafeInteger(value)&&value>=0&&value<=100000000000; + if(!valid(pool.totalAmount)||!valid(pool.totalMg)||!Array.isArray(entries)||!Array.isArray(pool.usages)||!Array.isArray(allUsages))throw new Error('日购料预估记录无效,请刷新料价'); + const indices=new Set(); + for(const entry of entries){ + if(!Number.isSafeInteger(entry.lineIndex)||entry.lineIndex<0||indices.has(entry.lineIndex)||!valid(entry.mg)||!entry.mg)throw new Error('日购料预估克重或商品行无效'); + indices.add(entry.lineIndex); + } + const originals=orderId?allUsages.filter(usage=>usage.order_id===orderId):[]; + const usages=pool.usages.filter(usage=>usage.active&&usage.order_id!==orderId).map(usage=>({...usage})); + const usedMg=usages.reduce((total,usage)=>total+usage.mg,0),wantedMg=entries.reduce((total,entry)=>total+entry.mg,0); + const covered=pool.totalMg>0&&usedMg+wantedMg<=pool.totalMg,amounts=Object.fromEntries(entries.map(entry=>[entry.lineIndex,null])); + for(const entry of entries){ + const original=originals.find(usage=>usage.line_index===entry.lineIndex); + usages.push({...original,mg:entry.mg,previewIndex:entry.lineIndex,appended:!original}); + } + for(const usage of usages){ + if(!valid(usage.mg)||!usage.mg||!usage.appended&&(!Number.isSafeInteger(usage.fifo_sequence)||usage.fifo_sequence<1||typeof usage.created!=='string'||!usage.created))throw new Error('日购料耗用顺序尚未读到,请刷新料价'); + } + usages.sort((a,b)=>Number(!!a.appended)-Number(!!b.appended)||(a.appended?a.previewIndex-b.previewIndex:a.createdb.created?1:a.fifo_sequence-b.fifo_sequence)); + if(covered){ + let cumulativeMg=0,previousAmount=0; + for(const usage of usages){ + cumulativeMg+=usage.mg; + const cumulativeAmount=poolMaterialAmount(pool.totalAmount,pool.totalMg,cumulativeMg); + if(usage.previewIndex!==undefined)amounts[usage.previewIndex]=cumulativeAmount-previousAmount; + previousAmount=cumulativeAmount; + } + } + return {amounts,usedMg,wantedMg,covered}; + } function priceLockCost(input){ const locked=fixed(input.lockedQuantity,3,'锁定克重'),actual=fixed(input.quantity,3,'实际克重'); const originalRate=fixed(input.buyRate,2,'原进货料价'); @@ -186,6 +218,6 @@ } return {byPayer,total,rows,goodsExcluded,pendingCount:(order.pendingFees||[]).length}; } - const api={calculate,cents,isSilver,costs,costLabels,costPayers,charges,sale,orderTotal,purchaseCosts,poolMaterialAmount,priceLockCost,orderCosts}; + const api={calculate,cents,isSilver,costs,costLabels,costPayers,charges,sale,orderTotal,purchaseCosts,poolMaterialAmount,poolMaterialPreview,priceLockCost,orderCosts}; if(typeof module==='object'&&module.exports)module.exports=api;else root.LedgerCalc=api; })(typeof globalThis==='object'?globalThis:this); diff --git a/新账系统/public/material-pools-ui.js b/新账系统/public/material-pools-ui.js index dfe4aff..08988f7 100644 --- a/新账系统/public/material-pools-ui.js +++ b/新账系统/public/material-pools-ui.js @@ -24,7 +24,7 @@ function materialPoolManualDraft(line,unit){ } function materialSourceFieldsHTML(line,prefix,unit){ const source=line.costMaterial?.mode==='pool'?'pool':'manual',saved=line.materialPoolDraft||{},poolId=line.costMaterial?.poolId||saved.poolId||'',manual=materialPoolManualDraft(line,unit); - return `
${choice('料费成本来源',prefix+'materialSource',[['manual','手动填写成本'],['pool','当日加权料价']],source)}${button('刷新料价','reload-material-choices','quiet')}每日料价只自动核算料费,进货工费仍按实际填写。
`; + return `
${choice('料费成本来源',prefix+'materialSource',[['manual','手动填写成本'],['pool','当日加权料价']],source)}${button('刷新料价','reload-material-choices','quiet')}料价按当天加权;垫付款按购料录入顺序扣减。进货工费仍按实际填写。
`; } function materialPoolFieldsSetup(line,unit,parts,costMaterial,materialDraft,costPayers){ if(line.costMaterial?.mode!=='pool')return {parts,costMaterial,materialDraft,costPayers}; @@ -33,7 +33,9 @@ function materialPoolFieldsSetup(line,unit,parts,costMaterial,materialDraft,cost } function materialPoolAvailableRows(orderDate,selected){ const rows=materialPoolsCacheUser===state.user.id?materialPoolsCache?.rows||[]:[]; - const byDate=new Map(rows.filter(pool=>pool.date<=orderDate&&(pool.remainingMg>0||pool.id===selected||pool.date===orderDate)).map(pool=>[pool.id,pool])); + const orderId=$('#order-form')?.querySelector('[name="orderId"]')?.value; + const available=rows.map(pool=>({...pool,availableMg:orderId?Math.max(0,pool.totalMg-(pool.usages||[]).filter(usage=>usage.active&&usage.order_id!==orderId).reduce((sum,usage)=>sum+usage.mg,0)):pool.remainingMg})); + const byDate=new Map(available.filter(pool=>pool.date<=orderDate&&(pool.availableMg>0||pool.id===selected||pool.date===orderDate||orderId&&pool.usages?.some(usage=>usage.active&&usage.order_id===orderId))).map(pool=>[pool.id,pool])); if(orderDate&&!byDate.has(orderDate))byDate.set(orderDate,{id:orderDate,date:orderDate,totalMg:0,usedMg:0,remainingMg:0,status:'pending'}); if(selected&&selected<=orderDate&&!byDate.has(selected))byDate.set(selected,{id:selected,date:selected,totalMg:0,usedMg:0,remainingMg:0,status:'pending'}); return [...byDate.values()].sort((a,b)=>b.date.localeCompare(a.date)); @@ -51,15 +53,21 @@ function restoreManualMaterial(root){ get('materialMode').disabled=false;get('materialRate').readOnly=false;get('materialPayer').disabled=false;get('materialMode').closest('label').hidden=false;get('materialPayer').closest('label').hidden=false; material.querySelector('.material-pool-payer')?.remove();material.querySelector('.purchase-total').firstChild.textContent='料费成本合计(元)';get('materialRate').closest('label').firstChild.textContent='进货料价(元/克)'; } -function materialPoolFormUsage(poolId){ - let total=0; - for(const controls of document.querySelectorAll('#order-form .material-source-controls')){ - const row=controls.closest('.line-item'),prefix=controls.dataset.prefix; - const selected=controls.dataset.defaultDate==='true'?$('#order-form [name="date"]').value:row.querySelector(`[name="${prefix}materialPoolId"]`).value||controls.dataset.poolId||$('#order-form [name="date"]').value; - if(row.querySelector(`[name="${prefix}materialSource"]`).value!=='pool'||selected!==poolId||row.querySelector('[name="unit"]').value!=='g'||LedgerCalc.isSilver(row.querySelector('[name="nameType"]').value))continue; - total+=materialPoolMg(row.querySelector('[name="quantity"]').value)||0; - } - return total; +function materialPoolFormPreview(pool,currentRow){ + const form=$('#order-form'),date=form.querySelector('[name="date"]').value,rows=[...form.querySelectorAll('.line-item')],entries=[]; + rows.forEach((row,lineIndex)=>{ + const controls=row.querySelector('.material-source-controls');if(!controls)return; + const prefix=controls.dataset.prefix,source=row.querySelector(`[name="${prefix}materialSource"]`).value; + let selected=row.querySelector(`[name="${prefix}materialPoolId"]`).value||controls.dataset.poolId; + if(controls.dataset.defaultDate==='true'||!selected||selected>date)selected=date; + const allowed=row.querySelector('[name="unit"]').value==='g'&&!LedgerCalc.isSilver(row.querySelector('[name="nameType"]').value); + const active=source==='pool'||allowed&&controls.dataset.allowed==='false'&&controls.dataset.preferredSource==='pool'; + if(!allowed||!active||selected!==pool.id)return; + const mg=materialPoolMg(row.querySelector('[name="quantity"]').value);if(mg)entries.push({lineIndex,mg}); + }); + const allUsages=(materialPoolsCache?.rows||[]).flatMap(value=>value.usages||[]),orderId=form.querySelector('[name="orderId"]')?.value||null; + const preview=LedgerCalc.poolMaterialPreview(pool,entries,{orderId,allUsages}); + return {...preview,amount:preview.amounts[rows.indexOf(currentRow)]??null}; } function syncMaterialPoolSelection(root,unit,quantity){ const controls=root.querySelector('.material-source-controls');if(!controls)return false; @@ -71,28 +79,29 @@ function syncMaterialPoolSelection(root,unit,quantity){ controls.dataset.allowed=String(allowed); let selected=poolSelect.value||controls.dataset.poolId; if(controls.dataset.defaultDate==='true'||!selected||selected>orderDate)selected=orderDate; - const available=materialPoolAvailableRows(orderDate,selected),optionsHTML=available.map(pool=>``).join(''); + const available=materialPoolAvailableRows(orderDate,selected),optionsHTML=available.map(pool=>``).join(''); if(poolSelect.innerHTML!==optionsHTML)poolSelect.innerHTML=optionsHTML; poolSelect.value=selected;controls.dataset.poolId=selected; const active=source.value==='pool',previous=controls.dataset.source; if(active&&previous!=='pool')captureManualMaterial(root); if(!active&&previous==='pool')restoreManualMaterial(root); controls.dataset.source=source.value;controls.querySelector('.material-pool-date-label').hidden=!active;poolSelect.disabled=!active;controls.querySelector('[data-action="reload-material-choices"]').hidden=!active; - const help=controls.querySelector('.material-source-help');help.textContent=allowed?'每日料价只自动核算料费,进货工费仍按实际填写。':'按件商品和银饰请手动填写料费成本。'; + const help=controls.querySelector('.material-source-help');help.textContent=allowed?'料价按当天加权;垫付款按购料录入顺序扣减。进货工费仍按实际填写。':'按件商品和银饰请手动填写料费成本。'; const note=controls.querySelector('.material-pool-note');note.hidden=!active; if(!active)return false; - const pool=materialPoolsCacheUser===state.user.id?materialPoolsCache?.rows.find(pool=>pool.id===selected):null,mg=materialPoolMg(quantity),wanted=materialPoolFormUsage(selected),used=pool?(typeof orderEditPoolUsedMg==='function'?orderEditPoolUsedMg(pool):pool.usedMg):0,covered=!!pool&&pool.totalMg>=used+wanted&&pool.totalMg>0; - let amount=null;if(covered&&mg)try{amount=LedgerCalc.poolMaterialAmount(pool.totalAmount,pool.totalMg,mg);}catch{} + const pool=materialPoolsCacheUser===state.user.id?materialPoolsCache?.rows.find(pool=>pool.id===selected):null,mg=materialPoolMg(quantity); + let preview=null,previewError='';if(pool)try{preview=materialPoolFormPreview(pool,row);}catch(err){previewError=err.message;} + const wanted=preview?.wantedMg??0,used=preview?.usedMg??pool?.usedMg??0,covered=preview?.covered===true,amount=mg?preview?.amount??null:null; const payerText=materialPoolPayers(pool); get('materialMode').value='total';get('materialMode').disabled=true;get('materialMode').closest('label').hidden=true; const rate=get('materialRate');rate.disabled=false;rate.required=false;rate.readOnly=true;rate.value=pool?.averageRate==null?'':(pool.averageRate/100).toFixed(2);rate.closest('label').hidden=false;rate.closest('label').firstChild.textContent='加权进货料价(元/克,自动)'; get('material').value=amount==null?'':(amount/100).toFixed(2);get('material').readOnly=true;get('material').required=false;get('material').closest('label').firstChild.textContent='耗用料费合计(元,自动)'; get('materialPayer').disabled=true;get('materialPayer').closest('label').hidden=true; - let payer=material.querySelector('.material-pool-payer');if(!payer){material.querySelector('.purchase-cost-grid').insertAdjacentHTML('beforeend',field('料费付款人(自动分摊)',prefix+'materialPoolPayer','','text','readonly').replace('