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

290 lines
24 KiB
JavaScript
Raw Normal View History

2026-10-21 01:32:49 +08:00
'use strict';
// 日购料只记录实际采购与成本归属;货盘出入仍由独立库存流水管理。
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;
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')),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);
`);
// 旧采购的原始金额、日期、录入人和时间保持原值,只增补并发版本及软删除字段。
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}`);
}
}
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 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)
.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');
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 ['owner','assistant']){
const purchased=sum(purchases.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;
const revision=createHash('sha256').update(JSON.stringify({purchases,usages:usages.map(({lines,...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}};
}
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){
const pools=allIds(ledger).map(id=>readPool(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');
return {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){
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,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){
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});
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');
if(knownCost>LIMIT)throw new Error('货品成本超出支持范围');
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');
}
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}={}){
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});
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 oldAmount=line.costParts?.material??0;
applySnapshot(line,{...next,mg:usage.mg},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;
}
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});}
}
// 让所有快照使用最终分配后的同一版本,展示版本本身不参与财务改写。
const finalPool=readPool(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 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');
const payer=env.pick(input.payer,['owner','assistant'],'采购付款人'),note=env.text(input.note,'采购备注',200,true),id=randomUUID();
const previous=readPool(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);
const pool=reconcile(ledger,date,date,actor,env);
ledger.audit('material-pool:'+date,'登记实际购料',actor,{id,date,mg,amount,payer,note,averageRate:pool.averageRate,notice:'实际采购支出只记本条;订单仅结转消耗成本,不重复记付款'});
ledger.audit('material-purchase:'+id,'登记实际购料',actor,{before:null,after:purchaseValue(readPurchase(ledger,id,env))});
return {id,poolId:date,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 row;
}
function purchaseDetail(ledger,id,env){
const purchase=purchaseValue(readPurchase(ledger,id,env));
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,pool:readPool(ledger,purchase.pool_id,env),history};
}
function changeablePurchase(ledger,id,input,actor,env){
activeActor(actor,env);
if(!input||typeof input!=='object'||Array.isArray(input))env.fail('购料记录格式无效');
const row=readPurchase(ledger,id,env);
if(row.deleted_at)env.fail('这笔购料记录已删除,请刷新列表',409);
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');
const payer=env.pick(input.payer,['owner','assistant'],'采购付款人'),note=env.text(input.note,'采购备注',200,true),target=readPool(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('同日购料累计超出支持范围');
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);
// 改采购日不迁移已交付用量。原池不足时关联单待补,新日期的料留在新池。
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)});
return {id,poolId:date,previousPoolId:before.pool_id,pool};
});}
function deletePurchase(ledger,id,input,actor,env){return atomic(ledger,()=>{
const before=changeablePurchase(ledger,id,input,actor,env),deleted=env.now();
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)});
return {id,poolId:before.pool_id,previousPoolId:before.pool_id,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: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(usage));
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){
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),'实物退回释放',date,actor,env);pools.add(usage.pool_id);
}
for(const id of pools)reconcile(ledger,id,date,actor,env);
}
// 整单修改复用原行的消耗身份;删除、重排、换池和手填成本都留前后事件。
function adjust(ledger,order,date,actor,env){
const existing=ledger.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY line_index',order.id),affected=new Set();
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);
}
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);
}
}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));
usageEvent(ledger,row,null,usageValue(row),'整单修改新增消耗',date,actor,env);
}
}
for(const id of affected)reconcile(ledger,id,date,actor,env,{skipJournalOrder:order.id});
return ledger.rawOrder(order.id);
}
2026-10-21 01:32:49 +08:00
function reassign(ledger,order,input,actor,env){return atomic(ledger,()=>{
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,()=>{
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('开始日期不能晚于结束日期');
return {from,to,purchases:ledger.rows("SELECT * FROM material_purchases WHERE date>=? AND date<=? AND deleted_at='' ORDER BY date,created,rowid",from,to),
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};