锁价支持手动料价和当日加权料池预留

This commit is contained in:
summer committed 2026-11-02 19:30:28 +08:00
1 parent 4e5a04a34e
commit 9893ecf037
22 files changed
+622 -94

No files matched your search

+5 -3
View File
@@ -26,6 +26,7 @@ const Recoveries=require('./recoveries');
// 仅服务器的新单生成流程能传入,客户端字段不能取得这个权限。 // 仅服务器的新单生成流程能传入,客户端字段不能取得这个权限。
const NEW_ORDER_ACTION=Symbol('newOrderAction'); const NEW_ORDER_ACTION=Symbol('newOrderAction');
const SAME_DAY_ORDER_ACTION=Symbol('sameDayOrderAction'); const SAME_DAY_ORDER_ACTION=Symbol('sameDayOrderAction');
const LockPools=require('./price-lock-pools');
const PRICE_LOCK_DELIVERY=Symbol('priceLockDelivery'); const PRICE_LOCK_DELIVERY=Symbol('priceLockDelivery');
const RECOVERY_ORDER=Symbol('recoveryOrder'); const RECOVERY_ORDER=Symbol('recoveryOrder');
const FEE_LABELS={shipping:'快递费',box:'包装盒',certificate:'证书',braiding:'编绳',sticker:'手机贴',other:'其他直接费用'}; const FEE_LABELS={shipping:'快递费',box:'包装盒',certificate:'证书',braiding:'编绳',sticker:'手机贴',other:'其他直接费用'};
@@ -270,7 +271,7 @@ class Ledger {
if(recovery){o.recovery_id=recovery.id;o.recovery_mode='exchange';o.recovery_immutable_reason=Recoveries.IMMUTABLE_REASON;o.nonCashOffset=recovery.offsetAmount;o.cashPaid=recovery.cashPayment;o.netSettlement=recovery.netSettlement;o.balance=o.total-o.netReceived-o.nonCashOffset;} if(recovery){o.recovery_id=recovery.id;o.recovery_mode='exchange';o.recovery_immutable_reason=Recoveries.IMMUTABLE_REASON;o.nonCashOffset=recovery.offsetAmount;o.cashPaid=recovery.cashPayment;o.netSettlement=recovery.netSettlement;o.balance=o.total-o.netReceived-o.nonCashOffset;}
o.rounding_adjustment=o.rounding_mode==='yuan'?o.total-(sum(o.lines,'sale')-o.discount):0; o.rounding_adjustment=o.rounding_mode==='yuan'?o.total-(sum(o.lines,'sale')-o.discount):0;
o.goodsCost=o.lines.some(l=>l.cost===null)?null:sum(o.lines,'cost');o.directCost=sum(o.expenses,'amount'); o.goodsCost=o.lines.some(l=>l.cost===null)?null:sum(o.lines,'cost');o.directCost=sum(o.expenses,'amount');
o.materialCostPending=!['returned','cancelled'].includes(o.status)&&o.lines.some(l=>l.costMaterial?.mode==='pool'&&l.costParts?.material==null); o.materialCostPending=!['returned','cancelled'].includes(o.status)&&o.lines.some(l=>(l.costMaterial?.mode==='pool'||l.priceLockPool)&&l.costParts?.material==null);
o.knownGoodsCost=sum(o.lines,l=>l.cost??sum(Object.values(l.costParts||{}).map(amount=>({amount:amount??0})),'amount')); o.knownGoodsCost=sum(o.lines,l=>l.cost??sum(Object.values(l.costParts||{}).map(amount=>({amount:amount??0})),'amount'));
o.pendingFees=['draft','confirmed'].includes(o.status)?o.fee_items.filter(f=>f.status!=='recorded'&&(o.status==='draft'||f.status==='estimated')):[]; o.pendingFees=['draft','confirmed'].includes(o.status)?o.fee_items.filter(f=>f.status!=='recorded'&&(o.status==='draft'||f.status==='estimated')):[];
o.draftFees=sum(o.pendingFees,f=>f.amount||0); o.draftFees=sum(o.pendingFees,f=>f.amount||0);
@@ -278,7 +279,7 @@ class Ledger {
const j=this.one('SELECT COALESCE(SUM(profit),0) AS profit FROM journal WHERE order_id=?',id);o.profit=o.materialCostPending&&o.status==='delivered'?null:j.profit;o.knownProfit=o.profit??0; const j=this.one('SELECT COALESCE(SUM(profit),0) AS profit FROM journal WHERE order_id=?',id);o.profit=o.materialCostPending&&o.status==='delivered'?null:j.profit;o.knownProfit=o.profit??0;
o.ownerCost=o.status==='delivered'?Calc.orderCosts(o).byPayer.owner.goods:0; o.ownerCost=o.status==='delivered'?Calc.orderCosts(o).byPayer.owner.goods:0;
if(['delivered','returned','cancelled'].includes(o.status))o.ownerCost+=sum(o.expenses,e=>e.payer==='owner'?e.amount:0); if(['delivered','returned','cancelled'].includes(o.status))o.ownerCost+=sum(o.expenses,e=>e.payer==='owner'?e.amount:0);
if(priceLock){ if(priceLock&&!LockPools.find(this,priceLock.id)){
const delivery=priceLock.delivery?JSON.parse(priceLock.delivery):null,sources=[]; const delivery=priceLock.delivery?JSON.parse(priceLock.delivery):null,sources=[];
const leftover=['delivered','returned'].includes(o.status)&&priceLock.buy_payer==='assistant'?(delivery?.leftover_cost??0):0; const leftover=['delivered','returned'].includes(o.status)&&priceLock.buy_payer==='assistant'?(delivery?.leftover_cost??0):0;
if(leftover)sources.push({kind:'leftover',amount:leftover,quantity:delivery.leftover_mg,explanation:'助理垫付的剩余金料进入自有货盘,按原采购成本抵扣货款待结'}); if(leftover)sources.push({kind:'leftover',amount:leftover,quantity:delivery.leftover_mg,explanation:'助理垫付的剩余金料进入自有货盘,按原采购成本抵扣货款待结'});
@@ -287,7 +288,7 @@ class Ledger {
o.assistantInventoryCredit=leftover+returned;o.assistantInventoryCreditSources=sources; o.assistantInventoryCredit=leftover+returned;o.assistantInventoryCreditSources=sources;
o.assistantInventoryCreditExplanation=sources.map(source=>source.explanation).join(';'); o.assistantInventoryCreditExplanation=sources.map(source=>source.explanation).join(';');
} }
if(!priceLock&&o.status==='returned'&&o.lines.some(line=>line.costMaterial?.mode==='pool')){ if((!priceLock||LockPools.find(this,priceLock.id))&&o.status==='returned'&&o.lines.some(line=>line.costMaterial?.mode==='pool')){
const pooled=o.lines.filter(line=>line.costMaterial?.mode==='pool'); const pooled=o.lines.filter(line=>line.costMaterial?.mode==='pool');
const retained=Calc.orderCosts({...o,lines:pooled,status:'delivered'}).rows.filter(row=>row.kind==='goods'&&row.payer==='assistant'&&!row.materialPoolId); const retained=Calc.orderCosts({...o,lines:pooled,status:'delivered'}).rows.filter(row=>row.kind==='goods'&&row.payer==='assistant'&&!row.materialPoolId);
const amount=sum(retained,'amount'); const amount=sum(retained,'amount');
@@ -690,6 +691,7 @@ class Ledger {
} else if(action==='return'){ } else if(action==='return'){
if(o.status!=='delivered')fail('只有已交付订单可以整单退货',409);if(input.verified!==true)fail('请先确认实物已收回或退回供应商'); if(o.status!=='delivered')fail('只有已交付订单可以整单退货',409);if(input.verified!==true)fail('请先确认实物已收回或退回供应商');
RollingMaterialPools.recordReturns(this,o,date,input,actor,priceLockEnv); RollingMaterialPools.recordReturns(this,o,date,input,actor,priceLockEnv);
if(!RollingMaterialPools.enabled(this))LockPools.recordReturn(this,o,date,input,actor,priceLockEnv);
text(input.reason,'退货原因',200);this.run("UPDATE orders SET status='returned',returned_date=? WHERE id=?",date,id); text(input.reason,'退货原因',200);this.run("UPDATE orders SET status='returned',returned_date=? WHERE id=?",date,id);
const group=randomUUID();o.lines.forEach((l,i)=>{ const group=randomUUID();o.lines.forEach((l,i)=>{
const destination=input.returnPockets?.[i]??l.pocket; const destination=input.returnPockets?.[i]??l.pocket;
+17 -21
View File
@@ -7,6 +7,7 @@ const Rolling=require('./rolling-material-pools');
const PARTIES=['owner','assistant','assistant2']; const PARTIES=['owner','assistant','assistant2'];
const sum=(rows,key)=>rows.reduce((total,row)=>total+(row[key]??0),0); const sum=(rows,key)=>rows.reduce((total,row)=>total+(row[key]??0),0);
const LIMIT=100000000000; const LIMIT=100000000000;
const LockPools=require('./price-lock-pools');
const ALLOCATION_VERSION=2,ALLOCATION_KEY='material-pool-allocation-version'; const ALLOCATION_VERSION=2,ALLOCATION_KEY='material-pool-allocation-version';
function initialize(ledger){ function initialize(ledger){
ledger.db.exec(` ledger.db.exec(`
@@ -53,6 +54,7 @@ function initialize(ledger){
});}finally{if(foreignKeys)ledger.db.exec('PRAGMA foreign_keys=ON');} });}finally{if(foreignKeys)ledger.db.exec('PRAGMA foreign_keys=ON');}
} }
Rolling.initialize(ledger); Rolling.initialize(ledger);
LockPools.initialize(ledger);
} }
function atomic(ledger,fn){ function atomic(ledger,fn){
ledger.db.exec('SAVEPOINT material_pool_action'); ledger.db.exec('SAVEPOINT material_pool_action');
@@ -74,9 +76,10 @@ function readPool(ledger,id,env,{internal=false}={}){
if(Rolling.isDay(ledger,id))return Rolling.readPool(ledger,id,env,{internal}); if(Rolling.isDay(ledger,id))return Rolling.readPool(ledger,id,env,{internal});
if(!internal&&Rolling.enabled(ledger)){const saved=Rolling.legacySnapshot(ledger,id);if(saved)return visiblePool(ledger,saved);} 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); 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.*,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) 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}:{}),product:JSON.parse(lines)[row.line_index]?.name??''};}); .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}:{}),product:JSON.parse(lines)[row.line_index]?.name??''};});
purchases.splice(0,purchases.length,...purchases.map(row=>actualPurchase(ledger,row))); 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 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 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 shortageMg=Math.max(0,usedMg-totalMg),remainingMg=Math.max(0,totalMg-usedMg),pending=shortageMg>0;
@@ -101,11 +104,11 @@ function visiblePool(ledger,pool){
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}); 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};} 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 self=ledger.memberFor(ledger.actor),own=(kind,id)=>ledger.entityMember(kind,id)===self;
const usages=pool.usages.map(row=>own('order',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 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,shared:true,canEdit:false,canRequestChange:false,...(pool.rolling?{sourceKind:row.sourceKind,allocations:row.allocations,cashAmount:row.cashAmount}:{})}); 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,...safePool}=pool; const {returns,opening,...safePool}=pool;
return {...safePool,...(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('order',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}; return {...safePool,...(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 internalPool(ledger,id,env){return readPool(ledger,id,env,{internal:true});}
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 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);}
@@ -164,18 +167,7 @@ function allocatePayers(purchases,fromAmount,amount){
if(skip||left)throw new Error('日购料垫付金额不足,无法分配料费'); if(skip||left)throw new Error('日购料垫付金额不足,无法分配料费');
return {owner_amount:ownerAmount,assistant_amount:assistantAmount,...(includesThird?{assistant2_amount:assistant2Amount}:{}),zero_payer:zeroPayer}; return {owner_amount:ownerAmount,assistant_amount:assistantAmount,...(includesThird?{assistant2_amount:assistant2Amount}:{}),zero_payer:zeroPayer};
} }
function allocateUsages(pool,usages){ function allocateUsages(pool,usages){return LockPools.allocate(pool,usages,allocatePayers).map((row,index)=>({usage:row.kind==='priceLock'?row:usages[index],...row}));}
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}={}){ function prepareLines(ledger,lines,businessDate,env,{orderId=null}={}){
if(Rolling.isDay(ledger,businessDate))return Rolling.prepareLines(ledger,lines,businessDate,env,{orderId}); if(Rolling.isDay(ledger,businessDate))return Rolling.prepareLines(ledger,lines,businessDate,env,{orderId});
if(Rolling.enabled(ledger)&&lines.some(line=>line.costMaterial?.mode==='pool'))Rolling.assertDate(ledger,businessDate,env); if(Rolling.enabled(ledger)&&lines.some(line=>line.costMaterial?.mode==='pool'))Rolling.assertDate(ledger,businessDate,env);
@@ -190,12 +182,12 @@ function prepareLines(ledger,lines,businessDate,env,{orderId=null}={}){
}); });
if(!groups.size)return lines; if(!groups.size)return lines;
// 整单修改按原行身份替换用量,原 created,rowid 保持原位;新增行与正式交付一样追加。 // 整单修改按原行身份替换用量,原 created,rowid 保持原位;新增行与正式交付一样追加。
const originals=orderId?ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId):[]; 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(rowid),0) AS value FROM material_pool_usages').value,created=env.now(); 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){ for(const [id,group] of groups){
const pool=internalPool(ledger,id,env); const pool=internalPool(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) const usages=pool.usages.filter(usage=>usage.active)
.filter(usage=>usage.order_id!==orderId); .filter(usage=>!orderId||usage.order_id!==orderId);
for(const {line,index} of group){ for(const {line,index} of group){
const original=originals.find(usage=>usage.line_index===index); const original=originals.find(usage=>usage.line_index===index);
usages.push({...original,mg:consumptionMg(line),created:original?.created??created,fifo_sequence:original?.fifo_sequence??lastSequence+index+1,preview_index:index}); usages.push({...original,mg:consumptionMg(line),created:original?.created??created,fifo_sequence:original?.fifo_sequence??lastSequence+index+1,preview_index:index});
@@ -218,6 +210,7 @@ function reconcileInternal(ledger,id,date,actor,env,{skipJournalOrder=null,alloc
const beforePool=internalPool(ledger,id,env),active=beforePool.usages.filter(row=>row.active),pending=beforePool.shortageMg>0; const beforePool=internalPool(ledger,id,env),active=beforePool.usages.filter(row=>row.active),pending=beforePool.shortageMg>0;
const orders=new Map(); const orders=new Map();
for(const {usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,assistant2_amount:assistant2Amount,zero_payer} of allocateUsages(beforePool,active)){ for(const {usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,assistant2_amount:assistant2Amount,zero_payer} 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(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:[]}); 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]; const update=orders.get(usage.order_id),line=update.order.lines[usage.line_index];
@@ -408,6 +401,7 @@ function deliver(ledger,order,date,actor,env){
if(ledger.one('SELECT id FROM material_pool_usages WHERE order_id=? AND line_index=?',order.id,index))env.fail('本商品已登记日购料消耗,不能重复交付',409); 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()}; 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)); 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); 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}); for(const id of pools)reconcile(ledger,id,date,actor,env,{skipJournalOrder:order.id});
@@ -421,6 +415,7 @@ function release(ledger,order,date,actor,env,{kind='实物退回释放'}={}){
ledger.run('UPDATE material_pool_usages SET active=0,revision=revision+1,updated=? WHERE id=?',env.now(),usage.id); 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); 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); for(const id of pools)reconcile(ledger,id,date,actor,env);
} }
// 整单修改复用原行的消耗身份;删除、重排、换池和手填成本都留前后事件。 // 整单修改复用原行的消耗身份;删除、重排、换池和手填成本都留前后事件。
@@ -451,6 +446,7 @@ function adjust(ledger,order,date,actor,env){
}else{ }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()}; 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)); 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; usageEvent(ledger,row,null,usageValue(row),'整单修改新增消耗',date,actor,env);consumptionChanged=true;
} }
} }
@@ -505,4 +501,4 @@ function reporting(ledger,query,env){
settlements:restricted?[]:ledger.rows('SELECT * FROM material_pool_settlements WHERE date>=? AND date<=? ORDER BY date,created,rowid',from,to), 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)}))}; 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}; module.exports={initialize,allocatePayers,prepareLine,prepareLines,readPool,visiblePool,list,purchase,purchaseDetail,editPurchase,deletePurchase,deliver,release,adjust,reassign,settle,reporting,settlement,allocationStatus,migrateAllocation,actualPurchase,reconcile};
+4 -4
View File
@@ -1,7 +1,7 @@
'use strict'; 'use strict';
// 历史采购更正先试算回滚;只在麦麦复核同一依赖版本后重算历史链。 // 历史采购更正先试算回滚;只在麦麦复核同一依赖版本后重算历史链。
const {randomUUID}=require('node:crypto'),Rolling=require('./rolling-material-pools'); const {randomUUID}=require('node:crypto'),Rolling=require('./rolling-material-pools');
const Material=()=>require('./material-pools'); const Material=()=>require('./material-pools'),LockApprovals=require('./price-lock-pool-approvals');
const fields=['goodsCost','profit','settlementDue','ownerCost','total','netReceived']; const fields=['goodsCost','profit','settlementDue','ownerCost','total','netReceived'];
function atomic(l,fn){l.db.exec('SAVEPOINT material_purchase_change_action');try{const result=fn();l.db.exec('RELEASE material_purchase_change_action');return result;}catch(error){l.db.exec('ROLLBACK TO material_purchase_change_action');l.db.exec('RELEASE material_purchase_change_action');throw error;}} function atomic(l,fn){l.db.exec('SAVEPOINT material_purchase_change_action');try{const result=fn();l.db.exec('RELEASE material_purchase_change_action');return result;}catch(error){l.db.exec('ROLLBACK TO material_purchase_change_action');l.db.exec('RELEASE material_purchase_change_action');throw error;}}
function initialize(l){l.db.exec(`CREATE TABLE IF NOT EXISTS material_purchase_changes( function initialize(l){l.db.exec(`CREATE TABLE IF NOT EXISTS material_purchase_changes(
@@ -14,12 +14,12 @@ function summary(before,after){const relatedOrders=[];for(const [id,b] of before
function apply(l,id,action,payload,actor,env){return Rolling.withHistorical(l,()=>l.scope(null,()=>{const result=action==='delete'?Material().deletePurchase(l,id,payload,actor,env):Material().editPurchase(l,id,payload,actor,env);Rolling.rebuild(l,actor,env);return result;},null));} function apply(l,id,action,payload,actor,env){return Rolling.withHistorical(l,()=>l.scope(null,()=>{const result=action==='delete'?Material().deletePurchase(l,id,payload,actor,env):Material().editPurchase(l,id,payload,actor,env);Rolling.rebuild(l,actor,env);return result;},null));}
function preview(l,id,action,payload,actor,env){ function preview(l,id,action,payload,actor,env){
const compact=p=>Object.fromEntries(['id','date','mg','amount','payer','note','revision'].map(k=>[k,p[k]])); const compact=p=>Object.fromEntries(['id','date','mg','amount','payer','note','revision'].map(k=>[k,p[k]]));
const before=compact(Material().purchaseDetail(l,id,env).purchase),old=finance(l);l.db.exec('SAVEPOINT material_change_preview'); const before=compact(Material().purchaseDetail(l,id,env).purchase),old=finance(l),oldLocks=LockApprovals.finance(l);l.db.exec('SAVEPOINT material_change_preview');
try{apply(l,id,action,payload,{...actor,role:'owner'},env);l.syncTeamFunds({...actor,role:'owner'});const after=action==='delete'?null:compact(Material().purchaseDetail(l,id,env).purchase);return {before,after,...summary(old,finance(l))};} try{apply(l,id,action,payload,{...actor,role:'owner'},env);l.syncTeamFunds({...actor,role:'owner'});const after=action==='delete'?null:compact(Material().purchaseDetail(l,id,env).purchase);const result={before,after,...summary(old,finance(l))},relatedPriceLocks=LockApprovals.changes(oldLocks,LockApprovals.finance(l));if(relatedPriceLocks.length){result.relatedPriceLocks=relatedPriceLocks;result.affectedDates=[...new Set([...result.affectedDates,...relatedPriceLocks.map(r=>r.date)])].sort();result.summary.affectedPriceLockCount=relatedPriceLocks.length;}return result;}
finally{l.db.exec('ROLLBACK TO material_change_preview');l.db.exec('RELEASE material_change_preview');} finally{l.db.exec('ROLLBACK TO material_change_preview');l.db.exec('RELEASE material_change_preview');}
} }
function read(l,id,actor,env){active(actor,env);const r=l.one('SELECT * FROM material_purchase_changes WHERE id=?',id);if(!r||actor.role!=='owner'&&r.requester_id!==actor.id)env.fail('购料更正申请不存在或无权访问',404);return r;} function read(l,id,actor,env){active(actor,env);const r=l.one('SELECT * FROM material_purchase_changes WHERE id=?',id);if(!r||actor.role!=='owner'&&r.requester_id!==actor.id)env.fail('购料更正申请不存在或无权访问',404);return r;}
function dto(l,r,actor){const {payload,preview:raw,snapshot_hash,...rest}=r,preview=JSON.parse(raw),stale=r.status==='pending'&&Rolling.dependency(l)!==snapshot_hash;if(actor.role!=='owner'){preview.relatedOrders=preview.relatedOrders.filter(o=>l.canAccess('order',o.id,actor));preview.summary={affectedOrderCount:preview.summary.affectedOrderCount};}return {...rest,stale,canApprove:actor.role==='owner'&&r.status==='pending'&&!stale,preview};} function dto(l,r,actor){const {payload,preview:raw,snapshot_hash,...rest}=r,preview=JSON.parse(raw),stale=r.status==='pending'&&Rolling.dependency(l)!==snapshot_hash;if(actor.role!=='owner'){preview.relatedOrders=preview.relatedOrders.filter(o=>l.canAccess('order',o.id,actor));if(preview.relatedPriceLocks)preview.relatedPriceLocks=LockApprovals.visibleChanges(l,preview.relatedPriceLocks,actor);preview.summary={affectedOrderCount:preview.summary.affectedOrderCount};}return {...rest,stale,canApprove:actor.role==='owner'&&r.status==='pending'&&!stale,preview};}
function detail(l,id,actor,env){return dto(l,read(l,id,actor,env),actor);} function detail(l,id,actor,env){return dto(l,read(l,id,actor,env),actor);}
function list(l,query,actor,env){active(actor,env);const status=query.status||'pending';if(!['all','pending','approved','rejected'].includes(status))env.fail('更正申请状态无效');const all=l.rows('SELECT * FROM material_purchase_changes ORDER BY created DESC,rowid DESC').filter(r=>actor.role==='owner'||r.requester_id===actor.id);return {rows:all.filter(r=>status==='all'||r.status===status).map(r=>dto(l,r,actor)),counts:Object.fromEntries(['pending','approved','rejected'].map(s=>[s,all.filter(r=>r.status===s).length]))};} function list(l,query,actor,env){active(actor,env);const status=query.status||'pending';if(!['all','pending','approved','rejected'].includes(status))env.fail('更正申请状态无效');const all=l.rows('SELECT * FROM material_purchase_changes ORDER BY created DESC,rowid DESC').filter(r=>actor.role==='owner'||r.requester_id===actor.id);return {rows:all.filter(r=>status==='all'||r.status===status).map(r=>dto(l,r,actor)),counts:Object.fromEntries(['pending','approved','rejected'].map(s=>[s,all.filter(r=>r.status===s).length]))};}
function request(l,id,input,actor,env){ function request(l,id,input,actor,env){
+4
View File
@@ -3,6 +3,7 @@
const {randomUUID}=require('node:crypto'); const {randomUUID}=require('node:crypto');
const MaterialPools=require('./material-pools'); const MaterialPools=require('./material-pools');
const Rolling=require('./rolling-material-pools'); const Rolling=require('./rolling-material-pools');
const LockPoolApprovals=require('./price-lock-pool-approvals');
const hash=require('./order-snapshot-hash'); const hash=require('./order-snapshot-hash');
function activeActor(actor,env){if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号处理取消申请',403);} function activeActor(actor,env){if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号处理取消申请',403);}
function owner(actor,env){activeActor(actor,env);if(actor.role!=='owner')env.fail('取消申请必须由麦麦账号审批',403);} function owner(actor,env){activeActor(actor,env);if(actor.role!=='owner')env.fail('取消申请必须由麦麦账号审批',403);}
@@ -35,6 +36,9 @@ function snapshot(ledger,id){
for(const table of ['payments','expenses','settlements','journal','movements'])tables[table]=ledger.rows('SELECT * FROM '+table+' WHERE order_id=? ORDER BY rowid',id); for(const table of ['payments','expenses','settlements','journal','movements'])tables[table]=ledger.rows('SELECT * FROM '+table+' WHERE order_id=? ORDER BY rowid',id);
tables.corrections=ledger.rows('SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?) ORDER BY rowid',id,id,id); tables.corrections=ledger.rows('SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?) ORDER BY rowid',id,id,id);
tables.materialUsages=ledger.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY rowid',id); tables.materialUsages=ledger.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY rowid',id);
const poolIds=[...new Set(tables.materialUsages.map(row=>row.pool_id))],poolLocks=poolIds.map(poolId=>({id:poolId,...LockPoolApprovals.snapshot(ledger,{poolId})})).filter(pool=>pool.priceLockPool);
// 作废审计会回传原单详情;仅保存依赖指纹,不能带入其他成员锁单的客户资料。
if(poolLocks.length)tables.priceLockPoolDependencies=poolLocks.map(pool=>({id:pool.id,hash:hash(pool.priceLockPool)}));
const priceLock=ledger.one('SELECT id FROM price_locks WHERE final_order_id=?',id)?.id||null; const priceLock=ledger.one('SELECT id FROM price_locks WHERE final_order_id=?',id)?.id||null;
// 不改变旧模式申请的哈希;滚动模式另核对跨日来源和第三人归属,防止批准旧试算。 // 不改变旧模式申请的哈希;滚动模式另核对跨日来源和第三人归属,防止批准旧试算。
return {order,...tables,priceLock,...(Rolling.enabled(ledger)?{rollingDependency:Rolling.dependency(ledger)}:{})}; return {order,...tables,priceLock,...(Rolling.enabled(ledger)?{rollingDependency:Rolling.dependency(ledger)}:{})};
+10 -6
View File
@@ -3,6 +3,7 @@
const {randomUUID}=require('node:crypto'); const {randomUUID}=require('node:crypto');
const OrderEdit=require('./order-edit'); const OrderEdit=require('./order-edit');
const Rolling=require('./rolling-material-pools'); const Rolling=require('./rolling-material-pools');
const LockPoolApprovals=require('./price-lock-pool-approvals');
const hash=require('./order-snapshot-hash'); const hash=require('./order-snapshot-hash');
const clone=value=>JSON.parse(JSON.stringify(value)); const clone=value=>JSON.parse(JSON.stringify(value));
const ACTION_LABELS={edit:'修改订单',expense:'费用补记',fees:'旧费用核实',refund:'退款',return:'退货',cost:'成本补录'}; const ACTION_LABELS={edit:'修改订单',expense:'费用补记',fees:'旧费用核实',refund:'退款',return:'退货',cost:'成本补录'};
@@ -47,7 +48,7 @@ function directSnapshot(ledger,id){
for(const table of ['payments','expenses','settlements','journal','movements','material_pool_usages'])tables[table]=ledger.rows('SELECT * FROM '+table+' WHERE order_id=? ORDER BY rowid',id); for(const table of ['payments','expenses','settlements','journal','movements','material_pool_usages'])tables[table]=ledger.rows('SELECT * FROM '+table+' WHERE order_id=? ORDER BY rowid',id);
tables.corrections=ledger.rows('SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?) ORDER BY rowid',id,id,id); tables.corrections=ledger.rows('SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?) ORDER BY rowid',id,id,id);
const lock=ledger.one('SELECT * FROM price_locks WHERE final_order_id=?',id)||null; const lock=ledger.one('SELECT * FROM price_locks WHERE final_order_id=?',id)||null;
return {order,...tables,priceLock:lock,...(lock?{priceLockEvents:ledger.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY rowid',lock.id)}:{})}; return {order,...tables,priceLock:lock,...(lock?{priceLockEvents:ledger.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY rowid',lock.id),...LockPoolApprovals.snapshot(ledger,{priceLockId:lock.id})}:{})};
} }
function snapshot(ledger,id,dependencies){return ledger.scope(null,()=>snapshotInternal(ledger,id,dependencies),null);} function snapshot(ledger,id,dependencies){return ledger.scope(null,()=>snapshotInternal(ledger,id,dependencies),null);}
function snapshotInternal(ledger,id,dependencies){ function snapshotInternal(ledger,id,dependencies){
@@ -55,7 +56,8 @@ function snapshotInternal(ledger,id,dependencies){
purchases:ledger.rows('SELECT * FROM material_purchases WHERE pool_id=? ORDER BY rowid',poolId), purchases:ledger.rows('SELECT * FROM material_purchases WHERE pool_id=? ORDER BY rowid',poolId),
usages:ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE pool_id=? ORDER BY rowid',poolId), usages:ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE pool_id=? ORDER BY rowid',poolId),
settlements:ledger.rows('SELECT * FROM material_pool_settlements WHERE pool_id=? ORDER BY rowid',poolId), settlements:ledger.rows('SELECT * FROM material_pool_settlements WHERE pool_id=? ORDER BY rowid',poolId),
orders:ledger.rows('SELECT DISTINCT o.id FROM orders o JOIN material_pool_usages u ON u.order_id=o.id WHERE u.pool_id=? ORDER BY o.id',poolId).map(row=>directSnapshot(ledger,row.id)) orders:ledger.rows('SELECT DISTINCT o.id FROM orders o JOIN material_pool_usages u ON u.order_id=o.id WHERE u.pool_id=? ORDER BY o.id',poolId).map(row=>directSnapshot(ledger,row.id)),
...LockPoolApprovals.snapshot(ledger,{poolId})
})); }));
// 未启用时不增添字段,已保存的旧申请哈希继续有效;启用后任何结转来源变动都须重审。 // 未启用时不增添字段,已保存的旧申请哈希继续有效;启用后任何结转来源变动都须重审。
return {dependencies,data:directSnapshot(ledger,id),pools,...(Rolling.enabled(ledger)?{rollingDependency:Rolling.dependency(ledger)}:{})}; return {dependencies,data:directSnapshot(ledger,id),pools,...(Rolling.enabled(ledger)?{rollingDependency:Rolling.dependency(ledger)}:{})};
@@ -104,7 +106,8 @@ function effectInternal(ledger,id,dependencies){
journal:grouped('journal',['date'],['sales','goods','expense','profit']),movements:grouped('movements',['date','pocket','kind'],['mg']), journal:grouped('journal',['date'],['sales','goods','expense','profit']),movements:grouped('movements',['date','pocket','kind'],['mg']),
related:relatedIds.map(orderId=>({order:stableRaw(ledger.rawOrder(orderId)),summary:summary(ledger.detail(orderId))})), related:relatedIds.map(orderId=>({order:stableRaw(ledger.rawOrder(orderId)),summary:summary(ledger.detail(orderId))})),
usages:dependencies.pools.map(poolId=>({id:poolId,rows:ledger.rows('SELECT order_id,line_index,pool_id,date,mg,active,amount,owner_amount,assistant_amount,revision FROM material_pool_usages WHERE pool_id=? ORDER BY order_id,line_index',poolId)})), usages:dependencies.pools.map(poolId=>({id:poolId,rows:ledger.rows('SELECT order_id,line_index,pool_id,date,mg,active,amount,owner_amount,assistant_amount,revision FROM material_pool_usages WHERE pool_id=? ORDER BY order_id,line_index',poolId)})),
...(Rolling.enabled(ledger)?{rollingMaterial:rollingEffect(ledger)}:{})}; ...(Rolling.enabled(ledger)?{rollingMaterial:rollingEffect(ledger)}:{}),
...LockPoolApprovals.effect(ledger,Rolling.enabled(ledger)?null:dependencies.pools)};
} }
function changes(before,after){ function changes(before,after){
const labels={status:'订单状态',returned_date:'退货日期',received:'累计收款',refunded:'累计退款',payments:'收退款流水',expenses:'实际费用流水',date:'订单日期',customer:'客户称呼',salesperson:'开单人',note:'客户单备注',internal_note:'内部备注(客户不可见)',total:'销售金额',discount:'优惠',rounding_mode:'取整方式',payment_account:'收款账户',fees_date:'费用日期',lines:'商品及成本',fee_items:'实际费用',netReceived:'已收净额',goodsCost:'货品成本',directCost:'直接费用',profit:'利润',settlementDue:'双方待结'}; const labels={status:'订单状态',returned_date:'退货日期',received:'累计收款',refunded:'累计退款',payments:'收退款流水',expenses:'实际费用流水',date:'订单日期',customer:'客户称呼',salesperson:'开单人',note:'客户单备注',internal_note:'内部备注(客户不可见)',total:'销售金额',discount:'优惠',rounding_mode:'取整方式',payment_account:'收款账户',fees_date:'费用日期',lines:'商品及成本',fee_items:'实际费用',netReceived:'已收净额',goodsCost:'货品成本',directCost:'直接费用',profit:'利润',settlementDue:'双方待结'};
@@ -122,17 +125,18 @@ function apply(ledger,id,action,payload,actor,env){
} }
function preview(ledger,id,action,payload,actor,dependencies,env){return ledger.scope(null,()=>previewInternal(ledger,id,action,payload,actor,dependencies,env),null);} function preview(ledger,id,action,payload,actor,dependencies,env){return ledger.scope(null,()=>previewInternal(ledger,id,action,payload,actor,dependencies,env),null);}
function previewInternal(ledger,id,action,payload,actor,dependencies,env){ function previewInternal(ledger,id,action,payload,actor,dependencies,env){
const before=cleanOrder(ledger.detail(id)),inventoryBefore=inventorySummary(ledger,id),relatedBefore=new Map(relatedOrderIds(ledger,id,dependencies).filter(orderId=>orderId!==id).map(orderId=>[orderId,cleanOrder(ledger.detail(orderId))])); const before=cleanOrder(ledger.detail(id)),inventoryBefore=inventorySummary(ledger,id),relatedBefore=new Map(relatedOrderIds(ledger,id,dependencies).filter(orderId=>orderId!==id).map(orderId=>[orderId,cleanOrder(ledger.detail(orderId))])),locksBefore=LockPoolApprovals.finance(ledger);
ledger.db.exec('SAVEPOINT order_change_preview'); ledger.db.exec('SAVEPOINT order_change_preview');
try{ try{
apply(ledger,id,action,payload,{...actor,role:'owner'},env); apply(ledger,id,action,payload,{...actor,role:'owner'},env);
const after=cleanOrder(ledger.detail(id)),relatedOrders=[...relatedBefore].map(([orderId,original])=>{const next=cleanOrder(ledger.detail(orderId));return {id:orderId,number:original.number,before:original,after:next,summary:{before:summary(original),after:summary(next)},changes:changes(original,next)};}).filter(row=>row.changes.length); const after=cleanOrder(ledger.detail(id)),relatedOrders=[...relatedBefore].map(([orderId,original])=>{const next=cleanOrder(ledger.detail(orderId));return {id:orderId,number:original.number,before:original,after:next,summary:{before:summary(original),after:summary(next)},changes:changes(original,next)};}).filter(row=>row.changes.length);
const inventoryAfter=inventorySummary(ledger,id),result={before,after,summary:{before:summary(before),after:summary(after),inventory:{before:inventoryBefore,after:inventoryAfter,changes:inventoryChanges(inventoryBefore,inventoryAfter)}},changes:changes(before,after),relatedOrders}; const relatedPriceLocks=LockPoolApprovals.changes(locksBefore,LockPoolApprovals.finance(ledger));
const inventoryAfter=inventorySummary(ledger,id),result={before,after,summary:{before:summary(before),after:summary(after),inventory:{before:inventoryBefore,after:inventoryAfter,changes:inventoryChanges(inventoryBefore,inventoryAfter)}},changes:changes(before,after),relatedOrders,...(relatedPriceLocks.length?{relatedPriceLocks}:{})};
return {...result,effectHash:hash(effect(ledger,id,dependencies))}; return {...result,effectHash:hash(effect(ledger,id,dependencies))};
}finally{ledger.db.exec('ROLLBACK TO order_change_preview');ledger.db.exec('RELEASE order_change_preview');} }finally{ledger.db.exec('ROLLBACK TO order_change_preview');ledger.db.exec('RELEASE order_change_preview');}
} }
function rowDetail(ledger,row,actor){ function rowDetail(ledger,row,actor){
const saved=JSON.parse(row.preview);if(ledger.teamMode&&actor?.role==='assistant')saved.relatedOrders=(saved.relatedOrders||[]).filter(order=>ledger.canAccess('order',order.id,actor)); const saved=JSON.parse(row.preview);if(ledger.teamMode&&actor?.role==='assistant'){saved.relatedOrders=(saved.relatedOrders||[]).filter(order=>ledger.canAccess('order',order.id,actor));if(saved.relatedPriceLocks)saved.relatedPriceLocks=LockPoolApprovals.visibleChanges(ledger,saved.relatedPriceLocks,actor);}
const expired=stale(ledger,row),{payload,snapshot:savedSnapshot,snapshot_hash:snapshotHash,preview:storedPreview,effect_hash:effectHash,...fields}=row; const expired=stale(ledger,row),{payload,snapshot:savedSnapshot,snapshot_hash:snapshotHash,preview:storedPreview,effect_hash:effectHash,...fields}=row;
return {...fields,action:row.action||'edit',action_label:ACTION_LABELS[row.action||'edit'],...(row.action&&row.action!=='edit'?{action_input:Object.fromEntries(Object.entries(JSON.parse(payload)).filter(([key])=>!['revision','reason','verified'].includes(key)))}:{}),order_number:saved.before.number,order_date:saved.before.date,order_status:saved.before.status, return {...fields,action:row.action||'edit',action_label:ACTION_LABELS[row.action||'edit'],...(row.action&&row.action!=='edit'?{action_input:Object.fromEntries(Object.entries(JSON.parse(payload)).filter(([key])=>!['revision','reason','verified'].includes(key)))}:{}),order_number:saved.before.number,order_date:saved.before.date,order_status:saved.before.status,
stale:expired,canApprove:actor?.role==='owner'&&row.status==='pending'&&!expired&&!ledger.one("SELECT id FROM order_cancellations WHERE order_id=? AND status='pending'",row.order_id),...saved}; stale:expired,canApprove:actor?.role==='owner'&&row.status==='pending'&&!expired&&!ledger.one("SELECT id FROM order_cancellations WHERE order_id=? AND status='pending'",row.order_id),...saved};
+2
View File
@@ -3,6 +3,7 @@
const {randomUUID}=require('node:crypto'); const {randomUUID}=require('node:crypto');
const TeamMembers=require('./team-members'); const TeamMembers=require('./team-members');
const TeamFunds=require('./team-funds'); const TeamFunds=require('./team-funds');
const LockPoolApprovals=require('./price-lock-pool-approvals');
const hash=require('./order-snapshot-hash'); const hash=require('./order-snapshot-hash');
const PENDING_REASON='本单有待审批归属申请,请先由麦麦同意或驳回后再改动'; const PENDING_REASON='本单有待审批归属申请,请先由麦麦同意或驳回后再改动';
function active(actor,env){if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号处理订单归属',403);} function active(actor,env){if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号处理订单归属',403);}
@@ -65,6 +66,7 @@ function snapshot(ledger,id){return ledger.scope(null,()=>{
data.usageParties=ledger.rows('SELECT p.* FROM material_usage_parties p JOIN material_pool_usages u ON u.id=p.usage_id WHERE u.order_id=? ORDER BY p.rowid',id); data.usageParties=ledger.rows('SELECT p.* FROM material_usage_parties p JOIN material_pool_usages u ON u.id=p.usage_id WHERE u.order_id=? ORDER BY p.rowid',id);
data.corrections=ledger.rows('SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?) ORDER BY rowid',id,id,id); data.corrections=ledger.rows('SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?) ORDER BY rowid',id,id,id);
data.lockEvents=relations.lock?ledger.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY rowid',relations.lock.id):[]; data.lockEvents=relations.lock?ledger.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY rowid',relations.lock.id):[];
if(relations.lock)Object.assign(data,LockPoolApprovals.snapshot(ledger,{priceLockId:relations.lock.id}));
data.fundSources=ledger.rows("SELECT * FROM team_fund_sources WHERE (kind='order' AND source_id=?) OR (kind='price_lock' AND source_id=?) ORDER BY kind,source_id",id,relations.lock?.id??''); data.fundSources=ledger.rows("SELECT * FROM team_fund_sources WHERE (kind='order' AND source_id=?) OR (kind='price_lock' AND source_id=?) ORDER BY kind,source_id",id,relations.lock?.id??'');
data.fundingClaims=ledger.rows("SELECT * FROM team_fund_claim_uses WHERE source_kind='order' AND source_id=? ORDER BY component",id); data.fundingClaims=ledger.rows("SELECT * FROM team_fund_claim_uses WHERE source_kind='order' AND source_id=? ORDER BY component",id);
return data; return data;
+49
View File
@@ -0,0 +1,49 @@
'use strict';
// 审批依据保留原始来源,结果比较只保留业务值;没有池锁时沿用旧申请哈希。
const exists=(ledger,table)=>!!ledger.one("SELECT name FROM sqlite_master WHERE type='table' AND name=?",table);
const allocations=value=>(typeof value==='string'?JSON.parse(value):value??[]).map(({payer,amount})=>({payer,amount}));
function rows(ledger,{poolId=null,priceLockId=null}={}){
if(!exists(ledger,'price_lock_pool_reservations'))return {reservations:[],returns:[]};
const reservations=ledger.rows('SELECT * FROM price_lock_pool_reservations'+(priceLockId?' WHERE price_lock_id=?':poolId?' WHERE pool_id=?':'')+' ORDER BY rowid',...(priceLockId?[priceLockId]:poolId?[poolId]:[]));
const returns=exists(ledger,'price_lock_pool_returns')?ledger.rows('SELECT * FROM price_lock_pool_returns'+(priceLockId?' WHERE price_lock_id=?':poolId?' WHERE origin_pool_id=? OR date=?':'')+' ORDER BY rowid',...(priceLockId?[priceLockId]:poolId?[poolId,poolId]:[])):[];
return {reservations,returns};
}
function snapshot(ledger,query={}){
const state=rows(ledger,query);if(!state.reservations.length&&!state.returns.length)return {};
if(query.poolId){const ids=[...new Set([...state.reservations,...state.returns].map(row=>row.price_lock_id))];state.locks=ids.map(id=>ledger.one('SELECT * FROM price_locks WHERE id=?',id));}
if(exists(ledger,'material_usage_order')){
const usageIds=new Set(state.reservations.map(row=>row.id)),orderUsageIds=new Set(query.poolId?ledger.rows('SELECT id FROM material_pool_usages WHERE pool_id=?',query.poolId).map(row=>row.id):[]);
state.usageOrder=ledger.rows('SELECT * FROM material_usage_order ORDER BY sequence').filter(row=>row.kind==='priceLock'?usageIds.has(row.source_id):row.kind==='order'&&orderUsageIds.has(row.source_id));
}
return {priceLockPool:state};
}
function effect(ledger,poolIds=null){
const source=poolIds?poolIds.map(poolId=>rows(ledger,{poolId})): [rows(ledger)];
const unique=values=>[...new Map(values.map(row=>[row.id,row])).values()];
const reservations=unique(source.flatMap(value=>value.reservations)),returns=unique(source.flatMap(value=>value.returns));
if(!reservations.length&&!returns.length)return {};
const stable=(key,value)=>['id','revision','created','updated','actor','source_sequence','source_id'].includes(key)?undefined:value;
return {priceLockPool:{
reservations:reservations.map(row=>({priceLockId:row.price_lock_id,poolId:row.pool_id,mg:row.mg,amount:row.amount,allocations:allocations(row.allocations),snapshot:JSON.parse(JSON.stringify(JSON.parse(row.snapshot),stable))})).sort((a,b)=>a.priceLockId.localeCompare(b.priceLockId)),
returns:returns.map(row=>({priceLockId:row.price_lock_id,date:row.date,mg:row.mg,amount:row.amount,allocations:allocations(row.allocations),originPoolId:row.origin_pool_id,...(row.kind!==undefined?{kind:row.kind}:{}),...(row.same_day!==undefined?{sameDay:row.same_day}:{})})).sort((a,b)=>a.priceLockId.localeCompare(b.priceLockId)||String(a.kind??'').localeCompare(String(b.kind??''))||a.date.localeCompare(b.date))
}};
}
function finance(ledger){return ledger.scope(null,()=>financeInternal(ledger),null);}
function financeInternal(ledger){
const state=rows(ledger),result=new Map();
for(const reservation of state.reservations){
const lock=ledger.one('SELECT * FROM price_locks WHERE id=?',reservation.price_lock_id);if(!lock)continue;
const delivery=lock.delivery?JSON.parse(lock.delivery):null,order=lock.final_order_id?ledger.rawOrder(lock.final_order_id):null;
const original=order?.lines.flatMap(line=>line.materialAllocations??[]).filter(part=>part.source==='original');
result.set(lock.id,{id:lock.id,number:lock.number,date:lock.date,customer:lock.customer,member:ledger.entityMember('price_lock',lock.id),
materialAmount:reservation.amount,usedMaterialAmount:original?.length?original.reduce((sum,part)=>sum+part.amount,0):reservation.amount,leftoverCost:delivery?(delivery.leftover_cost??null):0,allocations:allocations(reservation.allocations)});
}
return result;
}
function changes(before,after){
const fields=['materialAmount','usedMaterialAmount','leftoverCost','allocations'];
return [...before].flatMap(([id,previous])=>{const next=after.get(id);if(!next||fields.every(key=>JSON.stringify(previous[key])===JSON.stringify(next[key])))return [];
return [{id,number:previous.number,date:previous.date,customer:previous.customer,member:previous.member,before:Object.fromEntries(fields.map(key=>[key,previous[key]])),after:Object.fromEntries(fields.map(key=>[key,next[key]]))}];});
}
function visibleChanges(ledger,value,actor){return actor?.role==='assistant'?value.filter(row=>ledger.canAccess('price_lock',row.id,actor)):value;}
module.exports={snapshot,effect,finance,changes,visibleChanges};
+92
View File
@@ -0,0 +1,92 @@
'use strict';
// 锁价预留只占用已有料池;不生成采购、现金、销售或实物流水。
const {randomUUID}=require('node:crypto'),Calc=require('./public/calculations');
const PARTIES=['owner','assistant','assistant2'],sum=(rows,key)=>rows.reduce((n,r)=>n+(r[key]??0),0);
function initialize(l){l.db.exec(`
CREATE TABLE IF NOT EXISTS price_lock_pool_reservations(id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL UNIQUE REFERENCES price_locks(id),pool_id TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),amount INTEGER,allocations TEXT NOT NULL DEFAULT '[]',snapshot TEXT NOT NULL DEFAULT '{}',revision INTEGER NOT NULL DEFAULT 1,created TEXT NOT NULL,updated TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS price_lock_pool_returns(id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),kind TEXT NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL,amount INTEGER,allocations TEXT NOT NULL,origin_pool_id TEXT NOT NULL,same_day INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,UNIQUE(price_lock_id,kind));
CREATE TABLE IF NOT EXISTS material_usage_order(sequence INTEGER PRIMARY KEY AUTOINCREMENT,kind TEXT NOT NULL,source_id TEXT NOT NULL,UNIQUE(kind,source_id));
INSERT INTO material_usage_order(kind,source_id) SELECT 'order',u.id FROM material_pool_usages u WHERE NOT EXISTS(SELECT 1 FROM material_usage_order s WHERE s.kind='order' AND s.source_id=u.id) ORDER BY u.created,u.rowid;
`);}
function sequence(l,kind,id){if(!l.one('SELECT sequence FROM material_usage_order WHERE kind=? AND source_id=?',kind,id))l.run('INSERT INTO material_usage_order(kind,source_id) VALUES (?,?)',kind,id);return l.one('SELECT sequence FROM material_usage_order WHERE kind=? AND source_id=?',kind,id).sequence;}
function decorate(l,rows){return rows.map(r=>({...r,fifo_sequence:l.one("SELECT sequence FROM material_usage_order WHERE kind='order' AND source_id=?",r.id)?.sequence??r.fifo_sequence}));}
function find(l,id){const r=l.one('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=?',id);return r?{...r,allocations:JSON.parse(r.allocations),snapshot:JSON.parse(r.snapshot)}:null;}
function splitParts(parts,amount){let left=amount;const taken=[],rest=[];for(const part of parts){const n=Math.min(left,part.amount);if(n)taken.push({payer:part.payer,amount:n});if(part.amount>n)rest.push({payer:part.payer,amount:part.amount-n});left-=n;}if(left)throw new Error('锁价料池付款归属不足');if(!amount&&!taken.length)taken.push({payer:parts[0]?.payer??'owner',amount:0});return {taken,rest};}
function split(snapshot,used){
if(snapshot.amount===null)return {usedMg:used,amount:null,leftoverMg:snapshot.quantity-used,leftoverCost:null,allocations:[],leftoverAllocations:[]};
const amount=Calc.poolMaterialAmount(snapshot.basisAmount,snapshot.basisMg,snapshot.prefixMg+used)-snapshot.prefixAmount;
const parts=splitParts(snapshot.allocations,amount);return {usedMg:used,amount,leftoverMg:snapshot.quantity-used,leftoverCost:snapshot.amount-amount,allocations:parts.taken,leftoverAllocations:parts.rest};
}
function detail(l,id,env){const r=find(l,id);if(!r)return null;return {...r.snapshot,revision:r.revision,frozen:r.pool_id!==env.today()};}
function reservations(l,date){return l.rows(`SELECT r.*,s.sequence AS fifo_sequence,p.number,p.customer,p.line,p.status,p.delivery,p.final_order_id,o.status AS order_status,o.returned_date FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id LEFT JOIN material_usage_order s ON s.kind='priceLock' AND s.source_id=r.id LEFT JOIN orders o ON o.id=p.final_order_id WHERE r.pool_id=? ORDER BY r.created,r.rowid`,date).map(r=>{
const snapshot=JSON.parse(r.snapshot),delivery=r.delivery?JSON.parse(r.delivery):null;
let mg=r.mg;if(delivery?.date===date)mg=delivery.original_used_mg;if(r.order_status==='returned'&&r.returned_date===date)mg=0;
const effective=snapshot.amount===undefined?{amount:null,allocations:[]}:mg===r.mg?{amount:r.amount,allocations:JSON.parse(r.allocations)}:split(snapshot,mg);
return {...r,kind:'priceLock',date,price_lock_id:r.price_lock_id,order_id:r.final_order_id,line_index:0,reserved_mg:r.mg,mg,active:mg>0?1:0,amount:effective.amount,snapshot,allocations:effective.allocations,product:JSON.parse(r.line).name,...Object.fromEntries(PARTIES.map(p=>[p+'_amount',effective.amount===null?null:sum(effective.allocations.filter(a=>a.payer===p),'amount')]))};
});}
function combined(l,date,rows){return [...decorate(l,rows),...reservations(l,date)].sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);}
function returns(l,date){return l.rows('SELECT r.*,p.number,p.customer,p.line FROM price_lock_pool_returns r JOIN price_locks p ON p.id=r.price_lock_id WHERE r.date=? ORDER BY r.created,r.rowid',date).map(r=>({...r,allocations:JSON.parse(r.allocations),product:JSON.parse(r.line).name,sourceKind:'return',cashAmount:0,payer:JSON.parse(r.allocations)[0]?.payer??'owner',sameDay:!!r.same_day,note:r.kind==='leftover'?'锁价余料回池':'锁价退货回料',source_sequence:l.one("SELECT sequence FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?",r.id)?.sequence??0}));}
function fundingParts(purchases,start,amount){let skip=start,left=amount;const result=[];for(const p of purchases)for(const part of (p.allocations??[{payer:p.payer,amount:p.amount}])){if(skip>=part.amount){skip-=part.amount;continue;}const n=Math.min(left,part.amount-skip);if(n)result.push({payer:part.payer,amount:n});left-=n;skip=0;}if(left)throw new Error('锁价料池来源金额不足');return result;}
function allocate(pool,rows,allocatePayers){
const missing=pool.totalAmount===null||sum(rows,'mg')>pool.totalMg;let mg=0,previous=0;
return rows.map(row=>{
const prefixMg=mg,prefixAmount=previous;mg+=row.mg;const cumulative=missing?null:Calc.poolMaterialAmount(pool.totalAmount,pool.totalMg,mg),amount=cumulative===null?null:cumulative-previous;
const paid=amount===null?{owner_amount:null,assistant_amount:null,assistant2_amount:null}:allocatePayers(pool.purchases.filter(p=>p.amount>0),previous,amount);
let lockSnapshot;
if(row.kind==='priceLock'){
const full=missing?null:Calc.poolMaterialAmount(pool.totalAmount,pool.totalMg,prefixMg+row.reserved_mg)-prefixAmount;
let parts=[];
if(full!==null){
if(prefixMg+row.reserved_mg<=pool.totalMg)parts=fundingParts(pool.purchases.filter(p=>p.amount>0),prefixAmount,full);
else {
// 短交已经释放的尾料可以被前序订单使用;只要求本单实际耗用有真实资金来源。
// 原预留与同日回料的尾段保持相同归属,二者净额为零,不能再次占用可用料。
parts=fundingParts(pool.purchases.filter(p=>p.amount>0),prefixAmount,amount);let tail=full-amount;
const oldTail=row.snapshot.amount===null?[]:split(row.snapshot,row.mg).leftoverAllocations;
for(const p of oldTail){const n=Math.min(tail,p.amount);if(n)parts.push({payer:p.payer,amount:n});tail-=n;}
if(tail)parts.push({payer:oldTail.at(-1)?.payer??row.snapshot.allocations?.at(-1)?.payer??paid.zero_payer??'owner',amount:tail});
}
if(full===0&&!parts.length)parts.push({payer:paid.zero_payer??'owner',amount:0});
}
lockSnapshot={poolId:pool.id,date:pool.date,quantity:row.reserved_mg,amount:full,averageRate:pool.averageRate,allocations:parts,status:full===null?'pending':'allocated',basisAmount:pool.totalAmount,basisMg:pool.totalMg,prefixMg,prefixAmount,rolling:!!pool.rolling};
}
previous=cumulative??0;const result={...row,amount,...paid,...(lockSnapshot?{lockSnapshot}:{})};if(paid.assistant2_amount===undefined)delete result.assistant2_amount;return result;
});
}
function returnRow(l,lock,kind,date,mg,amount,allocations,origin,actor,env){
if(!mg)return;const old=l.one('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind=?',lock.id,kind),id=old?.id??randomUUID();
if(old)l.run('UPDATE price_lock_pool_returns SET mg=?,amount=?,allocations=? WHERE id=?',mg,amount,JSON.stringify(allocations),id);
else {l.run('INSERT INTO price_lock_pool_returns VALUES (?,?,?,?,?,?,?,?,?,?,?)',id,lock.id,kind,date,mg,amount,JSON.stringify(allocations),origin,origin===date?1:0,actor.name,env.now());require('./rolling-material-pools').registerSource(l,'lock_return',id);}
}
function materialAllocations(snapshot,used){const part=split(snapshot,used);return part.amount===null?[]:part.allocations.map(p=>({source:'original',quantity:used,rate:snapshot.averageRate,amount:p.amount,payer:p.payer,weighted:true,poolId:snapshot.poolId}));}
function update(l,row,pool,actor,env,{skipJournalOrder=null}={}){
const snapshot=row.lockSnapshot,old=row.snapshot,changed=JSON.stringify(snapshot)!==JSON.stringify(old);if(!changed)return;
const revision=row.revision+1;l.run('UPDATE price_lock_pool_reservations SET amount=?,allocations=?,snapshot=?,revision=?,updated=? WHERE id=?',snapshot.amount,JSON.stringify(snapshot.allocations),JSON.stringify(snapshot),revision,env.now(),row.id);
l.run('UPDATE price_locks SET material_amount=COALESCE(?,material_amount),buy_rate=COALESCE(?,buy_rate),revision=revision+1,updated=? WHERE id=?',snapshot.amount,snapshot.averageRate,env.now(),row.price_lock_id);
const lock=l.one('SELECT * FROM price_locks WHERE id=?',row.price_lock_id),lockedLine=JSON.parse(lock.line);lockedLine.costParts={...lockedLine.costParts,material:snapshot.amount};lockedLine.cost=Object.values(lockedLine.costParts).some(v=>v===null)?null:sum(Object.values(lockedLine.costParts).map(amount=>({amount})),'amount');l.run('UPDATE price_locks SET line=? WHERE id=?',JSON.stringify(lockedLine),lock.id);
if(lock.final_order_id){
const order=l.rawOrder(lock.final_order_id),line=order.lines[0],delivery=JSON.parse(lock.delivery),part=split(snapshot,delivery.original_used_mg),before=line.costParts.material;
const extra=(line.materialAllocations??[]).filter(a=>a.source==='extra');line.materialAllocations=[...materialAllocations(snapshot,delivery.original_used_mg),...extra];line.priceLockPool={...snapshot,quantity:delivery.original_used_mg,amount:part.amount,allocations:part.allocations,priceLockId:lock.id};
line.costParts.material=part.amount===null?null:part.amount+sum(extra,'amount');line.cost=Object.values(line.costParts).some(v=>v===null)?null:sum(Object.values(line.costParts).map(amount=>({amount})),'amount');
l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),order.id);
const nextDelivery={...delivery,leftover_cost:part.leftoverCost};l.run('UPDATE price_locks SET delivery=? WHERE id=?',JSON.stringify(nextDelivery),lock.id);
returnRow(l,lock,'leftover',delivery.date,part.leftoverMg,part.leftoverCost,part.leftoverAllocations,snapshot.poolId,actor,env);
if(order.status==='returned')returnRow(l,lock,'goods',order.returned_date,delivery.original_used_mg,part.amount,part.allocations,snapshot.poolId,actor,env);
const delta=(line.costParts.material??0)-(before??0);if(order.id!==skipJournalOrder){if(delta&&order.status==='delivered')l.journal(order.id,order.delivered_date,'锁价料池成本调整',0,delta,0);if(delta&&order.status==='returned'){l.journal(order.id,order.delivered_date,'锁价料池原耗用调整',0,delta,0);l.journal(order.id,order.returned_date,'锁价退货成本冲回调整',0,-delta,0);}l.touch(order.id);l.dirty(order.date);}
}
l.dirty(lock.date);l.audit('price-lock:'+lock.id,'锁价料池加权更新',actor,{poolId:pool.id,before:old,after:snapshot});
}
function reserve(l,lock,pool,actor,env){
if(pool.status==='pending'||pool.totalAmount===null||pool.remainingMg<lock.locked_mg)env.fail('当日料池可用克重不足或成本待补,请先核实购料');
const id=randomUUID(),created=env.now();l.run('INSERT INTO price_lock_pool_reservations(id,price_lock_id,pool_id,mg,created,updated) VALUES (?,?,?,?,?,?)',id,lock.id,pool.id,lock.locked_mg,created,created);sequence(l,'priceLock',id);
}
function prepareDelivery(l,lock,date,used,actor,env){const reservation=find(l,lock.id);if(!reservation)return null;const snapshot=reservation.snapshot;if(snapshot.amount===null||snapshot.amount===undefined)env.fail('锁价原料池成本待补,请先核实购料后交付',409);const part=split(snapshot,used);return {...part,snapshot};}
function finishDelivery(l,lock,delivery,actor,env){const r=find(l,lock.id);if(!r)return;const part=split(r.snapshot,delivery.original_used_mg);returnRow(l,lock,'leftover',delivery.date,part.leftoverMg,part.leftoverCost,part.leftoverAllocations,r.pool_id,actor,env);}
function recordReturn(l,order,date,input,actor,env){
const lock=l.one('SELECT * FROM price_locks WHERE final_order_id=?',order.id),r=lock?find(l,lock.id):null;if(!r)return false;
const line=order.lines[0],destination=input.returnPockets?.[0]??line.pocket;if(!env.selfPockets?.includes(destination))env.fail('料池锁价黄金须退回自有货盘');
const delivery=JSON.parse(lock.delivery),part=split(r.snapshot,delivery.original_used_mg);if(part.amount===null)env.fail('锁价原料池成本待补,不能退货回料',409);
returnRow(l,lock,'goods',date,delivery.original_used_mg,part.amount,part.allocations,r.pool_id,actor,env);
const extra=(line.materialAllocations??[]).filter(a=>a.source==='extra');if(delivery.extra_mg)returnRow(l,lock,'extra',date,delivery.extra_mg,sum(extra,'amount'),extra.map(a=>({payer:a.payer,amount:a.amount})),'',actor,env);return true;
}
module.exports={initialize,sequence,decorate,find,detail,reservations,combined,returns,allocate,update,reserve,split,materialAllocations,prepareDelivery,finishDelivery,recordReturn};
+22 -14
View File
@@ -3,6 +3,7 @@
const {randomUUID}=require('node:crypto'); const {randomUUID}=require('node:crypto');
const Calc=require('./public/calculations'); const Calc=require('./public/calculations');
const CreditCardFees=require('./public/credit-card-fees'); const CreditCardFees=require('./public/credit-card-fees');
const LockPools=require('./price-lock-pools'),MaterialPools=require('./material-pools'),Rolling=require('./rolling-material-pools');
const cardFeeNote=event=>event.card_fee_note||(event.card_fee_rate?CreditCardFees.note(event.card_fee_rate):'已记录信用卡手续费'); const cardFeeNote=event=>event.card_fee_note||(event.card_fee_rate?CreditCardFees.note(event.card_fee_rate):'已记录信用卡手续费');
const paymentAccount=(value,env)=>env.pick(CreditCardFees.normalizeAccount(value),env.accounts,'实际收付款账户'); const paymentAccount=(value,env)=>env.pick(CreditCardFees.normalizeAccount(value),env.accounts,'实际收付款账户');
const yuan=value=>(value/100).toFixed(2),grams=value=>(value/1000).toFixed(3); const yuan=value=>(value/100).toFixed(2),grams=value=>(value/1000).toFixed(3);
@@ -39,7 +40,8 @@ function detail(ledger,id,env){
const cash_events=events.filter(event=>event.kind!=='material'),material_events=events.filter(event=>event.kind==='material'); const cash_events=events.filter(event=>event.kind!=='material'),material_events=events.filter(event=>event.kind==='material');
const received=cash_events.filter(event=>event.kind==='receipt').reduce((sum,event)=>sum+event.amount,0),refunded=cash_events.filter(event=>event.kind==='refund').reduce((sum,event)=>sum+event.amount,0); const received=cash_events.filter(event=>event.kind==='receipt').reduce((sum,event)=>sum+event.amount,0),refunded=cash_events.filter(event=>event.kind==='refund').reduce((sum,event)=>sum+event.amount,0);
const credit_card_fees=events.filter(event=>event.card_fee_amount!==null).map(event=>({key:'card_fee:'+event.id,system:'credit_card',source_kind:'price_lock',source_id:event.id,date:event.date,amount:event.card_fee_amount,payer:event.card_fee_payer,note:cardFeeNote(event),...(event.card_fee_rate?{rate_permille:event.card_fee_rate}:{}),...(event.card_fee_expense_id?{expense_id:event.card_fee_expense_id}:{})})); const credit_card_fees=events.filter(event=>event.card_fee_amount!==null).map(event=>({key:'card_fee:'+event.id,system:'credit_card',source_kind:'price_lock',source_id:event.id,date:event.date,amount:event.card_fee_amount,payer:event.card_fee_payer,note:cardFeeNote(event),...(event.card_fee_rate?{rate_permille:event.card_fee_rate}:{}),...(event.card_fee_expense_id?{expense_id:event.card_fee_expense_id}:{})}));
return {...row,cash_events,material_events,received,refunded,netReceived:received-refunded,credit_card_fees,credit_card_fee_total:credit_card_fees.reduce((total,fee)=>total+fee.amount,0)}; const reservation=LockPools.find(ledger,id);
return {...row,material_source:reservation?'pool':'manual',...(reservation?{material_pool_id:reservation.pool_id,materialPool:LockPools.detail(ledger,id,env)}:{}),cash_events,material_events,received,refunded,netReceived:received-refunded,credit_card_fees,credit_card_fee_total:credit_card_fees.reduce((total,fee)=>total+fee.amount,0)};
} }
function list(ledger,query,env){ 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')); const date=env.day(query.date??query.to??env.today()),from=env.day(query.from??(query.date||query.to?date:'2000-01-01'));
@@ -80,13 +82,15 @@ function create(ledger,input,actor,env){return atomic(ledger,()=>{
if(input.line.unit!==undefined&&input.line.unit!=='g')env.fail('锁价只支持按克黄金'); if(input.line.unit!==undefined&&input.line.unit!=='g')env.fail('锁价只支持按克黄金');
const date=env.day(input.date),name=env.text(input.line.name,'黄金商品名称',60); const date=env.day(input.date),name=env.text(input.line.name,'黄金商品名称',60);
if(Calc.isSilver(name))env.fail('锁价只支持黄金商品,不支持银饰'); if(Calc.isSilver(name))env.fail('锁价只支持黄金商品,不支持银饰');
const quantity=env.weight(input.line.quantity,'锁定克重'),sellRate=env.money(input.line.goldPrice,'锁定销售金价'),buyRate=env.money(input.material?.rate,'原进货料价'); const source=env.pick(input.material?.source??'manual',['manual','pool'],'进货料价来源');
let pool=null;if(source==='pool'){if(!Rolling.enabled(ledger))env.fail('请先启用统一滚动料池后选择当日加权料价');if(date!==env.today())env.fail('料池锁价请使用当前营业日,历史料池已冻结');if(input.material.poolId!==date)env.fail('料池锁价须选择锁价当日料池');pool=MaterialPools.readPool(ledger,date,env,{internal:true});if(!pool.totalMg||pool.totalAmount===null||pool.status==='pending')env.fail('当日料池尚未登记可用金料或成本待补,请先核实购料');if(input.material.revision!==pool.revision)env.fail('料池已有变动,请刷新料价后锁定',409);}
const quantity=env.weight(input.line.quantity,'锁定克重'),sellRate=env.money(input.line.goldPrice,'锁定销售金价'),buyRate=pool?.averageRate??env.money(input.material?.rate,'原进货料价');
if(quantity<=0||sellRate<=0||buyRate<=0)env.fail('锁定克重、销售金价和进货料价必须大于0'); if(quantity<=0||sellRate<=0||buyRate<=0)env.fail('锁定克重、销售金价和进货料价必须大于0');
const payer=env.pick(input.material?.payer,['owner','assistant','assistant2'],'原料付款人'); const payer=pool?(pool.purchases[0]?.allocations?.[0]?.payer??pool.purchases[0]?.payer??'owner'):env.pick(input.material?.payer,['owner','assistant','assistant2'],'原料付款人');
if(input.material?.verified!==true)env.fail('请确认原料款已实际支付'); if(!pool&&input.material?.verified!==true)env.fail('请确认原料款已实际支付');
if(input.payment?.verified!==true)env.fail('请核实客户实际付款'); if(input.payment?.verified!==true)env.fail('请核实客户实际付款');
const received=env.money(input.payment.amount,'客户实际付款'),account=paymentAccount(input.payment.account,env); const received=env.money(input.payment.amount,'客户实际付款'),account=paymentAccount(input.payment.account,env);
const costs=Calc.priceLockCost({lockedQuantity:input.line.quantity,quantity:input.line.quantity,buyRate:input.material.rate}); const costs=Calc.priceLockCost({lockedQuantity:input.line.quantity,quantity:input.line.quantity,buyRate:yuan(buyRate)});
const line=ledger.validateLines([{...input.line,name,unit:'g',pocket:'',pricingMode:'auto',payer, const line=ledger.validateLines([{...input.line,name,unit:'g',pocket:'',pricingMode:'auto',payer,
costParts:{material:yuan(costs.originalPurchase),labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'total'},costLabor:{mode:'total'},costPayers:{material:payer,labor:payer}}])[0]; costParts:{material:yuan(costs.originalPurchase),labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'total'},costLabor:{mode:'total'},costPayers:{material:payer,labor:payer}}])[0];
const discount=env.money(input.discount??'0','整单优惠'),estimated=Calc.orderTotal([line.sale],discount,'yuan'); const discount=env.money(input.discount??'0','整单优惠'),estimated=Calc.orderTotal([line.sale],discount,'yuan');
@@ -98,10 +102,11 @@ function create(ledger,input,actor,env){return atomic(ledger,()=>{
ledger.assignMember('price_lock',id,ledger.selectedMember(input,actor),{fresh:true}); ledger.assignMember('price_lock',id,ledger.selectedMember(input,actor),{fresh:true});
const lock={id,number,customer,line}; const lock={id,number,customer,line};
if(received>0)event(ledger,lock,{date,kind:'receipt',amount:received,account,credit_card_fee_payer:input.payment.credit_card_fee_payer},actor,env); if(received>0)event(ledger,lock,{date,kind:'receipt',amount:received,account,credit_card_fee_payer:input.payment.credit_card_fee_payer},actor,env);
event(ledger,lock,{date,kind:'material',source:'original',amount:costs.originalPurchase,payer,quantity,rate:buyRate},actor,env); if(pool){LockPools.reserve(ledger,{id,locked_mg:quantity},pool,actor,env);MaterialPools.reconcile(ledger,date,date,actor,env);}else event(ledger,lock,{date,kind:'material',source:'original',amount:costs.originalPurchase,payer,quantity,rate:buyRate},actor,env);
ledger.run('UPDATE closes SET stale=1 WHERE date>=?',date); ledger.run('UPDATE closes SET stale=1 WHERE date>=?',date);
ledger.audit('price-lock:'+id,'创建锁价单',actor,{number,date,quantity,sellRate,buyRate,materialPayer:payer,materialAmount:costs.originalPurchase,received,account,revision:1}); const saved=ledger.one('SELECT revision,material_amount FROM price_locks WHERE id=?',id);
return {id,price_lock_id:id,status:'pending',revision:1}; ledger.audit('price-lock:'+id,'创建锁价单',actor,{number,date,quantity,sellRate,buyRate,materialPayer:payer,materialAmount:saved.material_amount,received,account,revision:saved.revision,...(pool?{materialSource:'pool'}:{})});
return {id,price_lock_id:id,status:'pending',revision:saved.revision};
});} });}
function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号交付锁价单',403); if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号交付锁价单',403);
@@ -116,7 +121,8 @@ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
if(lineInput.goldPrice!==undefined&&env.money(lineInput.goldPrice,'销售金价')!==lock.sell_rate)env.fail('锁价销售金价不能修改'); if(lineInput.goldPrice!==undefined&&env.money(lineInput.goldPrice,'销售金价')!==lock.sell_rate)env.fail('锁价销售金价不能修改');
if(lineInput.unit!==undefined&&lineInput.unit!=='g')env.fail('锁价交付必须按实际克重'); if(lineInput.unit!==undefined&&lineInput.unit!=='g')env.fail('锁价交付必须按实际克重');
const costs=Calc.priceLockCost({lockedQuantity:grams(lock.locked_mg),quantity:lineInput.quantity,buyRate:yuan(lock.buy_rate),extraBuyRate:input.extraMaterial?.rate}); const costs=Calc.priceLockCost({lockedQuantity:grams(lock.locked_mg),quantity:lineInput.quantity,buyRate:yuan(lock.buy_rate),extraBuyRate:input.extraMaterial?.rate});
const pocket=env.pick(input.inventory?.pocket,env.pockets,'交付货盘'),originalStock=env.pick(input.inventory?.original,['receive','stocked'],'原锁定黄金库存来源'); const pooled=LockPools.prepareDelivery(ledger,lock,date,costs.originalUsedMg,actor,env);if(pooled)Object.assign(costs,{originalPurchase:pooled.snapshot.amount,originalUsedCost:pooled.amount,leftoverCost:pooled.leftoverCost,materialCost:pooled.amount+costs.extraCost});
const pocket=env.pick(input.inventory?.pocket,env.pockets,'交付货盘'),originalStock=env.pick(input.inventory?.original,['receive','stocked'],'原锁定黄金库存来源');if(pooled&&originalStock!=='stocked')env.fail('料池锁价使用已有黄金,原锁料不能重复入库');
let extraStock=null,extraPayer=null,extraRate=null; let extraStock=null,extraPayer=null,extraRate=null;
if(costs.extraMg){ if(costs.extraMg){
extraStock=env.pick(input.inventory?.extra,['receive','stocked'],'补重黄金库存来源');extraPayer=env.pick(input.extraMaterial?.payer,['owner','assistant','assistant2'],'补重料费付款人'); extraStock=env.pick(input.inventory?.extra,['receive','stocked'],'补重黄金库存来源');extraPayer=env.pick(input.extraMaterial?.payer,['owner','assistant','assistant2'],'补重料费付款人');
@@ -124,7 +130,7 @@ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
} }
const discount=env.money(input.discount??'0','整单优惠'); const discount=env.money(input.discount??'0','整单优惠');
const payers=Calc.costPayers(lineInput.costPayers); const payers=Calc.costPayers(lineInput.costPayers);
if(payers&&payers.material!==lock.buy_payer)env.fail('原锁价料费付款人不能修改'); if(!pooled&&payers&&payers.material!==lock.buy_payer)env.fail('原锁价料费付款人不能修改');
const actualLine={...lineInput,name:lock.line.name,code:lock.line.code,unit:'g',pocket,pricingMode:'auto',goldPrice:yuan(lock.sell_rate), const actualLine={...lineInput,name:lock.line.name,code:lock.line.code,unit:'g',pocket,pricingMode:'auto',goldPrice:yuan(lock.sell_rate),
costParts:{...lineInput.costParts,material:yuan(costs.materialCost)},costMaterial:{mode:'total'}, costParts:{...lineInput.costParts,material:yuan(costs.materialCost)},costMaterial:{mode:'total'},
costPayers:{material:lock.buy_payer,labor:payers?.labor??lineInput.payer}}; costPayers:{material:lock.buy_payer,labor:payers?.labor??lineInput.payer}};
@@ -142,9 +148,9 @@ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
const normal={date,customer:lock.customer,salesperson:lock.salesperson,note,discount:yuan(discount),rounding_mode:'yuan',payment_account:settlementAccount, const normal={date,customer:lock.customer,salesperson:lock.salesperson,note,discount:yuan(discount),rounding_mode:'yuan',payment_account:settlementAccount,
lines:[actualLine],fee_items:fees.map(fee=>({...fee,amount:fee.amount===null?'':yuan(fee.amount),status:'estimated'})),fees_date:date}; lines:[actualLine],fee_items:fees.map(fee=>({...fee,amount:fee.amount===null?'':yuan(fee.amount),status:'estimated'})),fees_date:date};
const finalId=env.saveDeliveryOrder(normal).id; const finalId=env.saveDeliveryOrder(normal).id;
const allocations=[{source:'original',quantity:costs.originalUsedMg,rate:lock.buy_rate,amount:costs.originalUsedCost,payer:lock.buy_payer}]; const allocations=pooled?LockPools.materialAllocations(pooled.snapshot,costs.originalUsedMg):[{source:'original',quantity:costs.originalUsedMg,rate:lock.buy_rate,amount:costs.originalUsedCost,payer:lock.buy_payer}];
if(costs.extraMg)allocations.push({source:'extra',quantity:costs.extraMg,rate:extraRate,amount:costs.extraCost,payer:extraPayer}); if(costs.extraMg)allocations.push({source:'extra',quantity:costs.extraMg,rate:extraRate,amount:costs.extraCost,payer:extraPayer});
const storedLine=ledger.rawOrder(finalId).lines[0];storedLine.materialAllocations=allocations; const storedLine=ledger.rawOrder(finalId).lines[0];storedLine.materialAllocations=allocations;if(pooled)storedLine.priceLockPool={...pooled.snapshot,priceLockId:id,quantity:costs.originalUsedMg,amount:pooled.amount,allocations:pooled.allocations};
ledger.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify([storedLine]),finalId); ledger.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify([storedLine]),finalId);
ledger.run('UPDATE price_locks SET final_order_id=? WHERE id=?',finalId,id); ledger.run('UPDATE price_locks SET final_order_id=? WHERE id=?',finalId,id);
if(difference)event(ledger,lock,{date,kind:difference>0?'receipt':'refund',amount:Math.abs(difference),account:settlementAccount,credit_card_fee_payer:input.settlement.credit_card_fee_payer},actor,env); if(difference)event(ledger,lock,{date,kind:difference>0?'receipt':'refund',amount:Math.abs(difference),account:settlementAccount,credit_card_fee_payer:input.settlement.credit_card_fee_payer},actor,env);
@@ -156,12 +162,14 @@ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
const group=randomUUID(); const group=randomUUID();
if(originalStock==='receive')ledger.move({group,order:finalId,date,pocket,mg:lock.locked_mg,kind:'lock_purchase',note:lock.number+' 原锁定黄金入库',cost:lock.material_amount},actor); if(originalStock==='receive')ledger.move({group,order:finalId,date,pocket,mg:lock.locked_mg,kind:'lock_purchase',note:lock.number+' 原锁定黄金入库',cost:lock.material_amount},actor);
if(extraStock==='receive')ledger.move({group,order:finalId,date,pocket,mg:costs.extraMg,kind:'lock_purchase',note:lock.number+' 补重黄金入库',cost:costs.extraCost},actor); if(extraStock==='receive')ledger.move({group,order:finalId,date,pocket,mg:costs.extraMg,kind:'lock_purchase',note:lock.number+' 补重黄金入库',cost:costs.extraCost},actor);
env.completeNewOrder(finalId,date);
const delivery={date,quantity:costs.finalMg,original_used_mg:costs.originalUsedMg,extra_mg:costs.extraMg,leftover_mg:costs.leftoverMg,leftover_cost:costs.leftoverCost, const delivery={date,quantity:costs.finalMg,original_used_mg:costs.originalUsedMg,extra_mg:costs.extraMg,leftover_mg:costs.leftoverMg,leftover_cost:costs.leftoverCost,
total,difference,inventory:{pocket,original:originalStock,...(extraStock?{extra:extraStock}:{})}}; total,difference,inventory:{pocket,original:originalStock,...(extraStock?{extra:extraStock}:{})}};
ledger.run("UPDATE price_locks SET status='delivered',delivery=? WHERE id=?",JSON.stringify(delivery),id);
if(pooled){LockPools.finishDelivery(ledger,{...lock,id},delivery,actor,env);MaterialPools.reconcile(ledger,date,date,actor,env,{skipJournalOrder:finalId});}
env.completeNewOrder(finalId,date);
ledger.run("UPDATE price_locks SET status='delivered',revision=revision+1,delivery=?,updated=? WHERE id=?",JSON.stringify(delivery),env.now(),id); ledger.run("UPDATE price_locks SET status='delivered',revision=revision+1,delivery=?,updated=? WHERE id=?",JSON.stringify(delivery),env.now(),id);
ledger.audit('price-lock:'+id,'锁价交付并生成销售单',actor,{...delivery,final_order_id:finalId,revision:lock.revision+1}); ledger.audit('price-lock:'+id,'锁价交付并生成销售单',actor,{...delivery,final_order_id:finalId,revision:lock.revision+1});
return {id:finalId,order_id:finalId,price_lock_id:id,status:'delivered',revision:lock.revision+1}; return {id:finalId,order_id:finalId,price_lock_id:id,status:'delivered',revision:ledger.one('SELECT revision FROM price_locks WHERE id=?',id).revision};
});} });}
function inheritedPayments(ledger,orderId){ function inheritedPayments(ledger,orderId){
return ledger.rows("SELECT e.id,? AS order_id,e.date,e.kind,e.amount,e.account,'锁价单实际收退款' AS reference,e.actor,e.created,e.id AS price_lock_event_id FROM price_lock_events e JOIN price_locks l ON l.id=e.price_lock_id WHERE l.final_order_id=? AND e.kind IN ('receipt','refund') ORDER BY e.date,e.created,e.rowid",orderId,orderId); return ledger.rows("SELECT e.id,? AS order_id,e.date,e.kind,e.amount,e.account,'锁价单实际收退款' AS reference,e.actor,e.created,e.id AS price_lock_event_id FROM price_lock_events e JOIN price_locks l ON l.id=e.price_lock_id WHERE l.final_order_id=? AND e.kind IN ('receipt','refund') ORDER BY e.date,e.created,e.rowid",orderId,orderId);
+3
View File
@@ -175,3 +175,6 @@ button.order-copy-button:focus-visible{outline:3px solid var(--gold);outline-off
/* 跨日余料统一看当前值,历史记录只作追溯。 */ /* 跨日余料统一看当前值,历史记录只作追溯。 */
.material-rolling-current{background:#edf2e9;border-color:#c9d6c3}.material-rolling-current .panel-title{gap:12px;flex-wrap:wrap}.material-rolling-totals{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px 32px;margin:20px 0}.material-rolling-totals>div{display:flex;flex-direction:column;gap:8px;min-width:0}.material-rolling-totals>div>span{font-size:13px;color:var(--muted)}.material-rolling-totals strong{font-size:34px;font-weight:650;color:var(--green);font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.material-rolling-totals strong>small{font-size:15px;font-weight:400;margin-left:7px}.material-rolling-composition{border-top:1px solid #cad6c5;padding-top:13px}.material-rolling-composition>summary{font-size:13px}.material-rolling-composition>p{line-height:1.8;margin:12px 0 0;font-variant-numeric:tabular-nums}.material-rolling-parts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:16px}.material-rolling-parts>div{display:grid;gap:5px;padding:12px;background:#f8faf6;border:1px solid #d8e0d3;border-radius:6px;font-size:12px;font-variant-numeric:tabular-nums}.material-rolling-parts strong{font-size:17px;font-weight:600}.material-rolling-rule{margin:15px 0 0;line-height:1.8}.material-rolling-start .panel-title{flex-wrap:wrap;gap:10px}.material-rolling-start>p{margin:10px 0 0;line-height:1.8}.material-rolling-history-table{min-width:700px}.material-rolling-history-table button{white-space:nowrap}.material-rolling-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px 22px;margin:18px 0}.material-rolling-facts>div{min-width:0}.material-rolling-facts dt{font-size:12px;color:var(--muted);margin-bottom:5px}.material-rolling-facts dd{margin:0;font-size:15px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}#material-rolling-dialog{width:min(900px,96vw)}#material-rolling-title{padding-right:30px}#material-rolling-dialog>p{line-height:1.8}#material-rolling-dialog .check{align-items:flex-start;line-height:1.8;margin-top:18px}#material-rolling-dialog .check>input{flex-shrink:0;margin-top:4px}.material-change-panel .panel-title{gap:12px;flex-wrap:wrap}.material-change-tabs{display:flex;gap:7px;flex-wrap:wrap;margin:14px 0}.material-change-tabs button{font-size:12px;padding:6px 11px}.material-change-table{font-size:12px;min-width:700px}.material-change-table th.number{text-align:right}.material-change-table td{vertical-align:top;font-variant-numeric:tabular-nums}.material-change-table button{font-size:12px;padding:5px 9px}.material-change-text{white-space:pre-wrap;overflow-wrap:anywhere}.material-change-comparison{min-width:600px}.material-change-comparison th:first-child{min-width:110px}.material-change-comparison td{white-space:pre-wrap;overflow-wrap:anywhere}.material-change-different{background:#f9f1df}.material-change-impact{margin-top:20px}.material-change-impact h3{font-size:14px;margin:17px 0 10px}.material-change-impact>p{line-height:1.8}.material-change-review-form>label{margin-top:18px}.material-rolling-empty{margin:12px 0 0} .material-rolling-current{background:#edf2e9;border-color:#c9d6c3}.material-rolling-current .panel-title{gap:12px;flex-wrap:wrap}.material-rolling-totals{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px 32px;margin:20px 0}.material-rolling-totals>div{display:flex;flex-direction:column;gap:8px;min-width:0}.material-rolling-totals>div>span{font-size:13px;color:var(--muted)}.material-rolling-totals strong{font-size:34px;font-weight:650;color:var(--green);font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.material-rolling-totals strong>small{font-size:15px;font-weight:400;margin-left:7px}.material-rolling-composition{border-top:1px solid #cad6c5;padding-top:13px}.material-rolling-composition>summary{font-size:13px}.material-rolling-composition>p{line-height:1.8;margin:12px 0 0;font-variant-numeric:tabular-nums}.material-rolling-parts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:16px}.material-rolling-parts>div{display:grid;gap:5px;padding:12px;background:#f8faf6;border:1px solid #d8e0d3;border-radius:6px;font-size:12px;font-variant-numeric:tabular-nums}.material-rolling-parts strong{font-size:17px;font-weight:600}.material-rolling-rule{margin:15px 0 0;line-height:1.8}.material-rolling-start .panel-title{flex-wrap:wrap;gap:10px}.material-rolling-start>p{margin:10px 0 0;line-height:1.8}.material-rolling-history-table{min-width:700px}.material-rolling-history-table button{white-space:nowrap}.material-rolling-facts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px 22px;margin:18px 0}.material-rolling-facts>div{min-width:0}.material-rolling-facts dt{font-size:12px;color:var(--muted);margin-bottom:5px}.material-rolling-facts dd{margin:0;font-size:15px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}#material-rolling-dialog{width:min(900px,96vw)}#material-rolling-title{padding-right:30px}#material-rolling-dialog>p{line-height:1.8}#material-rolling-dialog .check{align-items:flex-start;line-height:1.8;margin-top:18px}#material-rolling-dialog .check>input{flex-shrink:0;margin-top:4px}.material-change-panel .panel-title{gap:12px;flex-wrap:wrap}.material-change-tabs{display:flex;gap:7px;flex-wrap:wrap;margin:14px 0}.material-change-tabs button{font-size:12px;padding:6px 11px}.material-change-table{font-size:12px;min-width:700px}.material-change-table th.number{text-align:right}.material-change-table td{vertical-align:top;font-variant-numeric:tabular-nums}.material-change-table button{font-size:12px;padding:5px 9px}.material-change-text{white-space:pre-wrap;overflow-wrap:anywhere}.material-change-comparison{min-width:600px}.material-change-comparison th:first-child{min-width:110px}.material-change-comparison td{white-space:pre-wrap;overflow-wrap:anywhere}.material-change-different{background:#f9f1df}.material-change-impact{margin-top:20px}.material-change-impact h3{font-size:14px;margin:17px 0 10px}.material-change-impact>p{line-height:1.8}.material-change-review-form>label{margin-top:18px}.material-rolling-empty{margin:12px 0 0}
@media(max-width:650px){.material-rolling-current{padding:18px 14px}.material-rolling-totals{gap:12px;margin:17px 0}.material-rolling-totals>div>span{font-size:11px}.material-rolling-totals strong{font-size:26px}.material-rolling-totals strong>small{font-size:12px;margin-left:4px}.material-rolling-parts{grid-template-columns:1fr}.material-rolling-parts>div{grid-template-columns:1.4fr 1fr 1fr;align-items:center;gap:8px}.material-rolling-parts strong{font-size:14px}.material-rolling-parts>div>span:last-child{text-align:right}.material-rolling-facts{gap:14px}.material-rolling-facts dd{font-size:14px}#material-rolling-dialog{padding:23px 16px}.material-change-panel .panel-title>button{font-size:12px;padding:7px 9px}.material-change-tabs{gap:6px}.material-change-tabs button{font-size:11px;padding:6px 8px}} @media(max-width:650px){.material-rolling-current{padding:18px 14px}.material-rolling-totals{gap:12px;margin:17px 0}.material-rolling-totals>div>span{font-size:11px}.material-rolling-totals strong{font-size:26px}.material-rolling-totals strong>small{font-size:12px;margin-left:4px}.material-rolling-parts{grid-template-columns:1fr}.material-rolling-parts>div{grid-template-columns:1.4fr 1fr 1fr;align-items:center;gap:8px}.material-rolling-parts strong{font-size:14px}.material-rolling-parts>div>span:last-child{text-align:right}.material-rolling-facts{gap:14px}.material-rolling-facts dd{font-size:14px}#material-rolling-dialog{padding:23px 16px}.material-change-panel .panel-title>button{font-size:12px;padding:7px 9px}.material-change-tabs{gap:6px}.material-change-tabs button{font-size:11px;padding:6px 8px}}
@media screen{.price-lock-material>.material-source-row{margin-bottom:16px}.price-lock-material-payers{display:flex;gap:6px 16px;flex-wrap:wrap;line-height:1.8;margin:10px 0 16px}.price-lock-material-payers>span{white-space:nowrap}.price-lock-material-payers b{font-variant-numeric:tabular-nums}.price-lock-material .actions{margin-top:12px}.lock-pool-delivery-payers{margin-bottom:0}.price-lock-list td:nth-child(6){min-width:175px;line-height:1.7}.price-lock-facts small{overflow-wrap:anywhere}}
@media screen and (max-width:650px){.price-lock-material>.material-source-row>label{flex-basis:100%}.price-lock-material-payers{gap:5px 12px}.price-lock-material>.material-source-row{gap:8px}}
+16 -2
View File
@@ -1031,11 +1031,24 @@ async function copyOrder(id,source){
$('#order-dialog')?.close();await render();$('#order-form [name="customer"]')?.focus();toast('已复制为新单,请修改并核对后再生成销售单据'); $('#order-dialog')?.close();await render();$('#order-form [name="customer"]')?.focus();toast('已复制为新单,请修改并核对后再生成销售单据');
}finally{orderCopyLoading=false;} }finally{orderCopyLoading=false;}
} }
function validateRelatedPriceLocks(items){
if(items===undefined)return [];
const amount=value=>value===null||Number.isSafeInteger(value)&&value>=0;
const snapshot=value=>value&&amount(value.materialAmount)&&['usedMaterialAmount','leftoverCost'].every(key=>!Object.hasOwn(value,key)||amount(value[key]))&&Array.isArray(value.allocations)&&value.allocations.every(part=>['owner','assistant','assistant2'].includes(part.payer)&&Number.isSafeInteger(part.amount)&&part.amount>=0)&&(value.materialAmount===null||value.allocations.reduce((sum,part)=>sum+part.amount,0)===value.materialAmount);
if(!Array.isArray(items)||!items.every(item=>item&&typeof item.id==='string'&&item.id&&validOrderDate(item.date)&&snapshot(item.before)&&snapshot(item.after)))throw new Error('关联锁价单的成本影响未完整返回,请重新读取后复核。');
return items;
}
function relatedPriceLocksHTML(items){
const locks=validateRelatedPriceLocks(items);if(!locks.length)return '';
const money=value=>value===null?'待补齐':'¥'+yuan(value),sources=value=>value.allocations.length?value.allocations.map(part=>teamMemberName(part.payer)+' '+money(part.amount)).join(';'):value.materialAmount===null?'待补齐后分摊':'无分摊金额';
const pair=(name,before,after)=>`<tr><th scope="row">${e(name)}</th><td>${e(before)}</td><td>${e(after)}</td></tr>`;
return `<section class="price-lock-related-impact"><h3>同时受影响的锁价单(${locks.length} 张)</h3><p class="small muted">以下只调整料池成本和付款归属,客户锁定售价与实际收付款保持原记录。</p>${locks.map(lock=>`<h3>${e(lock.date)} · ${e(lock.number||lock.id)}${lock.customer?' · '+e(lock.customer):''}</h3><div class="table-wrap"><table class="material-detail-table material-change-comparison" aria-label="关联锁价单成本影响"><thead><tr><th>核对项目</th><th>变更前</th><th>批准后</th></tr></thead><tbody>${pair('原锁预留料费',money(lock.before.materialAmount),money(lock.after.materialAmount))}${['before','after'].some(side=>Object.hasOwn(lock[side],'usedMaterialAmount'))?pair('交付耗用原锁料费',Object.hasOwn(lock.before,'usedMaterialAmount')?money(lock.before.usedMaterialAmount):'未交付',Object.hasOwn(lock.after,'usedMaterialAmount')?money(lock.after.usedMaterialAmount):'未交付'):''}${['before','after'].some(side=>Object.hasOwn(lock[side],'leftoverCost'))?pair('少重回池成本',Object.hasOwn(lock.before,'leftoverCost')?money(lock.before.leftoverCost):'未交付',Object.hasOwn(lock.after,'leftoverCost')?money(lock.after.leftoverCost):'未交付'):''}${pair('自动付款归属',sources(lock.before),sources(lock.after))}</tbody></table></div>`).join('')}</section>`;
}
function orderDetailCostSummary(o){ function orderDetailCostSummary(o){
const costs=LedgerCalc.orderCosts(o),rows=[],pools=new Map(); const costs=LedgerCalc.orderCosts(o),rows=[],pools=new Map();
// 日购料的每条分摊共用整行克重,先合并,再展示付款人各自承担的金额。 // 日购料的每条分摊共用整行克重,先合并,再展示付款人各自承担的金额。
for(const row of costs.rows){ for(const row of costs.rows){
if(row.materialPoolId&&row.calculation?.weighted){ if((row.materialPoolId||row.priceLockSource)&&row.calculation?.weighted){
const key=row.source,existing=pools.get(key); const key=row.source,existing=pools.get(key);
if(existing){existing.amount+=row.amount;existing.allocations.push({payer:row.payer,amount:row.amount});} if(existing){existing.amount+=row.amount;existing.allocations.push({payer:row.payer,amount:row.amount});}
else{const grouped={...row,allocations:[{payer:row.payer,amount:row.amount}]};pools.set(key,grouped);rows.push(grouped);} else{const grouped={...row,allocations:[{payer:row.payer,amount:row.amount}]};pools.set(key,grouped);rows.push(grouped);}
@@ -1626,6 +1639,7 @@ document.addEventListener('click',async ev=>{
if(a==='new-material-purchase'){$('#main').innerHTML=materialPoolsPageHTML(materialPoolsCache);return;} if(a==='new-material-purchase'){$('#main').innerHTML=materialPoolsPageHTML(materialPoolsCache);return;}
if(a==='toggle-material-pool'){materialPoolsOpenDate=materialPoolsOpenDate===b.dataset.id?'':b.dataset.id;if(materialPoolsCache&&$('#material-pools-content'))$('#material-pools-content').innerHTML=materialPoolListHTML(materialPoolsCache);return;} if(a==='toggle-material-pool'){materialPoolsOpenDate=materialPoolsOpenDate===b.dataset.id?'':b.dataset.id;if(materialPoolsCache&&$('#material-pools-content'))$('#material-pools-content').innerHTML=materialPoolListHTML(materialPoolsCache);return;}
if(a==='reload-material-choices')return await loadMaterialPoolChoices(true); if(a==='reload-material-choices')return await loadMaterialPoolChoices(true);
if(a==='reload-price-lock-pool')return await loadPriceLockPoolChoices(true);
if(a==='edit-material-purchase'||a==='delete-material-purchase')return await showMaterialPurchaseChange(b.dataset.id,a==='delete-material-purchase'?'delete':'edit'); if(a==='edit-material-purchase'||a==='delete-material-purchase')return await showMaterialPurchaseChange(b.dataset.id,a==='delete-material-purchase'?'delete':'edit');
if(a==='reload-material-purchase')return await showMaterialPurchaseChange(b.dataset.id,b.dataset.kind); if(a==='reload-material-purchase')return await showMaterialPurchaseChange(b.dataset.id,b.dataset.kind);
if(a==='close-material-purchase'){closeMaterialPurchaseDialog();return;} if(a==='close-material-purchase'){closeMaterialPurchaseDialog();return;}
@@ -1797,6 +1811,6 @@ document.addEventListener('submit',async ev=>{
if(typeof orderActionUsesChangeForm==='function'&&orderActionUsesChangeForm(kind))return await submitOrderActionChange(form,input); if(typeof orderActionUsesChangeForm==='function'&&orderActionUsesChangeForm(kind))return await submitOrderActionChange(form,input);
const id=currentOrder.id,detailContext=captureOrderDetailReload(id);await mutate('/api/orders/'+id+'/'+kind,input);invalidateMaterialPools();await refreshOrderDetailAfterSave(id,detailContext);return toast(actionName[kind]+'已保存'); const id=currentOrder.id,detailContext=captureOrderDetailReload(id);await mutate('/api/orders/'+id+'/'+kind,input);invalidateMaterialPools();await refreshOrderDetailAfterSave(id,detailContext);return toast(actionName[kind]+'已保存');
} }
}catch(err){if(['after-sale-edit-form','after-sale-review-form'].includes(form.id))return afterSaleOperationError(err);if(['material-rolling-enable-form','material-change-review-form'].includes(form.id))return materialRollingError(form,err);if(['inventory-change-form','inventory-change-review-form'].includes(form.id))return inventoryChangeError(err,inventoryChangeReview?{id:inventoryChangeReview.request.id,review:true}:inventoryChangeEntry?{id:inventoryChangeEntry.id,kind:inventoryChangeEntry.kind}:null);if(form.id==='action-form'&&form.dataset.orderChange==='true')return orderActionChangeError(err);if(form.id==='order-ownership-form')return orderOwnershipError(err);if(form.id==='order-change-form')return orderChangeError(err);if(form.id==='order-cancellation-form')return orderCancellationError(err);if(form.id==='order-edit-meta-form'||form.id==='order-form'&&form.dataset.orderEdit==='true')return orderEditError(err);if(form.id==='material-purchase-edit-form'||form.id==='material-purchase-delete-form')return materialPurchaseChangeError(form,err);if(form.id.startsWith('material-')){err.message=err.message.replace('不要重新开单','不要重复登记');toast(err.message,true);const target=form.id==='material-purchase-form'?$('#material-purchase-error'):$('#material-settlement-error');if(target)target.innerHTML=`<div class="error">${e(err.message)}${err.status===409?' '+button('关闭并重新读取该日购料','reload-material-settlement','quiet'):''}</div>`;return;}if(form.id==='people-count-form'&&err.status===409){await loadPeopleCount('人数已被更新,已显示当前值,请核对后再保存。');return toast('人数已被更新,请核对当前值后再保存。',true);}if(form.id==='people-count-form')err.message=err.message.replace('不要重新开单','不要重复记录人数');if(form.id==='after-sale-form')err.message=err.message.replace('不要重新开单','不要重复新增售后');if(form.id.startsWith('price-lock-'))err.message=err.message.replace('不要重新开单','不要重复锁价或交付');toast(err.message,true);if(form.id.startsWith('price-lock-')&&$('#price-lock-error'))$('#price-lock-error').innerHTML=`<div class="error">${e(err.message)}${err.status===409&&form.dataset.id?' '+button('重新读取锁价单','deliver-price-lock','',`data-id="${e(form.dataset.id)}"`):''}</div>`;else if(form.id==='people-count-form'&&$('#people-count-error'))$('#people-count-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='after-sale-form'&&$('#after-sale-error'))$('#after-sale-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='print-settings'&&$('#print-settings-error'))$('#print-settings-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id.endsWith('login-form')||form.id==='setup-form')$('#login-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='order-form')$('#order-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='stock-form'&&$('#stock-error'))$('#stock-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if($('#detail-error')&&form.id==='action-form')$('#detail-error').innerHTML=`<div class="error">${e(err.message)}${pending()?' '+button('恢复原操作','retry','danger'):''}</div>`;} }catch(err){if(['after-sale-edit-form','after-sale-review-form'].includes(form.id))return afterSaleOperationError(err);if(['material-rolling-enable-form','material-change-review-form'].includes(form.id))return materialRollingError(form,err);if(['inventory-change-form','inventory-change-review-form'].includes(form.id))return inventoryChangeError(err,inventoryChangeReview?{id:inventoryChangeReview.request.id,review:true}:inventoryChangeEntry?{id:inventoryChangeEntry.id,kind:inventoryChangeEntry.kind}:null);if(form.id==='action-form'&&form.dataset.orderChange==='true')return orderActionChangeError(err);if(form.id==='order-ownership-form')return orderOwnershipError(err);if(form.id==='order-change-form')return orderChangeError(err);if(form.id==='order-cancellation-form')return orderCancellationError(err);if(form.id==='order-edit-meta-form'||form.id==='order-form'&&form.dataset.orderEdit==='true')return orderEditError(err);if(form.id==='material-purchase-edit-form'||form.id==='material-purchase-delete-form')return materialPurchaseChangeError(form,err);if(form.id.startsWith('material-')){err.message=err.message.replace('不要重新开单','不要重复登记');toast(err.message,true);const target=form.id==='material-purchase-form'?$('#material-purchase-error'):$('#material-settlement-error');if(target)target.innerHTML=`<div class="error">${e(err.message)}${err.status===409?' '+button('关闭并重新读取该日购料','reload-material-settlement','quiet'):''}</div>`;return;}if(form.id==='people-count-form'&&err.status===409){await loadPeopleCount('人数已被更新,已显示当前值,请核对后再保存。');return toast('人数已被更新,请核对当前值后再保存。',true);}if(form.id==='people-count-form')err.message=err.message.replace('不要重新开单','不要重复记录人数');if(form.id==='after-sale-form')err.message=err.message.replace('不要重新开单','不要重复新增售后');if(form.id.startsWith('price-lock-'))err.message=err.message.replace('不要重新开单','不要重复锁价或交付');toast(err.message,true);if(form.id.startsWith('price-lock-')&&$('#price-lock-error'))$('#price-lock-error').innerHTML=`<div class="error">${e(err.message)}${err.status===409?(form.dataset.id?' '+button('重新读取锁价单','deliver-price-lock','',`data-id="${e(form.dataset.id)}"`):form.querySelector('[name="material_source"]')?.value==='pool'?' '+button('刷新料池后重新核对','reload-price-lock-pool','quiet'):''):''}</div>`;else if(form.id==='people-count-form'&&$('#people-count-error'))$('#people-count-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='after-sale-form'&&$('#after-sale-error'))$('#after-sale-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='print-settings'&&$('#print-settings-error'))$('#print-settings-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id.endsWith('login-form')||form.id==='setup-form')$('#login-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='order-form')$('#order-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if(form.id==='stock-form'&&$('#stock-error'))$('#stock-error').innerHTML=`<div class="error">${e(err.message)}</div>`;else if($('#detail-error')&&form.id==='action-form')$('#detail-error').innerHTML=`<div class="error">${e(err.message)}${pending()?' '+button('恢复原操作','retry','danger'):''}</div>`;}
}); });
init(); init();
+5 -4
View File
@@ -132,7 +132,7 @@
indices.add(entry.lineIndex); indices.add(entry.lineIndex);
} }
const originals=orderId?allUsages.filter(usage=>usage.order_id===orderId):[]; 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 usages=pool.usages.filter(usage=>usage.active&&(!orderId||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 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])); const covered=pool.totalMg>0&&usedMg+wantedMg<=pool.totalMg,amounts=Object.fromEntries(entries.map(entry=>[entry.lineIndex,null]));
for(const entry of entries){ for(const entry of entries){
@@ -184,7 +184,8 @@
const payers=costPayers(line.costPayers); const payers=costPayers(line.costPayers);
const parts=line.costParts?Object.entries(costLabels).map(([key,name])=>({key,name,amount:line.costParts[key]??null})):[{key:'total',name:'货品成本(原单未分项)',amount:line.cost??null}]; const parts=line.costParts?Object.entries(costLabels).map(([key,name])=>({key,name,amount:line.costParts[key]??null})):[{key:'total',name:'货品成本(原单未分项)',amount:line.cost??null}];
for(const part of parts){ for(const part of parts){
if(part.key==='material'&&line.costMaterial?.mode==='pool'){ if(part.key==='material'&&line.priceLockPool&&part.amount===null){add({kind:'goods',component:'material',name:part.name,source:'锁价料池成本待补',amount:null,payer:payers?.material??line.payer,excluded:goodsExcluded,materialPoolId:line.priceLockPool.poolId,poolPending:true,calculation:null});
}else if(part.key==='material'&&line.costMaterial?.mode==='pool'){
const pool=line.materialPool,allocations=pool?.allocations; const pool=line.materialPool,allocations=pool?.allocations;
if(part.amount===null||!allocations?.length){ if(part.amount===null||!allocations?.length){
add({kind:'goods',component:'material',name:part.name,source:`商品 ${i+1} · ${line.name} · ${line.costMaterial.poolId}日购料待补`,amount:null,payer:payers?.material??line.payer,excluded:goodsExcluded,materialPoolId:line.costMaterial.poolId,materialPoolRevision:pool?.revision,poolPending:true,calculation:null}); add({kind:'goods',component:'material',name:part.name,source:`商品 ${i+1} · ${line.name} · ${line.costMaterial.poolId}日购料待补`,amount:null,payer:payers?.material??line.payer,excluded:goodsExcluded,materialPoolId:line.costMaterial.poolId,materialPoolRevision:pool?.revision,poolPending:true,calculation:null});
@@ -195,8 +196,8 @@
}else if(part.key==='material'&&line.materialAllocations){ }else if(part.key==='material'&&line.materialAllocations){
const allocations=line.materialAllocations; const allocations=line.materialAllocations;
if(!Array.isArray(allocations)||!allocations.length||allocations.some(item=>!['original','extra'].includes(item.source)||!['owner','assistant','assistant2'].includes(item.payer)||!Number.isSafeInteger(item.amount)||item.amount<0||!Number.isSafeInteger(item.quantity)||item.quantity<=0||!Number.isSafeInteger(item.rate)||item.rate<=0)||allocations.reduce((total,item)=>total+item.amount,0)!==part.amount)throw new Error('锁价分项料费记录无效'); if(!Array.isArray(allocations)||!allocations.length||allocations.some(item=>!['original','extra'].includes(item.source)||!['owner','assistant','assistant2'].includes(item.payer)||!Number.isSafeInteger(item.amount)||item.amount<0||!Number.isSafeInteger(item.quantity)||item.quantity<=0||!Number.isSafeInteger(item.rate)||item.rate<=0)||allocations.reduce((total,item)=>total+item.amount,0)!==part.amount)throw new Error('锁价分项料费记录无效');
for(const item of allocations)add({kind:'goods',component:'material',name:part.name,source:`商品 ${i+1} · ${line.name} · ${item.source==='original'?'原锁价采购':'补重采购'}`,amount:item.amount,payer:item.payer,excluded:goodsExcluded, for(const item of allocations)add({kind:'goods',component:'material',name:part.name,source:`商品 ${i+1} · ${line.name} · ${item.source==='original'?(item.weighted?'原锁日料池':'原锁价采购'):'补重采购'}`,amount:item.amount,payer:item.payer,excluded:goodsExcluded,
priceLockSource:item.source,calculation:{rate:item.rate,quantity:item.quantity}}); priceLockSource:item.source,...(item.poolId?{materialPoolId:item.poolId}:{}),calculation:{rate:item.rate,quantity:item.quantity,...(item.weighted?{weighted:true}:{} )}});
}else add({kind:'goods',name:part.name,source:`商品 ${i+1} · ${line.name}`,amount:part.amount,payer:payers?.[part.key]??line.payer,excluded:goodsExcluded, }else add({kind:'goods',name:part.name,source:`商品 ${i+1} · ${line.name}`,amount:part.amount,payer:payers?.[part.key]??line.payer,excluded:goodsExcluded,
calculation:part.key==='material'&&line.recovery_id&&line.costMaterial?.rate!==undefined?{rate:line.costMaterial.rate,quantity:line.recoveryMaterialMg}:part.key==='material'&&line.costMaterial?.mode==='gram'?{rate:line.costMaterial.rate,quantity:line.quantity}:part.key==='labor'&&line.costLabor?.mode==='gram'?{rate:line.costLabor.rate,quantity:line.quantity}:null}); calculation:part.key==='material'&&line.recovery_id&&line.costMaterial?.rate!==undefined?{rate:line.costMaterial.rate,quantity:line.recoveryMaterialMg}:part.key==='material'&&line.costMaterial?.mode==='gram'?{rate:line.costMaterial.rate,quantity:line.quantity}:part.key==='labor'&&line.costLabor?.mode==='gram'?{rate:line.costLabor.rate,quantity:line.quantity}:null});
} }
+8 -3
View File
@@ -175,6 +175,7 @@ function materialChangePanelHTML(){
function validateMaterialChangeRequest(row,full=false){ function validateMaterialChangeRequest(row,full=false){
if(!row||typeof row.id!=='string'||!row.id||!Object.hasOwn(materialChangeStatuses,row.status)||!['edit','delete'].includes(row.action)||!Number.isSafeInteger(row.purchase_revision)||row.purchase_revision<1||typeof row.reason!=='string'||typeof row.requester_name!=='string'||typeof row.created!=='string')throw new Error('购料更正申请未完整返回,请重新读取。'); if(!row||typeof row.id!=='string'||!row.id||!Object.hasOwn(materialChangeStatuses,row.status)||!['edit','delete'].includes(row.action)||!Number.isSafeInteger(row.purchase_revision)||row.purchase_revision<1||typeof row.reason!=='string'||typeof row.requester_name!=='string'||typeof row.created!=='string')throw new Error('购料更正申请未完整返回,请重新读取。');
if(full){ if(full){
validateRelatedPriceLocks(row.preview?.relatedPriceLocks);
const value=row.preview,validPurchase=item=>item&&typeof item.id==='string'&&validOrderDate(item.date)&&['mg','amount','revision'].every(key=>Number.isSafeInteger(item[key])&&item[key]>0)&&['owner','assistant','assistant2'].includes(item.payer)&&typeof item.note==='string'; const value=row.preview,validPurchase=item=>item&&typeof item.id==='string'&&validOrderDate(item.date)&&['mg','amount','revision'].every(key=>Number.isSafeInteger(item[key])&&item[key]>0)&&['owner','assistant','assistant2'].includes(item.payer)&&typeof item.note==='string';
const validOrder=item=>item&&['total','netReceived'].every(key=>Number.isSafeInteger(item[key]))&&['goodsCost','profit','settlementDue','ownerCost'].every(key=>item[key]===null||Number.isSafeInteger(item[key])); const validOrder=item=>item&&['total','netReceived'].every(key=>Number.isSafeInteger(item[key]))&&['goodsCost','profit','settlementDue','ownerCost'].every(key=>item[key]===null||Number.isSafeInteger(item[key]));
if(typeof row.stale!=='boolean'||typeof row.canApprove!=='boolean'||!value||!validPurchase(value.before)||(row.action==='delete'?value.after!==null:!validPurchase(value.after))||!Array.isArray(value.relatedOrders)||!value.relatedOrders.every(item=>typeof item.id==='string'&&validOrderDate(item.date)&&validOrder(item.before)&&validOrder(item.after))||!Array.isArray(value.affectedDates)||!value.affectedDates.every(validOrderDate)||!Number.isSafeInteger(value.summary?.affectedOrderCount)||value.summary.affectedOrderCount<0||!['goodsDelta','profitDelta'].every(key=>state.user.role!=='owner'&&!Object.hasOwn(value.summary,key)||value.summary[key]===null||Number.isSafeInteger(value.summary[key])))throw new Error('购料更正影响未完整返回,请重新读取后复核。'); if(typeof row.stale!=='boolean'||typeof row.canApprove!=='boolean'||!value||!validPurchase(value.before)||(row.action==='delete'?value.after!==null:!validPurchase(value.after))||!Array.isArray(value.relatedOrders)||!value.relatedOrders.every(item=>typeof item.id==='string'&&validOrderDate(item.date)&&validOrder(item.before)&&validOrder(item.after))||!Array.isArray(value.affectedDates)||!value.affectedDates.every(validOrderDate)||!Number.isSafeInteger(value.summary?.affectedOrderCount)||value.summary.affectedOrderCount<0||!['goodsDelta','profitDelta'].every(key=>state.user.role!=='owner'&&!Object.hasOwn(value.summary,key)||value.summary[key]===null||Number.isSafeInteger(value.summary[key])))throw new Error('购料更正影响未完整返回,请重新读取后复核。');
@@ -196,7 +197,7 @@ function materialChangePurchaseComparisonHTML(before,after){
} }
function materialChangeImpactHTML(preview){ function materialChangeImpactHTML(preview){
const orders=preview.relatedOrders||[],summary=preview.summary; const orders=preview.relatedOrders||[],summary=preview.summary;
return `<section class="material-change-impact"><h3>服务器核算的订单影响</h3><p class="small muted">${summary?`受影响 ${summary.affectedOrderCount} 单。${Object.hasOwn(summary,'goodsDelta')&&Object.hasOwn(summary,'profitDelta')?`金料成本合计变化 ${materialRollingMoney(summary.goodsDelta)},利润合计变化 ${materialRollingMoney(summary.profitDelta)}。`:''}`:''}${preview.affectedDates?.length?'涉及日期:'+preview.affectedDates.map(e).join('、')+'。':''}</p>${orders.length?orders.map(order=>`<h3>${e(order.date)} · ${e(order.number||order.id)}</h3><div class="table-wrap"><table class="material-detail-table material-change-comparison" aria-label="关联订单成本影响"><thead><tr><th>核对项目</th><th>变更前</th><th>批准后</th></tr></thead><tbody>${[['金料及货品成本','goodsCost'],['利润','profit'],['待结净额','settlementDue'],['麦麦垫资成本','ownerCost'],['订单成交金额','total'],['客户收款净额','netReceived']].map(([title,key])=>materialChangePair(title,materialRollingMoney(order.before[key]),materialRollingMoney(order.after[key]))).join('')}</tbody></table></div>`).join(''):`<p class="small muted">${summary?.affectedOrderCount?'当前账号没有可查看的关联订单金额明细。':'本次没有订单金额变化。'}</p>`}</section>`; return `<section class="material-change-impact"><h3>服务器核算的订单影响</h3><p class="small muted">${summary?`受影响 ${summary.affectedOrderCount} 单。${Object.hasOwn(summary,'goodsDelta')&&Object.hasOwn(summary,'profitDelta')?`金料成本合计变化 ${materialRollingMoney(summary.goodsDelta)},利润合计变化 ${materialRollingMoney(summary.profitDelta)}。`:''}`:''}${preview.affectedDates?.length?'涉及日期:'+preview.affectedDates.map(e).join('、')+'。':''}</p>${orders.length?orders.map(order=>`<h3>${e(order.date)} · ${e(order.number||order.id)}</h3><div class="table-wrap"><table class="material-detail-table material-change-comparison" aria-label="关联订单成本影响"><thead><tr><th>核对项目</th><th>变更前</th><th>批准后</th></tr></thead><tbody>${[['金料及货品成本','goodsCost'],['利润','profit'],['待结净额','settlementDue'],['麦麦垫资成本','ownerCost'],['订单成交金额','total'],['客户收款净额','netReceived']].map(([title,key])=>materialChangePair(title,materialRollingMoney(order.before[key]),materialRollingMoney(order.after[key]))).join('')}</tbody></table></div>`).join(''):`<p class="small muted">${summary?.affectedOrderCount?'当前账号没有可查看的关联订单金额明细。':'本次没有订单金额变化。'}</p>`}${relatedPriceLocksHTML(preview.relatedPriceLocks)}</section>`;
} }
function materialChangeReviewHTML(row){ function materialChangeReviewHTML(row){
const pending=row.status==='pending',owner=state.user.role==='owner',canApprove=pending&&owner&&row.canApprove&&!row.stale; const pending=row.status==='pending',owner=state.user.role==='owner',canApprove=pending&&owner&&row.canApprove&&!row.stale;
@@ -275,9 +276,13 @@ function materialPoolSettlementHTML(pool){
const due=value.settlementDue,pending=value.pending||due==null,events=pool.settlements||[]; const due=value.settlementDue,pending=value.pending||due==null,events=pool.settlements||[];
return `<div class="material-pool-settlement"><div class="material-settlement-line"><strong>本批金料与助理结算</strong><span>助理垫付的剩余料款 ${value.assistantInventoryCredit==null?'待补采购':'¥'+yuan(value.assistantInventoryCredit)}</span><span>${pending?'采购未覆盖耗用,结算待补':due===0?'已结清':(due<0?'麦麦待转回助理':'助理待交麦麦')+' ¥'+yuan(Math.abs(due))}</span>${!pending&&due!==0?button('登记实际交款/返款','material-pool-settlement','',`data-id="${e(pool.id)}"`):''}</div>${events.length?`<div class="table-wrap"><table class="material-detail-table"><thead><tr><th>日期</th><th>实际交款/返款</th><th class="number">金额</th><th>备注</th></tr></thead><tbody>${events.map(item=>`<tr><td>${e(item.date)}</td><td>${item.amount<0?'麦麦 → 助理':'助理 → 麦麦'}</td><td class="number">¥${yuan(Math.abs(item.amount))}</td><td>${e(item.note)}</td></tr>`).join('')}</tbody></table></div>`:''}</div>`; return `<div class="material-pool-settlement"><div class="material-settlement-line"><strong>本批金料与助理结算</strong><span>助理垫付的剩余料款 ${value.assistantInventoryCredit==null?'待补采购':'¥'+yuan(value.assistantInventoryCredit)}</span><span>${pending?'采购未覆盖耗用,结算待补':due===0?'已结清':(due<0?'麦麦待转回助理':'助理待交麦麦')+' ¥'+yuan(Math.abs(due))}</span>${!pending&&due!==0?button('登记实际交款/返款','material-pool-settlement','',`data-id="${e(pool.id)}"`):''}</div>${events.length?`<div class="table-wrap"><table class="material-detail-table"><thead><tr><th>日期</th><th>实际交款/返款</th><th class="number">金额</th><th>备注</th></tr></thead><tbody>${events.map(item=>`<tr><td>${e(item.date)}</td><td>${item.amount<0?'麦麦 → 助理':'助理 → 麦麦'}</td><td class="number">¥${yuan(Math.abs(item.amount))}</td><td>${e(item.note)}</td></tr>`).join('')}</tbody></table></div>`:''}</div>`;
} }
function materialPoolUsagePayersText(item){
const parts=item.allocations||['owner','assistant','assistant2'].filter(payer=>Number.isSafeInteger(item[payer+'_amount'])).map(payer=>({payer,amount:item[payer+'_amount']}));
return parts.length?parts.map(part=>materialPayerName(part.payer)+' ¥'+yuan(part.amount)).join(' · '):'付款来源待补齐';
}
function materialPoolDetailHTML(pool){ function materialPoolDetailHTML(pool){
const purchases=pool.todayPurchases?.items||(pool.purchases||[]).filter(item=>!item.sourceKind||item.sourceKind==='purchase'),usages=(pool.usages||[]).filter(item=>!teamMode()||state.user.role==='owner'||item.order_id&&(item.member==null||item.member===currentMember())); const purchases=pool.todayPurchases?.items||(pool.purchases||[]).filter(item=>!item.sourceKind||item.sourceKind==='purchase'),usages=(pool.usages||[]).filter(item=>!teamMode()||state.user.role==='owner'||(item.order_id||item.price_lock_id)&&(item.member==null||item.member===currentMember()));
return `<div class="material-pool-details"><h3>${e(pool.date)} 购料明细(按录入先后)</h3><p class="small muted">单价=本笔购买总价÷购买克重,与当天加权料价分开显示;显示精度不改变记账金额。</p><div class="table-wrap"><table class="material-detail-table material-purchase-table"><thead><tr><th>购料日期</th><th class="number">购买克重</th><th class="number">单价(元/克)</th><th class="number">购买总价</th><th>付款人</th><th>备注</th><th>操作</th></tr></thead><tbody>${purchases.map(item=>`<tr data-purchase-id="${e(item.id)}"><td>${e(item.date)}</td><td class="number">${grams(item.mg)}g</td><td class="number">${materialPoolRate(item.amount*1000/item.mg)}</td><td class="number">¥${yuan(item.amount)}</td><td>${e(materialPayerName(materialPurchasePayer(item)))}</td><td class="material-purchase-note">${e(item.note)}</td><td>${materialPurchaseActionsHTML(item)}</td></tr>`).join('')||'<tr><td colspan="7">尚未登记实际购料。</td></tr>'}</tbody></table></div>${materialRollingReturnHTML(pool)}<h3>订单耗用明细</h3><div class="table-wrap"><table class="material-detail-table"><thead><tr><th>订单日期/单号</th><th>客户/商品</th><th class="number">使用克重</th><th class="number">耗用料费</th><th>耗用料款归属/状态</th></tr></thead><tbody>${usages.map(item=>`<tr${item.active?'':' class="muted"'}><td>${e(item.date)}<br><button class="link-button" data-action="open-order" data-id="${e(item.order_id)}">${e(item.number||'查看订单')}</button></td><td>${e(item.customer||'未填称呼')}<div class="small muted">商品 ${Number(item.line_index)+1} · ${e(item.product)}</div></td><td class="number">${grams(item.mg)}g</td><td class="number">${item.amount==null?'料费待补':'¥'+yuan(item.amount)}</td><td>${item.active?item.amount==null?'待补采购':`麦麦 ¥${yuan(item.owner_amount)} · 助理1 ¥${yuan(item.assistant_amount)}${item.assistant2_amount==null?'':` · 助理2 ¥${yuan(item.assistant2_amount)}`}`:'已释放,不计已用克重'}</td></tr>`).join('')||'<tr><td colspan="5">尚未关联订单。</td></tr>'}</tbody></table></div>${materialPoolSettlementHTML(pool)}</div>`; return `<div class="material-pool-details"><h3>${e(pool.date)} 购料明细(按录入先后)</h3><p class="small muted">单价=本笔购买总价÷购买克重,与当天加权料价分开显示;显示精度不改变记账金额。</p><div class="table-wrap"><table class="material-detail-table material-purchase-table"><thead><tr><th>购料日期</th><th class="number">购买克重</th><th class="number">单价(元/克)</th><th class="number">购买总价</th><th>付款人</th><th>备注</th><th>操作</th></tr></thead><tbody>${purchases.map(item=>`<tr data-purchase-id="${e(item.id)}"><td>${e(item.date)}</td><td class="number">${grams(item.mg)}g</td><td class="number">${materialPoolRate(item.amount*1000/item.mg)}</td><td class="number">¥${yuan(item.amount)}</td><td>${e(materialPayerName(materialPurchasePayer(item)))}</td><td class="material-purchase-note">${e(item.note)}</td><td>${materialPurchaseActionsHTML(item)}</td></tr>`).join('')||'<tr><td colspan="7">尚未登记实际购料。</td></tr>'}</tbody></table></div>${materialRollingReturnHTML(pool)}<h3>订单耗用与锁价原料明细</h3><div class="table-wrap"><table class="material-detail-table"><thead><tr><th>日期/订单或锁价单</th><th>客户/商品</th><th class="number">使用克重</th><th class="number">耗用料费</th><th>耗用料款归属/状态</th></tr></thead><tbody>${usages.map(item=>`<tr${item.active?'':' class="muted"'}><td>${e(item.date)}<br><button class="link-button" data-action="${item.kind==='priceLock'?'open-price-lock':'open-order'}" data-id="${e(item.kind==='priceLock'?item.price_lock_id:item.order_id)}">${e(item.number||(item.kind==='priceLock'?'查看锁价单':'查看订单'))}</button></td><td>${e(item.customer||'未填称呼')}<div class="small muted">${item.kind==='priceLock'?'锁价原料':'商品 '+(Number(item.line_index)+1)} · ${e(item.product)}</div></td><td class="number">${grams(item.mg)}g</td><td class="number">${item.amount==null?'料费待补':'¥'+yuan(item.amount)}</td><td>${item.active?item.amount==null?'待补采购':e(materialPoolUsagePayersText(item)):'已释放,不计已用克重'}</td></tr>`).join('')||'<tr><td colspan="5">尚未关联订单或锁价。</td></tr>'}</tbody></table></div>${materialPoolSettlementHTML(pool)}</div>`;
} }
function materialPurchaseActionsHTML(item){ function materialPurchaseActionsHTML(item){
if(item.sourceKind&&item.sourceKind!=='purchase')return '<span class="small muted">材料结转记录</span>'; if(item.sourceKind&&item.sourceKind!=='purchase')return '<span class="small muted">材料结转记录</span>';
+3 -2
View File
@@ -27,6 +27,7 @@ function validateOrderChangeRequest(request,orderId){
if(!Array.isArray(request.relatedOrders))throw new Error('关联订单的修改影响未完整返回,请重新读取后复核。'); if(!Array.isArray(request.relatedOrders))throw new Error('关联订单的修改影响未完整返回,请重新读取后复核。');
request.relatedOrders.forEach(related=>validateOrderChangeRequest({...request,order_id:related.id,before:related.before,after:related.after,summary:related.summary,relatedOrders:[]})); request.relatedOrders.forEach(related=>validateOrderChangeRequest({...request,order_id:related.id,before:related.before,after:related.after,summary:related.summary,relatedOrders:[]}));
} }
validateRelatedPriceLocks(request.relatedPriceLocks);
if(request.action!==undefined&&!Object.hasOwn(orderChangeActionLabels,request.action))throw new Error('变更申请类型未完整返回,请重新读取后复核。'); if(request.action!==undefined&&!Object.hasOwn(orderChangeActionLabels,request.action))throw new Error('变更申请类型未完整返回,请重新读取后复核。');
const inventory=request.summary.inventory; const inventory=request.summary.inventory;
if(inventory!==undefined&&(!inventory||!['before','after','changes'].every(key=>Array.isArray(inventory[key])&&inventory[key].every(row=>typeof row.date==='string'&&typeof row.pocket==='string'&&Number.isSafeInteger(row.mg)))))throw new Error('变更申请库存摘要未完整返回,请重新读取后复核。'); if(inventory!==undefined&&(!inventory||!['before','after','changes'].every(key=>Array.isArray(inventory[key])&&inventory[key].every(row=>typeof row.date==='string'&&typeof row.pocket==='string'&&Number.isSafeInteger(row.mg)))))throw new Error('变更申请库存摘要未完整返回,请重新读取后复核。');
@@ -114,8 +115,8 @@ function orderChangeComparisonHTML(raw){
orderChangePair('新增费用默认支付日期',before.fees_date||before.date,after.fees_date||after.date)+orderChangePair('交付日期',before.delivered_date,after.delivered_date); orderChangePair('新增费用默认支付日期',before.fees_date||before.date,after.fees_date||after.date)+orderChangePair('交付日期',before.delivered_date,after.delivered_date);
const summary=[['成交金额','total'],['收款净额','netReceived'],['货品成本','goodsCost'],['实际费用合计','directCost'],['利润','profit'],['双方待结净额','settlementDue']].map(([title,key])=>orderChangePair(title,orderChangeMoney(request.summary.before[key]),orderChangeMoney(request.summary.after[key]))).join(''); const summary=[['成交金额','total'],['收款净额','netReceived'],['货品成本','goodsCost'],['实际费用合计','directCost'],['利润','profit'],['双方待结净额','settlementDue']].map(([title,key])=>orderChangePair(title,orderChangeMoney(request.summary.before[key]),orderChangeMoney(request.summary.after[key]))).join('');
const lines=Array.from({length:Math.max(before.lines.length,after.lines.length)},(_,index)=>`<tr class="change-section-row"><th colspan="3" scope="colgroup">商品 ${index+1}</th></tr>${[['商品与销售计价说明','name'],['商品编号','code'],['克重/数量','quantity'],['销售金价、工费与件数','pricing'],['成交金额(含附加收费)','sale'],['客户附加收费','charges'],['货盘','pocket'],['货品成本合计','cost'],['进货料价与料费','material'],['进货工费','labor'],['其他货品成本','extra'],['成本付款人','payers']].map(([title,key])=>orderChangePair(title,orderChangeLineValue(before.lines[index],key),orderChangeLineValue(after.lines[index],key))).join('')}`).join(''); const lines=Array.from({length:Math.max(before.lines.length,after.lines.length)},(_,index)=>`<tr class="change-section-row"><th colspan="3" scope="colgroup">商品 ${index+1}</th></tr>${[['商品与销售计价说明','name'],['商品编号','code'],['克重/数量','quantity'],['销售金价、工费与件数','pricing'],['成交金额(含附加收费)','sale'],['客户附加收费','charges'],['货盘','pocket'],['货品成本合计','cost'],['进货料价与料费','material'],['进货工费','labor'],['其他货品成本','extra'],['成本付款人','payers']].map(([title,key])=>orderChangePair(title,orderChangeLineValue(before.lines[index],key),orderChangeLineValue(after.lines[index],key))).join('')}`).join('');
const related=(request.relatedOrders||[]).map(item=>`<section class="order-change-related"><h3>同时受影响的关联订单:${e(item.number||item.id)}</h3><p class="small muted">本次修改会重新分配同批购料的成本及付款人。以下关联订单的利润与待结金额也会随批准一起更新。</p>${orderChangeComparisonHTML({...request,order_id:item.id,before:item.before,after:item.after,summary:item.summary,relatedOrders:[]})}</section>`).join(''); const related=(request.relatedOrders||[]).map(item=>`<section class="order-change-related"><h3>同时受影响的关联订单:${e(item.number||item.id)}</h3><p class="small muted">本次修改会重新分配同批购料的成本及付款人。以下关联订单的利润与待结金额也会随批准一起更新。</p>${orderChangeComparisonHTML({...request,order_id:item.id,before:item.before,after:item.after,summary:item.summary,relatedOrders:[],relatedPriceLocks:[]})}</section>`).join('');
return `<div class="order-change-comparison"><p class="small muted">原值为申请时快照,申请值由服务器按本次变更试算。批准前请核对客户实付、商品、成本、费用及付款人。</p><div class="table-wrap"><table class="order-change-table" aria-label="变更申请原值与申请值对照"><thead><tr><th>核对项目</th><th>原值(申请时)</th><th>申请值(同意后)</th></tr></thead><tbody>${basic}${orderChangePair('订单状态',label[before.status]||before.status,label[after.status]||after.status)}${orderChangePair('退货日期',before.returned_date,after.returned_date)}${orderChangePair('整单优惠',orderChangeMoney(before.discount),orderChangeMoney(after.discount))}${summary}${lines}<tr class="change-section-row"><th colspan="3" scope="colgroup">逐笔收退款与实际费用</th></tr>${orderChangePair('有效客户收退款/账户',orderChangePaymentsValue(before),orderChangePaymentsValue(after))}${orderChangePair('已记实际费用/日期/付款人',orderChangeExpensesValue(before),orderChangeExpensesValue(after))}</tbody></table></div>${orderChangeInventoryHTML(request.summary.inventory)}${related}<p class="small muted">双方已发生的实际交款保留;试算不会发起真实收款、退款或转账。批准时仍会校验订单和关联资料版本。</p></div>`; return `<div class="order-change-comparison"><p class="small muted">原值为申请时快照,申请值由服务器按本次变更试算。批准前请核对客户实付、商品、成本、费用及付款人。</p><div class="table-wrap"><table class="order-change-table" aria-label="变更申请原值与申请值对照"><thead><tr><th>核对项目</th><th>原值(申请时)</th><th>申请值(同意后)</th></tr></thead><tbody>${basic}${orderChangePair('订单状态',label[before.status]||before.status,label[after.status]||after.status)}${orderChangePair('退货日期',before.returned_date,after.returned_date)}${orderChangePair('整单优惠',orderChangeMoney(before.discount),orderChangeMoney(after.discount))}${summary}${lines}<tr class="change-section-row"><th colspan="3" scope="colgroup">逐笔收退款与实际费用</th></tr>${orderChangePair('有效客户收退款/账户',orderChangePaymentsValue(before),orderChangePaymentsValue(after))}${orderChangePair('已记实际费用/日期/付款人',orderChangeExpensesValue(before),orderChangeExpensesValue(after))}</tbody></table></div>${orderChangeInventoryHTML(request.summary.inventory)}${related}${relatedPriceLocksHTML(request.relatedPriceLocks)}<p class="small muted">双方已发生的实际交款保留;试算不会发起真实收款、退款或转账。批准时仍会校验订单和关联资料版本。</p></div>`;
} }
function requireOrderChangeDetail(){ function requireOrderChangeDetail(){
if(busy)throw new Error('正在保存,请稍候。'); if(busy)throw new Error('正在保存,请稍候。');
+105 -23
View File
@@ -1,5 +1,5 @@
'use strict'; 'use strict';
let createMode='direct',priceLockRequest=0,priceLockDeliveryId='',currentPriceLock=null; let createMode='direct',priceLockRequest=0,priceLockDeliveryId='',currentPriceLock=null,priceLockPoolRead=null,priceLockPoolError='';
const priceLockDraftKey=()=>`mm-price-lock-draft-${session.user.id}`; const priceLockDraftKey=()=>`mm-price-lock-draft-${session.user.id}`;
const priceLockDeliveryKey=id=>`mm-price-lock-delivery-${session.user.id}-${id}`; const priceLockDeliveryKey=id=>`mm-price-lock-delivery-${session.user.id}-${id}`;
const priceLockPayerName=payer=>({owner:'麦麦',assistant:typeof teamMode==='function'&&teamMode()?'助理1':'助理',assistant2:'助理2'})[payer]||'待补'; const priceLockPayerName=payer=>({owner:'麦麦',assistant:typeof teamMode==='function'&&teamMode()?'助理1':'助理',assistant2:'助理2'})[payer]||'待补';
@@ -13,24 +13,83 @@ function lockQuantityMg(value){
function lockFormValue(form,name){return form.querySelector(`[name="${name}"]`)?.value??'';} function lockFormValue(form,name){return form.querySelector(`[name="${name}"]`)?.value??'';}
function lockCharges(root){return [...root.querySelectorAll('.charge-row')].map(row=>{const value=name=>row.querySelector(`[name="${name}"]`).value,type=value('chargeType'),customName=value('chargeName');return {id:row.dataset.chargeId,nameType:type,customName,name:type==='其他'?customName:type,amount:value('chargeAmount'),chargePrices:JSON.parse(row.dataset.chargePrices)};});} function lockCharges(root){return [...root.querySelectorAll('.charge-row')].map(row=>{const value=name=>row.querySelector(`[name="${name}"]`).value,type=value('chargeType'),customName=value('chargeName');return {id:row.dataset.chargeId,nameType:type,customName,name:type==='其他'?customName:type,amount:value('chargeAmount'),chargePrices:JSON.parse(row.dataset.chargePrices)};});}
function syncLockChargeFields(root){for(const row of root.querySelectorAll('.charge-row')){const custom=row.querySelector('[name="chargeType"]').value==='其他',input=row.querySelector('[name="chargeName"]');input.closest('label').hidden=!custom;input.disabled=!custom;input.required=custom;}} function syncLockChargeFields(root){for(const row of root.querySelectorAll('.charge-row')){const custom=row.querySelector('[name="chargeType"]').value==='其他',input=row.querySelector('[name="chargeName"]');input.closest('label').hidden=!custom;input.disabled=!custom;input.required=custom;}}
const priceLockUsesPool=lock=>lock?.material_source==='pool';
function priceLockMaterialAllocations(lock){return priceLockUsesPool(lock)?lock.materialPool?.allocations||[]:[{payer:lock.buy_payer,amount:lock.material_amount}];}
function priceLockAllocationText(allocations){return allocations.map(part=>priceLockPayerName(part.payer)+' ¥'+yuan(part.amount)).join(';');}
function priceLockAllocationHTML(allocations){return allocations.map(part=>`<span>${e(priceLockPayerName(part.payer))} <b>¥${yuan(part.amount)}</b></span>`).join('');}
function priceLockCreateMaterialHTML(material){
const manual=material.manual||material,source=material.source==='pool'?'pool':'manual';
return `<section class="panel internal price-lock-material"><h2>原锁金料实际成本</h2><div class="material-source-row">${choice('原锁材料来源','material_source',[['manual','手动填写料价'],['pool','当日加权料价']],source)}<span class="small muted">料池占用锁定克重;实物出库在交付时登记。</span></div><div id="lock-manual-material"><div class="grid three">${moneyField('原锁进货料价(元/克)','material_rate',manual.rate??'')}${choice('原锁料费付款人','material_payer',teamMemberOptions(),manual.payer||'owner')}<div><span class="small muted">这批金料已付金额</span><div id="lock-material-estimate" class="summary-amount">待填写</div></div></div><label class="check"><input type="checkbox" name="material_verified" ${manual.verified?'checked':''} required>已核实原锁金料的实际付款。</label><p class="small muted">独立记录这批原锁金料的实际付款;工费、快递等在交付时填写实际成本。库存归属也在交付时确认。</p></div><div id="lock-pool-material" hidden><div class="grid three">${field('料池日期(随锁价日期)','material_pool_date','','text','readonly')}${field('加权进货料价(元/克,自动)','material_pool_rate','','text','readonly')}<div><span class="small muted">本次预留料费(元,自动)</span><div id="lock-pool-material-estimate" class="summary-amount">待填写</div></div></div><p id="lock-pool-material-note" class="material-pool-note small muted" aria-live="polite"></p><div id="lock-pool-material-payers" class="price-lock-material-payers small" aria-live="polite"></div><div class="actions">${button('刷新料池','reload-price-lock-pool','quiet')}</div><p class="small muted">使用已登记购料,按购料付款顺序自动归属,可涉及多人;保存锁价不再登记料费付款。锁价当天补料仍参与加权,跨天后保留锁价日成本。</p></div></section>`;
}
// 原锁只占用本日料池;金额沿用普通开单的累计分币算法,付款人按同一金额区间取FIFO。
function priceLockPoolPreview(date,quantity){
const known=typeof materialPoolsCache!=='undefined'&&materialPoolsCacheUser===state.user.id&&!!materialPoolsCache;
const rows=known?materialPoolRows():[],pool=rows.find(value=>value.id===date);
if(priceLockPoolError||!known)throw new Error(priceLockPoolError||'正在读取每日料池,请稍候。');
if(!currentMaterialRolling())throw new Error('请先启用统一料池,再选择当日加权料价。');
if(!pool||!pool.totalMg)throw new Error(date+' 尚无可用材料。请先登记购料,再保存锁价。');
if(pool.totalAmount==null)throw new Error('料池成本尚未补齐,请先核对材料记录,再保存锁价。');
const mg=lockQuantityMg(quantity);
const preview=LedgerCalc.poolMaterialPreview(pool,[{lineIndex:0,mg}],{allUsages:rows.flatMap(value=>value.usages||[])});
const remainingMg=Math.max(0,pool.totalMg-preview.usedMg),shortageMg=Math.max(0,mg-remainingMg),amount=preview.amounts[0];
if(!preview.covered||amount==null)return {pool,mg,...preview,amount:null,remainingMg,shortageMg,allocations:[]};
const fromAmount=LedgerCalc.poolMaterialAmount(pool.totalAmount,pool.totalMg,preview.usedMg),allocations=[],parts=(pool.purchases||[]).flatMap(purchase=>purchase.allocations||[{payer:purchase.payer,amount:purchase.amount}]);
let skip=fromAmount,left=amount,zeroPayer='';
for(const part of parts){
if(!['owner','assistant','assistant2'].includes(part.payer)||!Number.isSafeInteger(part.amount)||part.amount<=0)throw new Error('料池付款来源未完整读到,请刷新料池。');
if(skip>=part.amount){skip-=part.amount;continue;}
zeroPayer||=part.payer;const value=Math.min(left,part.amount-skip),saved=allocations.find(item=>item.payer===part.payer);
if(value){if(saved)saved.amount+=value;else allocations.push({payer:part.payer,amount:value});}left-=value;skip=0;
if(!left)break;
}
if(skip||left)throw new Error('料池付款来源不足,请刷新并核对购料。');
if(!amount)allocations.push({payer:zeroPayer||parts.at(-1)?.payer||'owner',amount:0});
return {pool,mg,...preview,amount,remainingMg,shortageMg,allocations};
}
function syncPriceLockMaterial(form){
const source=form.querySelector('[name="material_source"]');if(!source)return;
const poolMode=source.value==='pool',manual=$('#lock-manual-material'),poolRoot=$('#lock-pool-material');
manual.hidden=poolMode;poolRoot.hidden=!poolMode;
for(const control of manual.querySelectorAll('input,select')){control.disabled=poolMode;control.required=!poolMode;}
if(!poolMode)return;
const date=lockFormValue(form,'date'),quantity=lockFormValue(form,'quantity'),note=$('#lock-pool-material-note'),payers=$('#lock-pool-material-payers'),estimate=$('#lock-pool-material-estimate'),rate=form.querySelector('[name="material_pool_rate"]');
form.querySelector('[name="material_pool_date"]').value=date;rate.value='';estimate.textContent='待确定';payers.innerHTML='';poolRoot.dataset.revision='';poolRoot.dataset.ready='false';note.classList.remove('danger-text');
try{
if(date!==state.today)throw new Error('当日加权料池只支持今天锁价;补录其他日期请使用手动填写料价。');
const preview=priceLockPoolPreview(date,quantity),{pool,amount,remainingMg,shortageMg,allocations}=preview;
rate.value=pool.averageRate==null?'':(pool.averageRate/100).toFixed(2);poolRoot.dataset.revision=pool.revision;
note.textContent=`${date} 料池 ${grams(pool.totalMg)}g,已用/预留 ${grams(preview.usedMg)}g,可用 ${grams(remainingMg)}g;本次预留 ${grams(preview.mg)}g。`;
if(shortageMg){note.textContent+=`还缺 ${grams(shortageMg)}g,请先补足购料后再保存锁价。`;note.classList.add('danger-text');return;}
estimate.textContent='¥'+yuan(amount);payers.innerHTML='<strong>自动来源:</strong>'+priceLockAllocationHTML(allocations);poolRoot.dataset.ready='true';
}catch(err){note.textContent=err.message;note.classList.add('danger-text');}
}
async function loadPriceLockPoolChoices(force=false){
const form=$('#price-lock-create-form');if(!form?.querySelector('[name="material_source"]')||typeof readMaterialPools!=='function')return;
if(priceLockPoolRead?.form===form)return priceLockPoolRead.promise;
const user=state.user.id;
const promise=(async()=>{priceLockPoolError='';let readError='';try{await readMaterialPools(force);}catch(err){readError='每日料池尚未读到:'+(err.name==='AbortError'?'读取超时,请刷新料池。':err.message);}if(form===$('#price-lock-create-form')&&state.user.id===user){priceLockPoolError=readError;syncPriceLockForm();}})();
priceLockPoolRead={form,promise};try{await promise;}finally{if(priceLockPoolRead?.promise===promise)priceLockPoolRead=null;}
}
function collectPriceLockCreate(){ function collectPriceLockCreate(){
const form=$('#price-lock-create-form'),get=name=>lockFormValue(form,name); const form=$('#price-lock-create-form'),get=name=>lockFormValue(form,name);
return {...(teamMode()?{member:get('member')||currentMember()}:{}),date:get('date'),customer:get('customer').trim(),salesperson:get('salesperson'),note:get('note'),discount:get('discount'),line:{name:get('name').trim(),unit:'g',pricingMode:'auto',quantity:get('quantity'),goldPrice:get('goldPrice'),laborRate:get('laborRate'),laborMode:get('laborMode'),pieces:get('pieces'),charges:lockCharges(form)},payment:{amount:get('received_amount'),account:readPaymentAccount(form),credit_card_fee_payer:readCreditCardPayer(form),verified:form.querySelector('[name="payment_verified"]').checked},material:{rate:get('material_rate'),payer:get('material_payer'),verified:form.querySelector('[name="material_verified"]').checked}}; const material=get('material_source')==='pool'?{source:'pool',poolId:get('date'),revision:$('#lock-pool-material')?.dataset.revision||''}:{rate:get('material_rate'),payer:get('material_payer'),verified:form.querySelector('[name="material_verified"]').checked};
return {...(teamMode()?{member:get('member')||currentMember()}:{}),date:get('date'),customer:get('customer').trim(),salesperson:get('salesperson'),note:get('note'),discount:get('discount'),line:{name:get('name').trim(),unit:'g',pricingMode:'auto',quantity:get('quantity'),goldPrice:get('goldPrice'),laborRate:get('laborRate'),laborMode:get('laborMode'),pieces:get('pieces'),charges:lockCharges(form)},payment:{amount:get('received_amount'),account:readPaymentAccount(form),credit_card_fee_payer:readCreditCardPayer(form),verified:form.querySelector('[name="payment_verified"]').checked},material};
} }
function renderPriceLockCreate(){ function renderPriceLockCreate(){
const d=priceLockReadDraft(priceLockDraftKey())||{},line=d.line||{},payment=d.payment||{},material=d.material||{}; const d=priceLockReadDraft(priceLockDraftKey())||{},line=d.line||{},payment=d.payment||{},material=d.material||{};
$('#main').innerHTML=heading('GOLD PRICE LOCK','黄金锁价','每张锁价记录一件按克黄金;多件请分别锁价。保存后进入待交付,暂不出入库、不计利润。',priceLockCreateControls())+`<form id="price-lock-create-form"><section class="panel"><h2>客户与锁价日期</h2><div class="grid four">${field('锁价日期','date',d.date||state.today,'date',`required max="${e(state.today)}"`)}${field('客户称呼/代号(必填)','customer',d.customer||'','text','required maxlength="60"')}${field('开单人(必填)','salesperson',d.salesperson||session.user.name,'text','required maxlength="30"')}${orderMemberField(d.member||currentMember())}${field('黄金商品','name',line.name||'足金999','text','required maxlength="60"')}</div></section><section class="panel line-item" data-price-lock-sale><h2>锁定售价与预计克重</h2><div class="grid four">${field('锁定克重(g)','quantity',line.quantity||'','number','required min="0.001" step="0.001"')}${moneyField('锁定销售金价(元/克)','goldPrice',line.goldPrice||'')}${choice('销售工费方式','laborMode',[['gram','克工费'],['piece','件工费']],line.laborMode||'gram')}${moneyField('销售工费','laborRate',line.laborRate??'')}${field('计工费件数','pieces',line.pieces||'1','number','required min="1" step="1"')}</div><div class="sale-charges"><div class="panel-title"><strong>客户附加项目(选填)</strong>${button('+ 添加附加项目','add-charge')}</div><p class="small muted">沿用直接开单的收费默认值,可按实际修改;交付时会保留这些项目。</p><div class="charge-list">${(line.charges||[]).map(chargeHTML).join('')}</div></div><div class="grid two" style="margin-top:16px">${moneyField('整单优惠(元)','discount',d.discount??'0')}<label>客户可见备注<textarea name="note" maxlength="170" rows="2">${e(d.note||'')}</textarea></label></div><p id="lock-sale-estimate" class="calculation small" aria-live="polite"></p></section><section class="panel"><h2>客户实际已付款</h2><p class="small muted">填写已经收到的金额,可与预计报价不同;尚未收款填0。</p><div class="grid three">${moneyField('实际收款(元)','received_amount',payment.amount??'')}${accountFields(payment.account)}</div><label class="check"><input type="checkbox" name="payment_verified" ${payment.verified?'checked':''} required>已核实实际收款金额与账户。</label>${creditCardPreviewHTML('lock-create-card-fee',payment.credit_card_fee_payer)}</section><section class="panel internal"><h2>原锁金料实际成本</h2><div class="grid three">${moneyField('原锁进货料价(元/克)','material_rate',material.rate??'')}${choice('原锁料费付款人','material_payer',teamMemberOptions(),material.payer||'owner')}<div><span class="small muted">这批金料已付金额</span><div id="lock-material-estimate" class="summary-amount">待填写</div></div></div><label class="check"><input type="checkbox" name="material_verified" ${material.verified?'checked':''} required>已核实原锁金料的实际付款。</label><p class="small muted">此处只记原锁金料付款;工费、快递等在交付时填写实际成本。库存归属也在交付时确认。</p></section><section class="panel"><div class="form-actions"><div><span class="small muted">预计成交额 · 四舍五入到元</span><div id="lock-create-total" class="summary-amount">待填写</div><div class="small muted">待交付,不计利润</div></div><button class="primary" type="submit">保存锁价待交付</button></div><div id="price-lock-error" aria-live="polite"></div></section></form>`; $('#main').innerHTML=heading('GOLD PRICE LOCK','黄金锁价','每张锁价记录一件按克黄金;多件请分别锁价。保存后进入待交付,暂不出入库、不计利润。',priceLockCreateControls())+`<form id="price-lock-create-form"><section class="panel"><h2>客户与锁价日期</h2><div class="grid four">${field('锁价日期','date',d.date||state.today,'date',`required max="${e(state.today)}"`)}${field('客户称呼/代号(必填)','customer',d.customer||'','text','required maxlength="60"')}${field('开单人(必填)','salesperson',d.salesperson||session.user.name,'text','required maxlength="30"')}${orderMemberField(d.member||currentMember())}${field('黄金商品','name',line.name||'足金999','text','required maxlength="60"')}</div></section><section class="panel line-item" data-price-lock-sale><h2>锁定售价与预计克重</h2><div class="grid four">${field('锁定克重(g)','quantity',line.quantity||'','number','required min="0.001" step="0.001"')}${moneyField('锁定销售金价(元/克)','goldPrice',line.goldPrice||'')}${choice('销售工费方式','laborMode',[['gram','克工费'],['piece','件工费']],line.laborMode||'gram')}${moneyField('销售工费','laborRate',line.laborRate??'')}${field('计工费件数','pieces',line.pieces||'1','number','required min="1" step="1"')}</div><div class="sale-charges"><div class="panel-title"><strong>客户附加项目(选填)</strong>${button('+ 添加附加项目','add-charge')}</div><p class="small muted">沿用直接开单的收费默认值,可按实际修改;交付时会保留这些项目。</p><div class="charge-list">${(line.charges||[]).map(chargeHTML).join('')}</div></div><div class="grid two" style="margin-top:16px">${moneyField('整单优惠(元)','discount',d.discount??'0')}<label>客户可见备注<textarea name="note" maxlength="170" rows="2">${e(d.note||'')}</textarea></label></div><p id="lock-sale-estimate" class="calculation small" aria-live="polite"></p></section><section class="panel"><h2>客户实际已付款</h2><p class="small muted">填写已经收到的金额,可与预计报价不同;尚未收款填0。</p><div class="grid three">${moneyField('实际收款(元)','received_amount',payment.amount??'')}${accountFields(payment.account)}</div><label class="check"><input type="checkbox" name="payment_verified" ${payment.verified?'checked':''} required>已核实实际收款金额与账户。</label>${creditCardPreviewHTML('lock-create-card-fee',payment.credit_card_fee_payer)}</section>${priceLockCreateMaterialHTML(material)}<section class="panel"><div class="form-actions"><div><span class="small muted">预计成交额 · 四舍五入到元</span><div id="lock-create-total" class="summary-amount">待填写</div><div class="small muted">待交付,不计利润</div></div><button class="primary" type="submit">保存锁价待交付</button></div><div id="price-lock-error" aria-live="polite"></div></section></form>`;
syncPriceLockForm(); syncPriceLockForm();loadPriceLockPoolChoices(true);
} }
function syncPriceLockCreate(){ function syncPriceLockCreate(){
const form=$('#price-lock-create-form');if(!form)return;syncPaymentRecipient(form);syncLockChargeFields(form); const form=$('#price-lock-create-form');if(!form)return;syncPaymentRecipient(form);syncLockChargeFields(form);syncPriceLockMaterial(form);
const piece=form.querySelector('[name="pieces"]'),pieceMode=lockFormValue(form,'laborMode')==='piece';piece.closest('label').hidden=!pieceMode;piece.required=pieceMode; const piece=form.querySelector('[name="pieces"]'),pieceMode=lockFormValue(form,'laborMode')==='piece';piece.closest('label').hidden=!pieceMode;piece.required=pieceMode;
const d=collectPriceLockCreate(); const d=collectPriceLockCreate();
try{const sale=LedgerCalc.sale(d.line),total=LedgerCalc.orderTotal([sale.sale],LedgerCalc.cents(d.discount),'yuan');$('#lock-create-total').textContent=orderAmount(total.total,'yuan');$('#lock-sale-estimate').textContent='商品及附加项目合计 ¥'+yuan(sale.sale)+';'+orderRoundingHint(total);}catch{$('#lock-create-total').textContent='待填写';$('#lock-sale-estimate').textContent='填写克重、销售金价与工费后显示预计报价。';} try{const sale=LedgerCalc.sale(d.line),total=LedgerCalc.orderTotal([sale.sale],LedgerCalc.cents(d.discount),'yuan');$('#lock-create-total').textContent=orderAmount(total.total,'yuan');$('#lock-sale-estimate').textContent='商品及附加项目合计 ¥'+yuan(sale.sale)+';'+orderRoundingHint(total);}catch{$('#lock-create-total').textContent='待填写';$('#lock-sale-estimate').textContent='填写克重、销售金价与工费后显示预计报价。';}
try{const cost=LedgerCalc.purchaseCosts({unit:'g',quantity:d.line.quantity,costParts:{material:'0',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'gram',rate:d.material.rate}});$('#lock-material-estimate').textContent=cost.total==null?'待填写':'¥'+yuan(cost.total);}catch{$('#lock-material-estimate').textContent='待填写';} try{const cost=LedgerCalc.purchaseCosts({unit:'g',quantity:d.line.quantity,costParts:{material:'0',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'gram',rate:d.material.rate}});$('#lock-material-estimate').textContent=cost.total==null?'待填写':'¥'+yuan(cost.total);}catch{$('#lock-material-estimate').textContent='待填写';}
let paymentCents=null;try{paymentCents=LedgerCalc.cents(d.payment.amount);}catch{} let paymentCents=null;try{paymentCents=LedgerCalc.cents(d.payment.amount);}catch{}
syncCreditCardPreview($('#lock-create-card-fee'),d.payment.account,paymentCents); syncCreditCardPreview($('#lock-create-card-fee'),d.payment.account,paymentCents);
localStorage.setItem(priceLockDraftKey(),JSON.stringify(d)); const manual={rate:lockFormValue(form,'material_rate'),payer:lockFormValue(form,'material_payer'),verified:form.querySelector('[name="material_verified"]').checked};
localStorage.setItem(priceLockDraftKey(),JSON.stringify({...d,material:d.material.source==='pool'?{...d.material,manual}:d.material}));
} }
function priceLockCardFeeTotal(lock){return Number.isSafeInteger(lock.credit_card_fee_total)?lock.credit_card_fee_total:(lock.credit_card_fees||[]).reduce((sum,item)=>sum+item.amount,0);} function priceLockCardFeeTotal(lock){return Number.isSafeInteger(lock.credit_card_fee_total)?lock.credit_card_fee_total:(lock.credit_card_fees||[]).reduce((sum,item)=>sum+item.amount,0);}
function priceLockCardFeesHTML(lock){ function priceLockCardFeesHTML(lock){
@@ -38,13 +97,28 @@ function priceLockCardFeesHTML(lock){
return `<div class="price-lock-card-fees internal"><strong>已记录的信用卡手续费 · ¥${yuan(priceLockCardFeeTotal(lock))}</strong><ul>${fees.map(item=>`<li><span>${e(item.date)} · ${e(priceLockPayerName(item.payer))}支付${item.note?' · '+e(item.note):''}</span><b>¥${yuan(item.amount)}</b></li>`).join('')}</ul><p class="small muted">已按各笔付款时保存的金额与费率计入内部成本;交付时沿用,不重复收取。退款不冲回已发生的手续费。</p></div>`; return `<div class="price-lock-card-fees internal"><strong>已记录的信用卡手续费 · ¥${yuan(priceLockCardFeeTotal(lock))}</strong><ul>${fees.map(item=>`<li><span>${e(item.date)} · ${e(priceLockPayerName(item.payer))}支付${item.note?' · '+e(item.note):''}</span><b>¥${yuan(item.amount)}</b></li>`).join('')}</ul><p class="small muted">已按各笔付款时保存的金额与费率计入内部成本;交付时沿用,不重复收取。退款不冲回已发生的手续费。</p></div>`;
} }
function priceLockDialog(){let dialog=$('#price-lock-dialog');if(!dialog){dialog=document.createElement('dialog');dialog.id='price-lock-dialog';document.body.append(dialog);}return dialog;} function priceLockDialog(){let dialog=$('#price-lock-dialog');if(!dialog){dialog=document.createElement('dialog');dialog.id='price-lock-dialog';document.body.append(dialog);}return dialog;}
function priceLockFacts(lock){return `<div class="grid three price-lock-facts"><div>锁价日期<strong>${e(lock.date)}</strong></div><div>原锁克重<strong>${grams(lock.locked_mg)}g</strong></div><div>锁定销售金价<strong>¥${yuan(lock.sell_rate)}/克</strong></div><div>${lock.status==='delivered'?'锁价及交付阶段净收款':'客户实际已付净额'}<strong>¥${yuan(lock.netReceived)}</strong>${lock.status==='delivered'?'<small>后续收退款请查看销售单。</small>':''}</div><div>原锁料费<strong>¥${yuan(lock.material_amount)}</strong><small>${e(priceLockPayerName(lock.buy_payer))}支付,进货料价 ¥${yuan(lock.buy_rate)}/克</small></div><div>状态<strong>${lock.status==='pending'?'待交付,不计利润':'已交付'}</strong></div></div>`+priceLockCardFeesHTML(lock);} function priceLockFacts(lock){
const pool=priceLockUsesPool(lock),material=lock.materialPool;
return `<div class="grid three price-lock-facts"><div>锁价日期<strong>${e(lock.date)}</strong></div><div>原锁克重<strong>${grams(lock.locked_mg)}g</strong></div><div>锁定销售金价<strong>¥${yuan(lock.sell_rate)}/克</strong></div><div>${lock.status==='delivered'?'锁价及交付阶段净收款':'客户实际已付净额'}<strong>¥${yuan(lock.netReceived)}</strong>${lock.status==='delivered'?'<small>后续收退款请查看销售单。</small>':''}</div><div>原锁料费 · ${pool?'当日加权料池':'手动独立购料'}<strong>¥${yuan(lock.material_amount)}</strong><small>${pool?`${e(material?.date||lock.material_pool_id||lock.date)}料池,加权均价约 ¥${yuan(material?.averageRate??lock.buy_rate)}/克`:`${e(priceLockPayerName(lock.buy_payer))}支付,进货料价 ¥${yuan(lock.buy_rate)}/克`}</small>${pool?`<small>${e(priceLockAllocationText(priceLockMaterialAllocations(lock)))}</small><small>${material?.frozen?'已冻结锁价日成本':'当天补料继续加权'},不重复记购料付款。</small>`:''}</div><div>状态<strong>${lock.status==='pending'?'待交付,不计利润':'已交付'}</strong></div></div>`+priceLockCardFeesHTML(lock);
}
function priceLockDeliveryCost(lock,quantity,extraBuyRate){
if(!priceLockUsesPool(lock))return LedgerCalc.priceLockCost({lockedQuantity:grams(lock.locked_mg),quantity,buyRate:(lock.buy_rate/100).toFixed(2),extraBuyRate});
const pool=lock.materialPool,finalMg=lockQuantityMg(quantity),originalUsedMg=Math.min(finalMg,lock.locked_mg),extraMg=Math.max(0,finalMg-lock.locked_mg),leftoverMg=lock.locked_mg-originalUsedMg;
if(!pool||!['basisAmount','basisMg','prefixMg','prefixAmount','amount'].every(key=>Number.isSafeInteger(pool[key])&&pool[key]>=0)||!pool.basisMg)throw new Error('原锁料池成本来源未完整读到,请重新读取锁价单。');
const originalUsedCost=LedgerCalc.poolMaterialAmount(pool.basisAmount,pool.basisMg,pool.prefixMg+originalUsedMg)-pool.prefixAmount;
const extraRate=extraMg?LedgerCalc.cents(extraBuyRate,'补重进货料价'):0;if(extraMg&&!extraRate)throw new Error('补重进货料价必须大于0。');
const extraCost=extraMg?Number((BigInt(extraMg)*BigInt(extraRate)+500n)/1000n):0;
let left=originalUsedCost;const allocations=[];
for(const part of priceLockMaterialAllocations(lock)){const amount=Math.min(left,part.amount);if(amount||!originalUsedCost&&!allocations.length)allocations.push({payer:part.payer,amount});left-=amount;}
if(left||originalUsedCost<0||originalUsedCost>pool.amount)throw new Error('原锁料池成本分摊不完整,请重新读取锁价单。');
return {lockedMg:lock.locked_mg,finalMg,originalUsedMg,extraMg,leftoverMg,originalPurchase:pool.amount,originalUsedCost,extraCost,materialCost:originalUsedCost+extraCost,leftoverCost:pool.amount-originalUsedCost,allocations};
}
async function renderPriceLocks(){ async function renderPriceLocks(){
if(priceLockDeliveryId)return await renderPriceLockDelivery(priceLockDeliveryId); if(priceLockDeliveryId)return await renderPriceLockDelivery(priceLockDeliveryId);
const request=++priceLockRequest,user=state.user.id; const request=++priceLockRequest,user=state.user.id;
$('#main').innerHTML=heading('PENDING DELIVERY','待交付','显示所有日期的锁价待交付记录。锁价时只记实际收付,交付后才计销售、成本和利润。',button('新增锁价','new-price-lock','primary')+button('刷新','refresh-price-locks'))+'<section class="panel"><div id="price-lock-list" aria-live="polite">正在读取待交付记录…</div></section>'; $('#main').innerHTML=heading('PENDING DELIVERY','待交付','显示所有日期的锁价待交付记录。锁价时只记实际收付,交付后才计销售、成本和利润。',button('新增锁价','new-price-lock','primary')+button('刷新','refresh-price-locks'))+'<section class="panel"><div id="price-lock-list" aria-live="polite">正在读取待交付记录…</div></section>';
try{const result=await api('/api/price-locks?status=pending');if(request!==priceLockRequest||tab!=='price-locks'||state.user.id!==user||!$('#price-lock-list'))return;if(!Array.isArray(result.rows))throw new Error('待交付记录未完整返回,请重试。'); try{const result=await api('/api/price-locks?status=pending');if(request!==priceLockRequest||tab!=='price-locks'||state.user.id!==user||!$('#price-lock-list'))return;if(!Array.isArray(result.rows))throw new Error('待交付记录未完整返回,请重试。');
$('#price-lock-list').innerHTML=result.rows.length?`<div class="table-wrap"><table class="price-lock-list"><thead><tr><th>锁价日期/客户</th><th>黄金商品</th><th class="number">锁定克重</th><th class="number">销售金价</th><th class="number">已收净额</th><th>原料付款</th><th>操作</th></tr></thead><tbody>${result.rows.map(lock=>`<tr><td>${e(lock.date)}<br>${e(lock.customer)}</td><td>${e(lock.line?.name||lock.product||'黄金')}</td><td class="number">${grams(lock.locked_mg)}g</td><td class="number">¥${yuan(lock.sell_rate)}/克</td><td class="number">¥${yuan(lock.netReceived)}</td><td>${e(priceLockPayerName(lock.buy_payer))}<br>¥${yuan(lock.material_amount)}</td><td><div class="actions">${button('查看','open-price-lock','',`data-id="${e(lock.id)}"`)}${button('交付','deliver-price-lock','primary',`data-id="${e(lock.id)}"`)}</div></td></tr>`).join('')}</tbody></table></div>`:'<div class="empty"><strong>目前没有锁价待交付记录</strong>已交付记录会进入订单列表。</div>'; $('#price-lock-list').innerHTML=result.rows.length?`<div class="table-wrap"><table class="price-lock-list"><thead><tr><th>锁价日期/客户</th><th>黄金商品</th><th class="number">锁定克重</th><th class="number">销售金价</th><th class="number">已收净额</th><th>原料来源/成本</th><th>操作</th></tr></thead><tbody>${result.rows.map(lock=>`<tr><td>${e(lock.date)}<br>${e(lock.customer)}</td><td>${e(lock.line?.name||lock.product||'黄金')}</td><td class="number">${grams(lock.locked_mg)}g</td><td class="number">¥${yuan(lock.sell_rate)}/克</td><td class="number">¥${yuan(lock.netReceived)}</td><td><strong>${priceLockUsesPool(lock)?'当日加权料池':'手动独立购料'}</strong><br>¥${yuan(lock.material_amount)}<div class="small muted">${e(priceLockAllocationText(priceLockMaterialAllocations(lock)))}</div></td><td><div class="actions">${button('查看','open-price-lock','',`data-id="${e(lock.id)}"`)}${button('交付','deliver-price-lock','primary',`data-id="${e(lock.id)}"`)}</div></td></tr>`).join('')}</tbody></table></div>`:'<div class="empty"><strong>目前没有锁价待交付记录</strong>已交付记录会进入订单列表。</div>';
}catch(err){if(request===priceLockRequest&&tab==='price-locks'&&$('#price-lock-list'))$('#price-lock-list').innerHTML=`<div class="error">${e(err.message)} ${button('重新读取','refresh-price-locks')}</div>`;} }catch(err){if(request===priceLockRequest&&tab==='price-locks'&&$('#price-lock-list'))$('#price-lock-list').innerHTML=`<div class="error">${e(err.message)} ${button('重新读取','refresh-price-locks')}</div>`;}
} }
async function openPriceLock(id){ async function openPriceLock(id){
@@ -54,8 +128,8 @@ async function openPriceLock(id){
}catch(err){if(request===priceLockRequest&&dialog.open)$('#price-lock-detail').innerHTML=`<div class="error">${e(err.message)}</div>`;} }catch(err){if(request===priceLockRequest&&dialog.open)$('#price-lock-detail').innerHTML=`<div class="error">${e(err.message)}</div>`;}
} }
function priceLockLineInputs(lock){ function priceLockLineInputs(lock){
const line=lock.line; const line=lock.line,payer=priceLockMaterialAllocations(lock)[0]?.payer||lock.buy_payer||'owner';
return {...line,quantity:grams(lock.locked_mg),goldPrice:(lock.sell_rate/100).toFixed(2),laborRate:(line.laborRate/100).toFixed(2),sale:(line.sale/100).toFixed(2),baseSale:((line.baseSale??line.sale)/100).toFixed(2),charges:(line.charges||[]).map(c=>({...c,amount:(c.amount/100).toFixed(2)})),payer:lock.buy_payer,costParts:{material:(lock.material_amount/100).toFixed(2),labor:'',accessories:'0',other:'0'},costMaterial:{mode:'total'},costLabor:{mode:'total'},costPayers:{material:lock.buy_payer,labor:'owner'}}; return {...line,quantity:grams(lock.locked_mg),goldPrice:(lock.sell_rate/100).toFixed(2),laborRate:(line.laborRate/100).toFixed(2),sale:(line.sale/100).toFixed(2),baseSale:((line.baseSale??line.sale)/100).toFixed(2),charges:(line.charges||[]).map(c=>({...c,amount:(c.amount/100).toFixed(2)})),payer,costParts:{material:(lock.material_amount/100).toFixed(2),labor:'',accessories:'0',other:'0'},costMaterial:{mode:'total'},costLabor:{mode:'total'},costPayers:{material:payer,labor:'owner'}};
} }
async function renderPriceLockDelivery(id){ async function renderPriceLockDelivery(id){
const request=++priceLockRequest,user=state.user.id; const request=++priceLockRequest,user=state.user.id;
@@ -67,35 +141,38 @@ async function renderPriceLockDelivery(id){
} }
currentPriceLock=lock; currentPriceLock=lock;
const saved=priceLockReadDraft(priceLockDeliveryKey(id)),draft=saved?.revision===lock.revision?saved:{},line=draft.line||priceLockLineInputs(lock),date=draft.date||state.today; const saved=priceLockReadDraft(priceLockDeliveryKey(id)),draft=saved?.revision===lock.revision?saved:{},line=draft.line||priceLockLineInputs(lock),date=draft.date||state.today;
$('#main').innerHTML=heading('LOCK DELIVERY','交付 · '+e(lock.customer),'最终克重全部按原锁销售金价结算;补重只新增进货成本。交付成功后生成正式销售单。',button('返回待交付','refresh-price-locks'))+`<section class="panel">${priceLockFacts(lock)}</section><form id="price-lock-delivery-form" data-id="${e(id)}" data-revision="${lock.revision}"><section class="panel"><div class="grid two">${field('交付日期','date',date,'date',`required min="${e(lock.date)}" max="${e(state.today)}"`)}${field('交付备注(客户可见,选填)','delivery_note',draft.note??lock.note??'','text','maxlength="170"')}</div></section><section class="panel price-lock-delivery-line"><div class="panel-title"><h2>最终商品与实际成本</h2><span class="small muted">一件黄金,保留原锁附加项目;可按实际增减。</span></div><div id="lines">${lineHTML(line,1)}</div></section><section class="panel internal"><h2>金料与库存确认</h2><p class="small muted">请选择本次交付所用的实际黄金货盘。已经记过入库的金料只出库,不会重复增加库存。</p><div class="grid two">${choice('原锁金料是否已记入这个货盘','original_stock',[['','请选择'],['receive','尚未记入,交付时先入库'],['stocked','此前已记入,只出库']],draft.inventory?.original||'')}<div id="lock-material-breakdown" class="lock-material-breakdown" aria-live="polite"></div></div><div id="lock-extra-material" hidden><h3>超出原锁克重的补重金料</h3><div class="grid three">${moneyField('补重进货料价(元/克)','extra_rate',draft.extraMaterial?.rate??'')}${choice('补重料费付款人','extra_payer',[['','请选择'],...teamMemberOptions()],draft.extraMaterial?.payer||'')}${choice('补重金料是否已记入所选货盘','extra_stock',[['','请选择'],['receive','尚未记入,交付时先入库'],['stocked','此前已记入,只出库']],draft.inventory?.extra||'')}</div><label class="check"><input type="checkbox" name="extra_verified" ${draft.extraMaterial?.verified?'checked':''}>已核实补重料费实际付款。</label></div><p id="lock-stock-note" class="note" aria-live="polite"></p></section>${feeHTML({...draft,date,fees_date:date},{cardPreview:false})}<section class="panel"><div class="grid two">${moneyField('整单优惠(元)','discount',draft.discount??(lock.discount/100).toFixed(2))}<div><span class="small muted">最终成交额 · 四舍五入到元</span><div id="lock-final-total" class="summary-amount">待填写</div><p id="lock-rounding-note" class="small muted"></p></div></div><div class="lock-settlement"><h2 id="lock-settlement-title">客户补款/退款</h2><p id="lock-settlement-hint" class="small muted" aria-live="polite"></p><div id="lock-settlement-fields"><div class="grid three">${field('本次实际补退款(元)','settlement_amount','','number','readonly')}${accountFields(draft.settlement?.account||lock.cash_events.find(event=>event.kind==='receipt')?.account)}</div><label class="check"><input type="checkbox" name="settlement_verified" ${draft.settlement?.verified?'checked':''}>已核实本次补款到账/退款已实际完成。</label></div></div>${creditCardPreviewHTML('lock-delivery-card-fee',draft.settlement?.credit_card_fee_payer)}<label class="check"><input type="checkbox" name="delivery_verified" required>已核对实物、实际成本、出入库来源与客户收付款,确认交付。</label><div class="form-actions"><span class="small muted">保存后才记销售、完整成本和利润,可打印正式客户单据。</span><button type="submit" class="primary">确认交付并生成销售单</button></div><div id="price-lock-error" aria-live="polite"></div></section></form>`; $('#main').innerHTML=heading('LOCK DELIVERY','交付 · '+e(lock.customer),'最终克重全部按原锁销售金价结算;补重只新增进货成本。交付成功后生成正式销售单。',button('返回待交付','refresh-price-locks'))+`<section class="panel">${priceLockFacts(lock)}</section><form id="price-lock-delivery-form" data-id="${e(id)}" data-revision="${lock.revision}"><section class="panel"><div class="grid two">${field('交付日期','date',date,'date',`required min="${e(lock.date)}" max="${e(state.today)}"`)}${field('交付备注(客户可见,选填)','delivery_note',draft.note??lock.note??'','text','maxlength="170"')}</div></section><section class="panel price-lock-delivery-line"><div class="panel-title"><h2>最终商品与实际成本</h2><span class="small muted">一件黄金,保留原锁附加项目;可按实际增减。</span></div><div id="lines">${lineHTML(line,1)}</div></section><section class="panel internal"><h2>金料与库存确认</h2><p class="small muted">请选择本次交付所用的实际黄金货盘。已经记过入库的金料只出库,不会重复增加库存。</p><div class="grid two">${choice('原锁金料是否已记入这个货盘','original_stock',[['','请选择'],['receive','尚未记入,交付时先入库'],['stocked',priceLockUsesPool(lock)?'料池已预留,仅出库,不重复入库':'此前已记入,只出库']],priceLockUsesPool(lock)?'stocked':draft.inventory?.original||'')}<div id="lock-material-breakdown" class="lock-material-breakdown" aria-live="polite"></div></div><div id="lock-extra-material" hidden><h3>超出原锁克重的补重金料</h3><div class="grid three">${moneyField('补重进货料价(元/克)','extra_rate',draft.extraMaterial?.rate??'')}${choice('补重料费付款人','extra_payer',[['','请选择'],...teamMemberOptions()],draft.extraMaterial?.payer||'')}${choice('补重金料是否已记入所选货盘','extra_stock',[['','请选择'],['receive','尚未记入,交付时先入库'],['stocked','此前已记入,只出库']],draft.inventory?.extra||'')}</div><label class="check"><input type="checkbox" name="extra_verified" ${draft.extraMaterial?.verified?'checked':''}>已核实补重料费实际付款。</label></div><p id="lock-stock-note" class="note" aria-live="polite"></p></section>${feeHTML({...draft,date,fees_date:date},{cardPreview:false})}<section class="panel"><div class="grid two">${moneyField('整单优惠(元)','discount',draft.discount??(lock.discount/100).toFixed(2))}<div><span class="small muted">最终成交额 · 四舍五入到元</span><div id="lock-final-total" class="summary-amount">待填写</div><p id="lock-rounding-note" class="small muted"></p></div></div><div class="lock-settlement"><h2 id="lock-settlement-title">客户补款/退款</h2><p id="lock-settlement-hint" class="small muted" aria-live="polite"></p><div id="lock-settlement-fields"><div class="grid three">${field('本次实际补退款(元)','settlement_amount','','number','readonly')}${accountFields(draft.settlement?.account||lock.cash_events.find(event=>event.kind==='receipt')?.account)}</div><label class="check"><input type="checkbox" name="settlement_verified" ${draft.settlement?.verified?'checked':''}>已核实本次补款到账/退款已实际完成。</label></div></div>${creditCardPreviewHTML('lock-delivery-card-fee',draft.settlement?.credit_card_fee_payer)}<label class="check"><input type="checkbox" name="delivery_verified" required>已核对实物、实际成本、出入库来源与客户收付款,确认交付。</label><div class="form-actions"><span class="small muted">保存后才记销售、完整成本和利润,可打印正式客户单据。</span><button type="submit" class="primary">确认交付并生成销售单</button></div><div id="price-lock-error" aria-live="polite"></div></section></form>`;
syncPriceLockForm(); syncPriceLockForm();
}catch(err){if(request===priceLockRequest&&tab==='price-locks'&&$('#price-lock-delivery-loading'))$('#price-lock-delivery-loading').innerHTML=`<div class="error">${e(err.message)}</div>${button('重新读取','deliver-price-lock','',`data-id="${e(id)}"`)}`;} }catch(err){if(request===priceLockRequest&&tab==='price-locks'&&$('#price-lock-delivery-loading'))$('#price-lock-delivery-loading').innerHTML=`<div class="error">${e(err.message)}</div>${button('重新读取','deliver-price-lock','',`data-id="${e(id)}"`)}`;}
} }
function collectPriceLockDelivery(){ function collectPriceLockDelivery(){
const form=$('#price-lock-delivery-form'),get=name=>lockFormValue(form,name),row=form.querySelector('#lines .line-item'); const form=$('#price-lock-delivery-form'),get=name=>lockFormValue(form,name),row=form.querySelector('#lines .line-item');
return {revision:Number(form.dataset.revision),date:get('date'),note:get('delivery_note'),line:collectLine(row),discount:get('discount'),extraMaterial:{rate:get('extra_rate'),payer:get('extra_payer'),verified:form.querySelector('[name="extra_verified"]').checked},inventory:{pocket:row.querySelector('[name="pocket"]').value,original:get('original_stock'),extra:get('extra_stock')},settlement:{amount:get('settlement_amount'),account:readPaymentAccount(form),credit_card_fee_payer:readCreditCardPayer(form),verified:form.querySelector('[name="settlement_verified"]').checked},fee_items:readFeeRows(),fee_auto_initialized:true,verified:form.querySelector('[name="delivery_verified"]').checked}; return {revision:Number(form.dataset.revision),date:get('date'),note:get('delivery_note'),line:collectLine(row),discount:get('discount'),extraMaterial:{rate:get('extra_rate'),payer:get('extra_payer'),verified:form.querySelector('[name="extra_verified"]').checked},inventory:{pocket:row.querySelector('[name="pocket"]').value,original:priceLockUsesPool(currentPriceLock)?'stocked':get('original_stock'),extra:get('extra_stock')},settlement:{amount:get('settlement_amount'),account:readPaymentAccount(form),credit_card_fee_payer:readCreditCardPayer(form),verified:form.querySelector('[name="settlement_verified"]').checked},fee_items:readFeeRows(),fee_auto_initialized:true,verified:form.querySelector('[name="delivery_verified"]').checked};
} }
function syncPriceLockDelivery(){ function syncPriceLockDelivery(){
const form=$('#price-lock-delivery-form'),lock=currentPriceLock;if(!form||!lock||form.dataset.id!==lock.id)return;syncPaymentRecipient(form); const form=$('#price-lock-delivery-form'),lock=currentPriceLock;if(!form||!lock||form.dataset.id!==lock.id)return;syncPaymentRecipient(form);
const row=form.querySelector('#lines .line-item'),get=name=>row.querySelector(`[name="${name}"]`); const row=form.querySelector('#lines .line-item'),get=name=>row.querySelector(`[name="${name}"]`);
get('goldPrice').value=(lock.sell_rate/100).toFixed(2);get('unit').value='g';get('pricingMode').value='auto';get('cost-materialMode').value='total';get('cost-materialPayer').value=lock.buy_payer; get('goldPrice').value=(lock.sell_rate/100).toFixed(2);get('unit').value='g';get('pricingMode').value='auto';get('cost-materialMode').value='total';get('cost-materialPayer').value=priceLockMaterialAllocations(lock)[0]?.payer||lock.buy_payer||'owner';
let costs=null,extra=false; let costs=null,extra=false;
try{extra=lockQuantityMg(get('quantity').value)>lock.locked_mg;}catch{} try{extra=lockQuantityMg(get('quantity').value)>lock.locked_mg;}catch{}
const extraRoot=$('#lock-extra-material');extraRoot.hidden=!extra;for(const input of extraRoot.querySelectorAll('input,select')){input.disabled=!extra;input.required=extra;} const extraRoot=$('#lock-extra-material');extraRoot.hidden=!extra;for(const input of extraRoot.querySelectorAll('input,select')){input.disabled=!extra;input.required=extra;}
try{costs=LedgerCalc.priceLockCost({lockedQuantity:grams(lock.locked_mg),quantity:get('quantity').value,buyRate:(lock.buy_rate/100).toFixed(2),extraBuyRate:lockFormValue(form,'extra_rate')});get('cost-material').value=(costs.materialCost/100).toFixed(2);}catch{get('cost-material').value='';} try{costs=priceLockDeliveryCost(lock,get('quantity').value,lockFormValue(form,'extra_rate'));get('cost-material').value=(costs.materialCost/100).toFixed(2);}catch{get('cost-material').value='';}
syncLine(row); syncLine(row);
// 冻结原锁价格及料费;其余销售项目、工费和实际费用仍沿用普通开单表单。 // 冻结原锁价格及料费;其余销售项目、工费和实际费用仍沿用普通开单表单。
for(const name of ['nameType','customName','unit','pricingMode','goldPrice','cost-materialMode','cost-materialPayer'])get(name).disabled=true; for(const name of ['nameType','customName','unit','pricingMode','goldPrice','cost-materialMode','cost-materialPayer'])get(name).disabled=true;
get('cost-material').readOnly=true;row.querySelector('.line-top button')?.remove(); get('cost-material').readOnly=true;row.querySelector('.line-top button')?.remove();
row.querySelector('.purchase-material .purchase-original').hidden=true; row.querySelector('.purchase-material .purchase-original').hidden=true;
row.querySelector('.purchase-material .purchase-formula').textContent=costs?`原锁使用 ${grams(costs.originalUsedMg)}g × ${yuan(lock.buy_rate)}元/克${costs.extraMg?';补重 '+grams(costs.extraMg)+'g × '+lockFormValue(form,'extra_rate')+'元/克':''} = ${yuan(costs.materialCost)}元`:'料费按原锁进货价计算;有补重时,请先填写补重进货料价。'; const poolMode=priceLockUsesPool(lock),formula=row.querySelector('.purchase-material .purchase-formula');
formula.textContent=costs?poolMode?`原锁按 ${lock.material_pool_id||lock.date} 料池耗用 ${grams(costs.originalUsedMg)}g,料费 ¥${yuan(costs.originalUsedCost)}${costs.extraMg?';补重 '+grams(costs.extraMg)+'g × '+lockFormValue(form,'extra_rate')+'元/克,料费 ¥'+yuan(costs.extraCost):''};合计 ¥${yuan(costs.materialCost)}`:`原锁使用 ${grams(costs.originalUsedMg)}g × ${yuan(lock.buy_rate)}元/克${costs.extraMg?';补重 '+grams(costs.extraMg)+'g × '+lockFormValue(form,'extra_rate')+'元/克':''} = ${yuan(costs.materialCost)}元`:poolMode?'原锁料费沿用料池实际分币金额;有补重时,请填写补重进货料价。':'料费按原锁进货价计算;有补重时,请先填写补重进货料价。';
if(poolMode){let payers=row.querySelector('.lock-pool-delivery-payers');if(!payers){formula.insertAdjacentHTML('afterend','<div class="lock-pool-delivery-payers price-lock-material-payers small"></div>');payers=row.querySelector('.lock-pool-delivery-payers');}payers.innerHTML='<strong>原锁耗用来源:</strong>'+priceLockAllocationHTML(costs?.allocations||priceLockMaterialAllocations(lock));}
get('goldPrice').closest('label').firstChild.textContent='原锁销售金价(元/克,固定)';get('cost-material').closest('label').firstChild.textContent='实际耗用料费合计(元,自动)';get('cost-materialPayer').closest('label').firstChild.textContent='原锁料费付款人';get('cost-materialMode').querySelector('option[value="total"]').textContent='原锁+补重自动核算';get('pocket').required=true;get('pocket').querySelector('option[value=""]').textContent='请选择实际黄金货盘'; get('goldPrice').closest('label').firstChild.textContent='原锁销售金价(元/克,固定)';get('cost-material').closest('label').firstChild.textContent='实际耗用料费合计(元,自动)';get('cost-materialPayer').closest('label').firstChild.textContent='原锁料费付款人';get('cost-materialMode').querySelector('option[value="total"]').textContent='原锁+补重自动核算';get('pocket').required=true;get('pocket').querySelector('option[value=""]').textContent='请选择实际黄金货盘';
form.querySelector('[name="original_stock"]').required=true; get('cost-materialPayer').closest('label').hidden=poolMode;
const originalStock=form.querySelector('[name="original_stock"]');originalStock.required=!poolMode;originalStock.disabled=poolMode;if(poolMode)originalStock.value='stocked';
const feeDate=form.querySelector('[name="fees_date"]');feeDate.value=lockFormValue(form,'date');feeDate.readOnly=true; const feeDate=form.querySelector('[name="fees_date"]');feeDate.value=lockFormValue(form,'date');feeDate.readOnly=true;
syncFeeRows();const d=collectPriceLockDelivery(); syncFeeRows();const d=collectPriceLockDelivery();
$('#lock-material-breakdown').textContent=costs?`原锁料费已付 ¥${yuan(lock.material_amount)};本单耗用料费 ¥${yuan(costs.materialCost)}${costs.leftoverMg?';余料 '+grams(costs.leftoverMg)+'g,成本 ¥'+yuan(costs.leftoverCost):''}`:extra?'请填写补重料价,计算本次实际耗用成本。':'填写最终交付克重,自动计算实际耗料。'; $('#lock-material-breakdown').textContent=costs?`原锁${poolMode?'预留':'料费已付'} ¥${yuan(lock.material_amount)};本单耗用料费 ¥${yuan(costs.materialCost)}${costs.leftoverMg?';'+(poolMode?'解除预留回池 ':'余料 ')+grams(costs.leftoverMg)+'g,成本 ¥'+yuan(costs.leftoverCost):''}${poolMode?';已有购料付款不重复登记。':''}`:extra?'请填写补重料价,计算本次实际耗用成本。':'填写最终交付克重,自动计算实际耗料。';
const original=d.inventory.original,pocket=d.inventory.pocket; const original=d.inventory.original,pocket=d.inventory.pocket;
$('#lock-stock-note').textContent=costs&&original&&pocket?`${original==='receive'?'原锁 '+grams(lock.locked_mg)+'g 先入库;':'原锁金料此前已入库;'}${costs.extraMg?(d.inventory.extra==='receive'?'补重 '+grams(costs.extraMg)+'g 先入库;':d.inventory.extra==='stocked'?'补重金料此前已入库;':'请选择补重金料是否已入库;'):''}从「${pocket}」出库 ${grams(costs.finalMg)}g。${costs.leftoverMg?'余料 '+grams(costs.leftoverMg)+'g 留在该货盘,按原进货价计成本,不重复入库。':''}`:'选择实际货盘和金料入库情况后,显示本次库存动作。'; $('#lock-stock-note').textContent=costs&&original&&pocket?`${poolMode?'原锁金料已在料池预留,不重复入库;':original==='receive'?'原锁 '+grams(lock.locked_mg)+'g 先入库;':'原锁金料此前已入库;'}${costs.extraMg?(d.inventory.extra==='receive'?'补重 '+grams(costs.extraMg)+'g 先入库;':d.inventory.extra==='stocked'?'补重金料此前已入库;':'请选择补重金料是否已入库;'):''}从「${pocket}」出库 ${grams(costs.finalMg)}g。${costs.leftoverMg?poolMode?'少重 '+grams(costs.leftoverMg)+'g 解除预留回到料池,实物留在货盘,不重复入库或扣料。':'余料 '+grams(costs.leftoverMg)+'g 留在该货盘,按原进货价计成本,不重复入库。':''}`:'选择实际货盘和金料入库情况后,显示本次库存动作。';
let difference=null; let difference=null;
try{ try{
const total=LedgerCalc.orderTotal([LedgerCalc.sale(d.line).sale],LedgerCalc.cents(d.discount),'yuan');difference=total.total-lock.netReceived; const total=LedgerCalc.orderTotal([LedgerCalc.sale(d.line).sale],LedgerCalc.cents(d.discount),'yuan');difference=total.total-lock.netReceived;
@@ -113,12 +190,12 @@ function syncPriceLockDelivery(){
} }
function syncPriceLockForm(){if($('#price-lock-create-form'))syncPriceLockCreate();else if($('#price-lock-delivery-form'))syncPriceLockDelivery();} function syncPriceLockForm(){if($('#price-lock-create-form'))syncPriceLockCreate();else if($('#price-lock-delivery-form'))syncPriceLockDelivery();}
async function finishPriceLockSave(url,data,result){ async function finishPriceLockSave(url,data,result){
$('#price-lock-dialog')?.close();invalidatePriceLockViews(); $('#price-lock-dialog')?.close();invalidatePriceLockViews();if(typeof invalidateMaterialPools==='function')invalidateMaterialPools();
if(url==='/api/price-locks'){ if(url==='/api/price-locks'){
const id=result.price_lock_id||result.id; const id=result.price_lock_id||result.id;
localStorage.removeItem(priceLockDraftKey());priceLockDeliveryId='';tab='price-locks'; localStorage.removeItem(priceLockDraftKey());priceLockDeliveryId='';tab='price-locks';
// POST已成功,立即移除可提交的表单;后续读取失败也不能再次创建。 // POST已成功,立即移除可提交的表单;后续读取失败也不能再次创建。
$('#main').innerHTML=heading('LOCK SAVED','锁价已保存','已经记好实际收款与原锁料款,尚未出入库、不计利润。')+`<section class="panel"><p id="lock-saved-status" aria-live="polite">正在读取已保存记录…</p><div class="actions">${button('查看已保存锁价单','open-price-lock','primary',`data-id="${e(id)}"`)}${button('重新读取待交付','refresh-price-locks')}</div></section>`; $('#main').innerHTML=heading('LOCK SAVED','锁价已保存',data.material?.source==='pool'?'已经记好实际收款并预留料池克重,料费没有重复付款;尚未出入库、不计利润。':'已经记好实际收款与原锁料款,尚未出入库、不计利润。')+`<section class="panel"><p id="lock-saved-status" aria-live="polite">正在读取已保存记录…</p><div class="actions">${button('查看已保存锁价单','open-price-lock','primary',`data-id="${e(id)}"`)}${button('重新读取待交付','refresh-price-locks')}</div></section>`;
document.querySelectorAll('nav button').forEach(b=>b.classList.toggle('active',b.dataset.tab===tab)); document.querySelectorAll('nav button').forEach(b=>b.classList.toggle('active',b.dataset.tab===tab));
try{await refresh();await openPriceLock(id);toast('锁价已保存到待交付,尚未出入库、不计利润');} try{await refresh();await openPriceLock(id);toast('锁价已保存到待交付,尚未出入库、不计利润');}
catch{if($('#lock-saved-status'))$('#lock-saved-status').textContent='锁价已经保存,最新页面暂未读到。请重新读取或查看已保存锁价单。';toast('锁价已经保存,请重新读取查看;不要重复新增。',true);} catch{if($('#lock-saved-status'))$('#lock-saved-status').textContent='锁价已经保存,最新页面暂未读到。请重新读取或查看已保存锁价单。';toast('锁价已经保存,请重新读取查看;不要重复新增。',true);}
@@ -136,13 +213,18 @@ async function submitPriceLockForm(form){
data=validateOrderIdentity(collectPriceLockCreate());url='/api/price-locks'; data=validateOrderIdentity(collectPriceLockCreate());url='/api/price-locks';
if(!data.customer||!data.line.name)throw new Error('请填写客户与黄金商品名称。'); if(!data.customer||!data.line.name)throw new Error('请填写客户与黄金商品名称。');
if(LedgerCalc.isSilver(data.line.name))throw new Error('锁价仅支持按克黄金,银饰请直接开单。'); if(LedgerCalc.isSilver(data.line.name))throw new Error('锁价仅支持按克黄金,银饰请直接开单。');
lockQuantityMg(data.line.quantity);if(LedgerCalc.cents(data.line.goldPrice)<=0||LedgerCalc.cents(data.material.rate)<=0)throw new Error('销售金价与原进货料价须大于0。'); lockQuantityMg(data.line.quantity);if(LedgerCalc.cents(data.line.goldPrice)<=0)throw new Error('销售金价须大于0。');
if(data.material.source==='pool'){
if(data.date!==state.today)throw new Error('当日加权料池只支持今天锁价;补录其他日期请使用手动填写料价。');
const preview=priceLockPoolPreview(data.date,data.line.quantity);if(!preview.covered)throw new Error(`当日料池还缺 ${grams(preview.shortageMg)}g,请先补足购料后再保存锁价。`);
if(!data.material.revision||data.material.revision!==preview.pool.revision)throw new Error('请刷新料池,核对当前成本与自动付款来源后再保存。');
}else if(LedgerCalc.cents(data.material.rate)<=0)throw new Error('原进货料价须大于0。');
LedgerCalc.cents(data.payment.amount,'客户实际付款');LedgerCalc.orderTotal([LedgerCalc.sale(data.line).sale],LedgerCalc.cents(data.discount),'yuan'); LedgerCalc.cents(data.payment.amount,'客户实际付款');LedgerCalc.orderTotal([LedgerCalc.sale(data.line).sale],LedgerCalc.cents(data.discount),'yuan');
if(isCreditCardAccount(data.payment.account)&&!creditCardAvailable())throw new Error('信用卡收款暂未准备好,请刷新后重新核对。'); if(isCreditCardAccount(data.payment.account)&&!creditCardAvailable())throw new Error('信用卡收款暂未准备好,请刷新后重新核对。');
if(!data.payment.verified||!data.material.verified)throw new Error('请核实客户实际付款与原锁料费实际付款。'); if(!data.payment.verified||data.material.source!=='pool'&&!data.material.verified)throw new Error('请核实客户实际付款与原锁料费实际付款。');
}else{ }else{
const lock=currentPriceLock;if(!lock||form.dataset.id!==lock.id)throw new Error('请重新读取锁价单后办理交付。');data=collectPriceLockDelivery();url='/api/price-locks/'+encodeURIComponent(lock.id)+'/deliver'; const lock=currentPriceLock;if(!lock||form.dataset.id!==lock.id)throw new Error('请重新读取锁价单后办理交付。');data=collectPriceLockDelivery();url='/api/price-locks/'+encodeURIComponent(lock.id)+'/deliver';
const costs=LedgerCalc.priceLockCost({lockedQuantity:grams(lock.locked_mg),quantity:data.line.quantity,buyRate:(lock.buy_rate/100).toFixed(2),extraBuyRate:data.extraMaterial.rate}); const costs=priceLockDeliveryCost(lock,data.line.quantity,data.extraMaterial.rate);
validateIssueDraft({lines:[data.line],fee_items:data.fee_items,discount:data.discount,rounding_mode:'yuan'},{requireIdentity:false}); validateIssueDraft({lines:[data.line],fee_items:data.fee_items,discount:data.discount,rounding_mode:'yuan'},{requireIdentity:false});
if(!state.pockets.includes(data.inventory.pocket)||!['receive','stocked'].includes(data.inventory.original))throw new Error('请选择实际出库货盘,并确认原锁金料是否已入库。'); if(!state.pockets.includes(data.inventory.pocket)||!['receive','stocked'].includes(data.inventory.original))throw new Error('请选择实际出库货盘,并确认原锁金料是否已入库。');
if(costs.extraMg&&(!['receive','stocked'].includes(data.inventory.extra)||!['owner','assistant','assistant2'].includes(data.extraMaterial.payer)||!data.extraMaterial.verified))throw new Error('请填写补重料价、付款人、是否已入库,并确认实际付款。'); if(costs.extraMg&&(!['receive','stocked'].includes(data.inventory.extra)||!['owner','assistant','assistant2'].includes(data.extraMaterial.payer)||!data.extraMaterial.verified))throw new Error('请填写补重料价、付款人、是否已入库,并确认实际付款。');
+12 -12
View File
@@ -3,6 +3,7 @@
const {randomUUID,createHash}=require('node:crypto'); const {randomUUID,createHash}=require('node:crypto');
const Calc=require('./public/calculations'); const Calc=require('./public/calculations');
const KEY='rolling-material-pools-v1',PARTIES=['owner','assistant','assistant2']; const KEY='rolling-material-pools-v1',PARTIES=['owner','assistant','assistant2'];
const LockPools=require('./price-lock-pools');
const sum=(rows,key)=>rows.reduce((n,row)=>n+(row[key]??0),0); const sum=(rows,key)=>rows.reduce((n,row)=>n+(row[key]??0),0);
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex'); const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const legacy=()=>require('./material-pools'); const legacy=()=>require('./material-pools');
@@ -19,6 +20,7 @@ function withHistorical(l,fn){const previous=l.rollingHistorical;l.rollingHistor
function assertDate(l,date,env){if(enabled(l)&&!l.rollingHistorical&&date!==env.today())env.fail('已结转日期的料池已冻结,历史更正须提交麦麦复核',409);} function assertDate(l,date,env){if(enabled(l)&&!l.rollingHistorical&&date!==env.today())env.fail('已结转日期的料池已冻结,历史更正须提交麦麦复核',409);}
function dependency(l){ function dependency(l){
const tables=['material_purchases','material_purchase_shares','material_purchase_payment_origins','recovery_purchase_sources','material_pool_usages','material_usage_parties','material_rolling_days','material_rolling_returns','material_rolling_legacy','material_rolling_source_order']; const tables=['material_purchases','material_purchase_shares','material_purchase_payment_origins','recovery_purchase_sources','material_pool_usages','material_usage_parties','material_rolling_days','material_rolling_returns','material_rolling_legacy','material_rolling_source_order'];
if(l.one('SELECT id FROM price_lock_pool_reservations LIMIT 1'))tables.push('price_lock_pool_reservations','price_lock_pool_returns','price_locks','material_usage_order');
return hash({config:config(l),tables:tables.map(table=>[table,l.rows('SELECT * FROM '+table+' ORDER BY rowid')]),orders:l.rows('SELECT id,revision,status,lines FROM orders ORDER BY rowid')}); return hash({config:config(l),tables:tables.map(table=>[table,l.rows('SELECT * FROM '+table+' ORDER BY rowid')]),orders:l.rows('SELECT id,revision,status,lines FROM orders ORDER BY rowid')});
} }
function parts(p){return (p.allocations??[{payer:p.payer,amount:p.amount}]).filter(a=>a.amount>0);} function parts(p){return (p.allocations??[{payer:p.payer,amount:p.amount}]).filter(a=>a.amount>0);}
@@ -110,13 +112,13 @@ function consumed(l,u,date){return !!u.active||!!l.rollingRebuilding&&!!l.one('S
function readSources(l,date,env,saved=l.one('SELECT * FROM material_rolling_days WHERE date=?',date)){ function readSources(l,date,env,saved=l.one('SELECT * FROM material_rolling_days WHERE date=?',date)){
const opening=saved?JSON.parse(saved.opening):nextOpening(l,date,env); const opening=saved?JSON.parse(saved.opening):nextOpening(l,date,env);
const actual=l.rows("SELECT p.*,s.sequence AS source_sequence FROM material_purchases p LEFT JOIN material_rolling_source_order s ON s.kind='purchase' AND s.source_id=p.id WHERE p.date=? AND p.deleted_at='' ORDER BY p.created,p.rowid",date).map(r=>({...legacy().actualPurchase(l,r),sourceKind:'purchase'})); const actual=l.rows("SELECT p.*,s.sequence AS source_sequence FROM material_purchases p LEFT JOIN material_rolling_source_order s ON s.kind='purchase' AND s.source_id=p.id WHERE p.date=? AND p.deleted_at='' ORDER BY p.created,p.rowid",date).map(r=>({...legacy().actualPurchase(l,r),sourceKind:'purchase'}));
const returns=returnsFor(l,date),netReturns=returns.filter(r=>!r.sameDay); const returns=[...returnsFor(l,date),...LockPools.returns(l,date)],netReturns=returns.filter(r=>!r.sameDay);
const carry=opening.mg?[{id:'carry:'+date,date,mg:opening.mg,amount:opening.amount,payer:opening.allocations?.[0]?.payer??'owner',allocations:opening.allocations??[],created:date+'T00:00:00.000Z',note:'以前结转',sourceKind:'carry',cashAmount:0,canEdit:false}]:[]; const carry=opening.mg?[{id:'carry:'+date,date,mg:opening.mg,amount:opening.amount,payer:opening.allocations?.[0]?.payer??'owner',allocations:opening.allocations??[],created:date+'T00:00:00.000Z',note:'以前结转',sourceKind:'carry',cashAmount:0,canEdit:false}]:[];
const returned=netReturns.map(r=>({...r,id:'return:'+r.id,payer:r.allocations[0]?.payer??'owner',sourceKind:'return',note:'退货回料',canEdit:false})); const returned=netReturns.map(r=>({...r,id:'return:'+r.id,payer:r.allocations[0]?.payer??'owner',sourceKind:'return',note:r.note??'退货回料',canEdit:false}));
const purchases=[...carry,...[...actual,...returned].sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.source_sequence-b.source_sequence)]; const purchases=[...carry,...[...actual,...returned].sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.source_sequence-b.source_sequence)];
const usages=l.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,...r})=>({...r,...l.one('SELECT assistant2_amount FROM material_usage_parties WHERE usage_id=?',r.id),product:JSON.parse(lines)[r.line_index]?.name??''})); const usages=LockPools.combined(l,date,l.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,...r})=>({...r,...l.one('SELECT assistant2_amount FROM material_usage_parties WHERE usage_id=?',r.id),product:JSON.parse(lines)[r.line_index]?.name??''})));
const totalMg=opening.mg+sum(actual,'mg')+sum(netReturns,'mg'),totalAmount=opening.amount===null?null:opening.amount+sum(actual,'amount')+sum(netReturns,'amount'),active=usages.filter(r=>consumed(l,r,date)),usedMg=sum(active,'mg'); const totalMg=opening.mg+sum(actual,'mg')+sum(netReturns,'mg'),totalAmount=opening.amount===null||netReturns.some(r=>r.amount===null)?null:opening.amount+sum(actual,'amount')+sum(netReturns,'amount'),active=usages.filter(r=>consumed(l,r,date)),usedMg=sum(active,'mg');
return {id:date,date,opening,actual,returns,netReturns,purchases,usages,totalMg,totalAmount,usedMg,averageRate:totalAmount!==null&&totalMg?Calc.poolMaterialAmount(totalAmount,totalMg,1000):null,revision:hash({opening,actual,returns,usages:usages.map(({lines,...r})=>r)})}; return {id:date,date,rolling:true,opening,actual,returns,netReturns,purchases,usages,totalMg,totalAmount,usedMg,averageRate:totalAmount!==null&&totalMg?Calc.poolMaterialAmount(totalAmount,totalMg,1000):null,revision:hash({opening,actual,returns,usages:usages.map(({lines,...r})=>r)})};
} }
function readPool(l,date,env,{internal=false,live=false}={}){ function readPool(l,date,env,{internal=false,live=false}={}){
const saved=l.one('SELECT * FROM material_rolling_days WHERE date=?',date); const saved=l.one('SELECT * FROM material_rolling_days WHERE date=?',date);
@@ -130,11 +132,7 @@ function readPool(l,date,env,{internal=false,live=false}={}){
revision,opening,todayPurchases:{mg:sum(actual,'mg'),amount:sum(actual,'amount'),count:actual.length,items:actual},todayReturns:{mg:sum(netReturns,'mg'),amount:sum(netReturns,'amount'),count:netReturns.length,grossMg:sum(returns,'mg'),grossAmount:sum(returns,'amount'),grossCount:returns.length},returns,purchases,usages,settlements:[],settlement:{legacyReadOnly:true,settlementDue:0,assistantInventoryCredit:0,transferred:0,pending}}; revision,opening,todayPurchases:{mg:sum(actual,'mg'),amount:sum(actual,'amount'),count:actual.length,items:actual},todayReturns:{mg:sum(netReturns,'mg'),amount:sum(netReturns,'amount'),count:netReturns.length,grossMg:sum(returns,'mg'),grossAmount:sum(returns,'amount'),grossCount:returns.length},returns,purchases,usages,settlements:[],settlement:{legacyReadOnly:true,settlementDue:0,assistantInventoryCredit:0,transferred:0,pending}};
return internal?pool:legacy().visiblePool(l,pool); return internal?pool:legacy().visiblePool(l,pool);
} }
function allocations(pool,usages){ function allocations(pool,usages){return LockPools.allocate(pool,usages,legacy().allocatePayers);}
const missing=pool.totalAmount===null||sum(usages,'mg')>pool.totalMg;let mg=0,previous=0;
return usages.map(u=>{mg+=u.mg;const accumulated=missing?null:Calc.poolMaterialAmount(pool.totalAmount,pool.totalMg,mg),amount=accumulated===null?null:accumulated-previous;
const paid=amount===null?{owner_amount:null,assistant_amount:null,assistant2_amount:null}:legacy().allocatePayers(pool.purchases.filter(p=>p.amount>0),previous,amount);previous=accumulated??0;return {...u,amount,...paid};});
}
function applyLine(line,row,pool){ function applyLine(line,row,pool){
const a=PARTIES.map(p=>({payer:p,amount:row[p+'_amount']??0})).filter(p=>p.amount>0);if(row.amount===0&&!a.length)a.push({payer:row.zero_payer??'owner',amount:0}); const a=PARTIES.map(p=>({payer:p,amount:row[p+'_amount']??0})).filter(p=>p.amount>0);if(row.amount===0&&!a.length)a.push({payer:row.zero_payer??'owner',amount:0});
line.costParts={...line.costParts,material:row.amount};line.cost=Object.values(line.costParts).some(v=>v===null)?null:sum(Object.values(line.costParts).map(amount=>({amount})),'amount'); line.costParts={...line.costParts,material:row.amount};line.cost=Object.values(line.costParts).some(v=>v===null)?null:sum(Object.values(line.costParts).map(amount=>({amount})),'amount');
@@ -143,14 +141,15 @@ function applyLine(line,row,pool){
function prepareLines(l,lines,businessDate,env,{orderId=null}={}){ function prepareLines(l,lines,businessDate,env,{orderId=null}={}){
const selected=lines.flatMap((line,index)=>line.costMaterial?.mode==='pool'?[{line,index}]:[]);if(!selected.length)return lines;assertDate(l,businessDate,env); const selected=lines.flatMap((line,index)=>line.costMaterial?.mode==='pool'?[{line,index}]:[]);if(!selected.length)return lines;assertDate(l,businessDate,env);
for(const {line} of selected){if(line.costMaterial.poolId!==businessDate)env.fail('滚动日料池须使用订单当天日期');if(line.unit!=='g'||Calc.isSilver(line.name))env.fail('日购料成本只支持按克黄金商品');} for(const {line} of selected){if(line.costMaterial.poolId!==businessDate)env.fail('滚动日料池须使用订单当天日期');if(line.unit!=='g'||Calc.isSilver(line.name))env.fail('日购料成本只支持按克黄金商品');}
const pool=readPool(l,businessDate,env,{internal:true}),original=l.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId??''),last=l.one('SELECT COALESCE(MAX(rowid),0) AS n FROM material_pool_usages').n; const pool=readPool(l,businessDate,env,{internal:true}),original=LockPools.decorate(l,l.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId??'')),last=l.one('SELECT COALESCE(MAX(sequence),0) AS n FROM material_usage_order').n;
const usages=pool.usages.filter(u=>u.active&&u.order_id!==orderId);for(const {line,index} of selected){const before=original.find(u=>u.line_index===index);usages.push({...before,mg:line.costMaterial?.consumptionMg??line.quantity,preview_index:index,created:before?.created??env.now(),fifo_sequence:before?.fifo_sequence??last+index+1});} const usages=pool.usages.filter(u=>u.active&&(!orderId||u.order_id!==orderId));for(const {line,index} of selected){const before=original.find(u=>u.line_index===index);usages.push({...before,mg:line.costMaterial?.consumptionMg??line.quantity,preview_index:index,created:before?.created??env.now(),fifo_sequence:before?.fifo_sequence??last+index+1});}
usages.sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);for(const u of allocations(pool,usages))if(u.preview_index!==undefined)applyLine(lines[u.preview_index],u,pool);return lines; usages.sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);for(const u of allocations(pool,usages))if(u.preview_index!==undefined)applyLine(lines[u.preview_index],u,pool);return lines;
} }
function reconcile(l,...args){return l.scope(null,()=>reconcileInternal(l,...args),null);} function reconcile(l,...args){return l.scope(null,()=>reconcileInternal(l,...args),null);}
function reconcileInternal(l,date,actor,env,{skipJournalOrder=null}={}){ function reconcileInternal(l,date,actor,env,{skipJournalOrder=null}={}){
assertDate(l,date,env);ensureDay(l,date,env);const pool=readSources(l,date,env),updates=new Map(); assertDate(l,date,env);ensureDay(l,date,env);const pool=readSources(l,date,env),updates=new Map();
for(const u of allocations(pool,pool.usages.filter(u=>consumed(l,u,date)))){ for(const u of allocations(pool,pool.usages.filter(u=>consumed(l,u,date)))){
if(u.kind==='priceLock'){LockPools.update(l,u,pool,actor,env,{skipJournalOrder});continue;}
if(!updates.has(u.order_id))updates.set(u.order_id,{order:l.rawOrder(u.order_id),delta:0,changed:false});const v=updates.get(u.order_id),line=v.order.lines[u.line_index]; if(!updates.has(u.order_id))updates.set(u.order_id,{order:l.rawOrder(u.order_id),delta:0,changed:false});const v=updates.get(u.order_id),line=v.order.lines[u.line_index];
if(!line||line.costMaterial?.poolId!==date)env.fail('滚动料池与商品来源不一致',409); if(!line||line.costMaterial?.poolId!==date)env.fail('滚动料池与商品来源不一致',409);
const before=line.costParts?.material,oldAlloc=line.materialPool?.allocations,oldRate=line.materialPool?.averageRate; const before=line.costParts?.material,oldAlloc=line.materialPool?.allocations,oldRate=line.materialPool?.averageRate;
@@ -163,6 +162,7 @@ function reconcileInternal(l,date,actor,env,{skipJournalOrder=null}={}){
} }
function recordReturns(l,order,date,input,actor,env){ function recordReturns(l,order,date,input,actor,env){
if(!enabled(l)||date<config(l).cutover)return;assertDate(l,date,env);ensureDay(l,date,env); if(!enabled(l)||date<config(l).cutover)return;assertDate(l,date,env);ensureDay(l,date,env);
if(LockPools.recordReturn(l,order,date,input,actor,env))return;
for(const [index,line] of order.lines.entries()){ for(const [index,line] of order.lines.entries()){
const destination=input.returnPockets?.[index]??line.pocket;if(!env.selfPockets?.includes(destination)||line.unit!=='g'||Calc.isSilver(line.name))continue; const destination=input.returnPockets?.[index]??line.pocket;if(!env.selfPockets?.includes(destination)||line.unit!=='g'||Calc.isSilver(line.name))continue;
const amount=line.costParts?.material;if(!Number.isSafeInteger(amount)||amount<0)env.fail('原商品金料成本尚未核实,不能将未知金额记为退货回料',409); const amount=line.costParts?.material;if(!Number.isSafeInteger(amount)||amount<0)env.fail('原商品金料成本尚未核实,不能将未知金额记为退货回料',409);
+9
View File
@@ -1,6 +1,7 @@
'use strict'; 'use strict';
// 三个经营款账户独立核算。新账只追加来源差额,旧二人结算绝不自动带入。 // 三个经营款账户独立核算。新账只追加来源差额,旧二人结算绝不自动带入。
const {randomUUID,createHash}=require('node:crypto'); const {randomUUID,createHash}=require('node:crypto');
const LockPools=require('./price-lock-pools');
const MEMBERS=['owner','assistant','assistant2']; const MEMBERS=['owner','assistant','assistant2'];
const NAMES={owner:'麦麦',assistant:'助理1',assistant2:'助理2'}; const NAMES={owner:'麦麦',assistant:'助理1',assistant2:'助理2'};
const LIMIT=100000000000; const LIMIT=100000000000;
@@ -105,6 +106,14 @@ function orderSnapshot(ledger,id,env){
} }
function priceLockSnapshot(ledger,id){ function priceLockSnapshot(ledger,id){
const snapshot=empty(),liable=entityMember(ledger,'price_lock',id);if(!liable)return snapshot; const snapshot=empty(),liable=entityMember(ledger,'price_lock',id);if(!liable)return snapshot;
const reserved=LockPools.find(ledger,id);if(reserved){
if(reserved.amount===null)snapshot.pending.push({member:liable,project:'锁价料池成本待补'});
else for(const part of reserved.allocations)obligation(snapshot,'pool-lock:'+reserved.id+':'+part.payer,ledger.one('SELECT date FROM price_locks WHERE id=?',id).date,'material_usage','锁价料池预留',liable,part.payer,part.amount);
for(const returned of ledger.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY rowid',id)){
if(returned.amount===null){snapshot.pending.push({member:liable,project:'锁价回料成本待补'});continue;}
for(const part of JSON.parse(returned.allocations))obligation(snapshot,'pool-lock-return:'+returned.id+':'+part.payer,returned.date,'material_return','锁价金料回池',part.payer,liable,part.amount);
}
}
for(const event of ledger.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY date,created,rowid',id)){ for(const event of ledger.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY date,created,rowid',id)){
if(event.kind==='material')addOutlay(snapshot,'material:'+event.id,event.date,'advance','锁价实际购料',liable,event.payer,event.amount); if(event.kind==='material')addOutlay(snapshot,'material:'+event.id,event.date,'advance','锁价实际购料',liable,event.payer,event.amount);
else addPayment(snapshot,event,liable,event.date); else addPayment(snapshot,event,liable,event.date);
@@ -110,3 +110,8 @@ test('恢复原操作入口对新启用路由复用原key,并在409时返回
const h=harness(),job={url:'/api/material-pools/rolling-enable',data:{date:TODAY,revision:'server-hash',verified:true},key:'stable-original-key'},button={dataset:{action:'retry'},disabled:false,closest(selector){return selector==='button'?this:null;}};h.saved.set('mm-pending-'+h.user.id,JSON.stringify(job));h.run('captureOrderDetailReload=function(){return null;};api=async function(url,data,key){__posts.push({url,data,key});return {enabled:true};};finishMaterialRollingMutation=async function(url,input,result){__finished={url,input,result};};');await h.handlers.click[0]({target:button});assert.equal(h.posts[0].key,job.key);assert.equal(h.context.__finished.url,job.url);assert.equal(h.saved.has('mm-pending-'+h.user.id),false); const h=harness(),job={url:'/api/material-pools/rolling-enable',data:{date:TODAY,revision:'server-hash',verified:true},key:'stable-original-key'},button={dataset:{action:'retry'},disabled:false,closest(selector){return selector==='button'?this:null;}};h.saved.set('mm-pending-'+h.user.id,JSON.stringify(job));h.run('captureOrderDetailReload=function(){return null;};api=async function(url,data,key){__posts.push({url,data,key});return {enabled:true};};finishMaterialRollingMutation=async function(url,input,result){__finished={url,input,result};};');await h.handlers.click[0]({target:button});assert.equal(h.posts[0].key,job.key);assert.equal(h.context.__finished.url,job.url);assert.equal(h.saved.has('mm-pending-'+h.user.id),false);
h.saved.set('mm-pending-'+h.user.id,JSON.stringify(job));h.run('api=async function(){const err=new Error("切换依据有变动");err.status=409;err.confirmed=true;throw err;};');await h.handlers.click[0]({target:button});assert.match(h.nodes.get('#material-rolling-error').innerHTML,/重新核对/);assert.equal(h.saved.has('mm-pending-'+h.user.id),false); h.saved.set('mm-pending-'+h.user.id,JSON.stringify(job));h.run('api=async function(){const err=new Error("切换依据有变动");err.status=409;err.confirmed=true;throw err;};');await h.handlers.click[0]({target:button});assert.match(h.nodes.get('#material-rolling-error').innerHTML,/重新核对/);assert.equal(h.saved.has('mm-pending-'+h.user.id),false);
}); });
test('历史购料更正复核同时展示关联锁价的前后料费和自动付款归属',async()=>{
const h=harness(),row=change();row.preview.relatedPriceLocks=[{id:'affected-lock',number:'合成关联锁价',date:OLD,customer:'合成<锁价客户>',before:{materialAmount:90000,usedMaterialAmount:0,leftoverCost:0,allocations:[{payer:'owner',amount:90000}]},after:{materialAmount:91000,usedMaterialAmount:0,leftoverCost:0,allocations:[{payer:'owner',amount:50000},{payer:'assistant2',amount:41000}]}}];h.context.__request=row;h.run('api=async()=>__request');await h.run('openMaterialChange("synthetic-change")');
assert.match(h.dialog.innerHTML,/合成关联锁价/);assert.match(h.dialog.innerHTML,/合成&lt;锁价客户&gt;/);assert.match(h.dialog.innerHTML,/原锁预留料费/);assert.match(h.dialog.innerHTML,/¥900\.00/);assert.match(h.dialog.innerHTML,/¥910\.00/);assert.match(h.dialog.innerHTML,/助理2 ¥410\.00/);
row.preview.relatedPriceLocks[0].after.allocations=[];assert.throws(()=>h.run('validateMaterialChangeRequest(__request,true)'),/锁价单的成本影响未完整返回/);
});
@@ -49,6 +49,11 @@ test('修改申请对照分列客户单备注与内部备注,内部原值新
const h=harness();h.context.__request=request({before:order({internal_note:'原内部备注\n<原尺寸>'}),after:order({internal_note:'新内部备注\n<新尺寸>'})}); const h=harness();h.context.__request=request({before:order({internal_note:'原内部备注\n<原尺寸>'}),after:order({internal_note:'新内部备注\n<新尺寸>'})});
const html=h.run('orderChangeComparisonHTML(__request)');assert.match(html,/客户单备注/);assert.match(html,/内部备注(客户不可见)/);assert.match(html,/原内部备注<br>&lt;原尺寸&gt;/);assert.match(html,/新内部备注<br>&lt;新尺寸&gt;/);assert.doesNotMatch(html,/<原尺寸>|<新尺寸>/); const html=h.run('orderChangeComparisonHTML(__request)');assert.match(html,/客户单备注/);assert.match(html,/内部备注(客户不可见)/);assert.match(html,/原内部备注<br>&lt;原尺寸&gt;/);assert.match(html,/新内部备注<br>&lt;新尺寸&gt;/);assert.doesNotMatch(html,/<原尺寸>|<新尺寸>/);
}); });
test('订单修改复核附带同池锁价影响,关联订单不会重复渲染锁价清单',()=>{
const h=harness(),row=request(),otherBefore=order({id:RELATED}),otherAfter=order({id:RELATED,goodsCost:190000,profit:18000});row.relatedOrders=[{id:RELATED,number:'合成关联订单',before:otherBefore,after:otherAfter,summary:{before:summary(otherBefore),after:summary(otherAfter)}}];row.relatedPriceLocks=[{id:'synthetic-related-lock',date:D,number:'合成关联锁价',customer:'合成<锁价客户>',before:{materialAmount:85000,usedMaterialAmount:0,leftoverCost:0,allocations:[{payer:'owner',amount:85000}]},after:{materialAmount:86000,usedMaterialAmount:0,leftoverCost:0,allocations:[{payer:'owner',amount:80000},{payer:'assistant',amount:6000}]}}];h.context.__request=row;
const html=h.run('orderChangeComparisonHTML(__request)');assert.equal((html.match(/同时受影响的锁价单/g)||[]).length,1);assert.match(html,/合成关联锁价/);assert.match(html,/合成&lt;锁价客户&gt;/);assert.match(html,/¥850\.00/);assert.match(html,/¥860\.00/);assert.match(html,/助理 ¥60\.00/);
row.relatedPriceLocks[0].after.allocations=[];assert.throws(()=>h.run('validateOrderChangeRequest(__request)'),/锁价单的成本影响未完整返回/);
});
test('助理显示申请修改,不能审批;旧成本入口转为申请',()=>{ test('助理显示申请修改,不能审批;旧成本入口转为申请',()=>{
const h=harness('assistant');h.run('renderDetail()');const html=h.nodes.get('#order-content').innerHTML;assert.match(html,/申请修改/);assert.ok(!html.includes('>修改订单<')); const h=harness('assistant');h.run('renderDetail()');const html=h.nodes.get('#order-content').innerHTML;assert.match(html,/申请修改/);assert.ok(!html.includes('>修改订单<'));
h.prepare(request());const pending=h.run('orderChangeDetailHTML(currentOrder)');assert.match(pending,/申请尚未生效/);assert.ok(!pending.includes('approve-order-change'));assert.ok(!pending.includes('reject-order-change'));assert.throws(()=>h.run("showOrderChangeForm('approve')"),/麦麦账号/); h.prepare(request());const pending=h.run('orderChangeDetailHTML(currentOrder)');assert.match(pending,/申请尚未生效/);assert.ok(!pending.includes('approve-order-change'));assert.ok(!pending.includes('reject-order-change'));assert.throws(()=>h.run("showOrderChangeForm('approve')"),/麦麦账号/);
@@ -0,0 +1,85 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
const {Ledger,today,day,money,weight,text,fail}=require('../ledger'),{createUser}=require('../server');
const MaterialPools=require('../material-pools'),Calc=require('../public/calculations');
const D=today();
function fixture(t){
const l=new Ledger(':memory:'),actors={};t.after(()=>l.close());
for(const member of ['owner','assistant','assistant2']){
const role=member==='owner'?'owner':'assistant',name='合成'+member;
actors[member]={id:createUser(l,name,role,'synthetic-lock-approval-password',member),name,role,member};
}
l.enableTeamMode();
const run=(data,fn,member='owner')=>l.scope(actors[member],()=>l.transact(randomUUID(),actors[member],data,fn));
run({},()=>l.stock({date:D,kind:'opening',pocket:'现货',grams:'100',note:'合成库存'},actors.owner));
const buy=(grams,total,payer='owner')=>{const input={date:D,grams,total,payer,note:'合成购料'};return run(input,()=>l.createMaterialPurchase(input,actors.owner));};
const enable=()=>{const preview=l.rollingMaterialPreview({},actors.owner);return run(preview,()=>l.enableRollingMaterial({date:D,revision:preview.revision,verified:true},actors.owner));};
const lock=(quantity='1',member='assistant')=>{
const input={date:D,customer:'私密锁客-'+member,salesperson:'合成开单',line:{name:'私密足金挂件',unit:'g',quantity,goldPrice:'1000',laborRate:'0',laborMode:'gram'},
material:{source:'pool',poolId:D,revision:l.materialPoolDetail(D).revision},payment:{amount:(Number(quantity)*1000).toFixed(2),account:member==='assistant2'?'助理2微信':'助理微信',verified:true}};
return run(input,()=>l.createPriceLock(input,actors[member]),member).id;
};
const issue=(quantity='1')=>{
const input={date:D,customer:'普通合成客户',salesperson:'合成开单',payment_account:'助理微信',rounding_mode:'yuan',fee_items:[],
lines:[{name:'足金999',unit:'g',quantity,pocket:'现货',payer:'owner',sale:(Number(quantity)*1000).toFixed(2),costParts:{material:'',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'pool',poolId:D}}]};
return run(input,()=>l.issueOrder(input,actors.assistant),'assistant').id;
};
const deliver=(id,quantity)=>{
const detail=l.priceLockDetail(id),difference=Number(quantity)*1000-detail.netReceived/100,input={date:D,revision:detail.revision,verified:true,
line:{quantity,laborRate:'0',laborMode:'gram',payer:'assistant',costParts:{labor:'0',accessories:'0',other:'0'},costPayers:{material:'assistant',labor:'assistant'}},
inventory:{pocket:'现货',original:'stocked'},fee_items:[],...(difference?{settlement:{amount:Math.abs(difference).toFixed(2),account:'助理微信',verified:true}}:{})};
return run(input,()=>l.deliverPriceLock(id,input,actors.assistant),'assistant').id;
};
const request=(id,input)=>run(input,()=>l.requestOrderChange(id,input,actors.assistant),'assistant');
const approve=request=>run(request,()=>l.approveOrderChange(request.requestId,{revision:request.request.order_revision,verified:true},actors.owner));
return {l,actors,run,buy,enable,lock,issue,deliver,request,approve};
}
const contents=l=>JSON.stringify(l.rows("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").map(({name})=>[name,l.rows('SELECT * FROM "'+name+'" ORDER BY rowid')]));
const financial=l=>JSON.stringify(['orders','payments','expenses','journal','movements','material_purchases','material_pool_usages','material_usage_parties','material_rolling_days','material_rolling_returns','price_locks','price_lock_events','price_lock_pool_reservations','price_lock_pool_returns','team_fund_cash','team_fund_transfers'].map(table=>[table,l.rows('SELECT * FROM '+table+' ORDER BY rowid')]));
test('普通改单试算展示关联锁成本和归属,助理看不到他人锁客户,批准与试算一致',t=>{
const f=fixture(t);f.buy('1','800','assistant2');f.buy('2','2000','owner');f.enable();
const order=f.issue(),lock=f.lock('1','assistant2'),before=financial(f.l),input={...f.l.orderEdit(order,f.actors.assistant).inputs,revision:f.l.rawOrder(order).revision,reason:'合成实际改重',verified:true};
input.lines[0].quantity='1.5';input.lines[0].sale='1500';input.lines[0].baseSale='1500';
const request=f.request(order,input);assert.equal(financial(f.l),before,'申请中的试算必须回滚原账');
assert.deepEqual(request.request.relatedPriceLocks,[]);
const ownerView=f.l.orderChangeRequest(request.requestId,f.actors.owner),related=ownerView.relatedPriceLocks.find(row=>row.id===lock);
assert.ok(related);assert.equal(related.customer,'私密锁客-assistant2');assert.equal(related.before.materialAmount,93334);assert.equal(related.after.materialAmount,93333);
assert.ok(!JSON.stringify(request.request).includes('私密锁客-assistant2'));
assert.equal(f.approve(request).request.status,'approved');assert.equal(f.l.priceLockDetail(lock).materialPool.amount,related.after.materialAmount);
});
test('待批改单和取消遇新池锁均过期,批准失败不改变任何表',t=>{
const f=fixture(t);f.buy('5','4500');f.enable();const editOrder=f.issue(),cancelOrder=f.issue();
const input={...f.l.orderEdit(editOrder,f.actors.assistant).inputs,revision:f.l.rawOrder(editOrder).revision,customer:'更正合成客户',reason:'合成备注更正',verified:true};
const change=f.request(editOrder,input),cancellation=f.run({},()=>f.l.requestOrderCancellation(cancelOrder,{revision:f.l.rawOrder(cancelOrder).revision,reason:'合成录错作废'},f.actors.assistant),'assistant');
f.lock();assert.equal(f.l.orderChangeRequest(change.requestId,f.actors.owner).stale,true);assert.equal(f.l.orderCancellation(cancelOrder,f.actors.owner).pending.stale,true);
const before=contents(f.l);assert.throws(()=>f.approve(change),/过期/);assert.equal(contents(f.l),before);
assert.throws(()=>f.run({},()=>f.l.approveOrderCancellation(cancellation.requestId,{revision:cancellation.request.order_revision,verified:true},f.actors.owner)),/过期/);assert.equal(contents(f.l),before);
});
test('归属审批独立覆盖池锁预留快照,主单版本未变也不能批准旧依据',t=>{
const f=fixture(t);f.buy('2','1800');f.enable();const lock=f.lock('1.5'),order=f.deliver(lock,'1'),revision=f.l.rawOrder(order).revision;
const input={member:'assistant2',revision,reason:'合成核对归属',verified:true},request=f.run(input,()=>f.l.changeOrderOwnership(order,input,f.actors.assistant),'assistant');
const row=f.l.one('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=?',lock),snapshot=JSON.parse(row.snapshot);snapshot.basisAmount++;
f.l.run('UPDATE price_lock_pool_reservations SET snapshot=? WHERE id=?',JSON.stringify(snapshot),row.id);
assert.equal(f.l.rawOrder(order).revision,revision);assert.equal(f.l.orderOwnershipChange(request.requestId,f.actors.owner).stale,true);
const before=contents(f.l);assert.throws(()=>f.run({},()=>f.l.approveOrderOwnership(request.requestId,{revision,verified:true},f.actors.owner)),/过期/);assert.equal(contents(f.l),before);
});
test('池锁退货试算回滚,随机回料身份不误拒审批;退货后归属转移保留真实现金',t=>{
const f=fixture(t);f.buy('2','1800');f.enable();const lock=f.lock('1.5'),order=f.deliver(lock,'1'),before=financial(f.l),cash=JSON.stringify(f.l.rows('SELECT * FROM team_fund_cash ORDER BY rowid'));
const input={action:'return',date:D,revision:f.l.rawOrder(order).revision,reason:'合成实物已退回',verified:true,returnPockets:['现货']},request=f.request(order,input);
assert.equal(financial(f.l),before);assert.equal(f.approve(request).request.status,'approved');assert.equal(f.l.detail(order).status,'returned');assert.equal(f.l.materialPools().current.usedMg,0);
assert.equal(JSON.stringify(f.l.rows('SELECT * FROM team_fund_cash ORDER BY rowid')),cash);
const transfer={member:'assistant2',revision:f.l.rawOrder(order).revision,reason:'合成归属核对',verified:true};f.run(transfer,()=>f.l.changeOrderOwnership(order,transfer,f.actors.owner));
assert.equal(f.l.entityMember('price_lock',lock),'assistant2');assert.equal(JSON.stringify(f.l.rows('SELECT * FROM team_fund_cash ORDER BY rowid')),cash);
});
test('同毫秒锁单和普通单交错,服务端与浏览器预估都遵循全局FIFO且只读',t=>{
const f=fixture(t);f.buy('0.005','0.01');f.enable();f.lock('0.001');f.issue('0.001');f.lock('0.001');
const timestamp=D+'T01:00:00.000Z';f.l.run('UPDATE material_pool_usages SET created=?',timestamp);f.l.run('UPDATE price_lock_pool_reservations SET created=?',timestamp);
const pool=f.l.materialPools().current,lines=f.l.validateLines([{name:'足金999',unit:'g',quantity:'0.001',pocket:'现货',payer:'owner',sale:'1',costParts:{material:'',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'pool',poolId:D}}],[],D),before=contents(f.l);
const server=MaterialPools.prepareLines(f.l,lines,D,{day,money,weight,text,fail,today:()=>D,now:()=>timestamp})[0].materialPool.amount,browser=Calc.poolMaterialPreview(pool,[{lineIndex:0,mg:1}]).amounts[0];
assert.equal(server,0);assert.equal(server,browser);assert.equal(contents(f.l),before);
});
@@ -0,0 +1,95 @@
'use strict';
// 全部为虚构DTO与内存DOM,不读取磁盘账本,也不发出网络请求。
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'),{randomUUID}=require('node:crypto');
const Calc=require('../public/calculations');
const D='2026-11-02',OLD='2026-11-01';
function node(extra={}){const classes=new Set();return {value:'',checked:false,disabled:false,required:false,readOnly:false,hidden:false,textContent:'',innerHTML:'',dataset:{},classList:{add:value=>classes.add(value),remove:value=>classes.delete(value),contains:value=>classes.has(value)},closest(){return this.label??=(node());},...extra};}
function pool(extra={}){return {id:D,date:D,totalMg:20000,totalAmount:1720000,averageRate:86000,remainingMg:20000,usedMg:0,revision:'synthetic-pool-v1',purchases:[{id:'p1',payer:'owner',amount:850000,mg:10000},{id:'p2',payer:'assistant',amount:870000,mg:10000}],usages:[],...extra};}
function harness(){
const nodes=new Map(),saved=new Map(),posts=[],user={id:'lock-pool-owner',name:'麦麦',role:'owner',member:'owner'},context=vm.createContext({LedgerCalc:Calc,crypto:{randomUUID},URLSearchParams,setInterval(){},setTimeout(){},clearTimeout(){},console,document:{querySelector:selector=>nodes.get(selector)||null,querySelectorAll:()=>[],addEventListener(){}},window:{scrollTo(){}},localStorage:{getItem:key=>saved.get(key)||null,setItem:(key,value)=>saved.set(key,String(value)),removeItem:key=>saved.delete(key)},sessionStorage:{getItem(){return null;},setItem(){}},__user:user,__posts:posts});
const run=code=>vm.runInContext(code,context),json=code=>JSON.parse(JSON.stringify(run(code)));
for(const file of ['price-locks-ui.js','material-pools-ui.js','order-changes-ui.js','app.js'])run(fs.readFileSync(require.resolve('../public/'+file),'utf8').replace(/\ninit\(\);\s*$/,''));
run(`session={user:__user};state={user:__user,today:'${D}',pockets:['现货','金料'],accounts:['麦麦微信']};tab='create';readPaymentAccount=()=> '麦麦微信';readCreditCardPayer=()=> 'owner';syncPaymentRecipient=()=>{};syncCreditCardPreview=()=>0;finishPriceLockSave=async()=>{};mutate=async(url,data)=>{__posts.push({url,data});return {id:'synthetic-lock'};};`);
for(const selector of ['#main','#price-lock-error','#lock-create-total','#lock-sale-estimate','#lock-material-estimate','#lock-pool-material-estimate','#lock-pool-material-note','#lock-pool-material-payers'])nodes.set(selector,node());
const fields=Object.fromEntries(Object.entries({date:D,customer:'合成客户',salesperson:'合成开单人',name:'足金999',quantity:'12',goldPrice:'1000',laborRate:'0',laborMode:'gram',pieces:'1',discount:'0',note:'',received_amount:'1000',material_source:'manual',material_rate:'855',material_payer:'assistant2',material_pool_date:'',material_pool_rate:''}).map(([name,value])=>[name,node({value})]));
fields.payment_verified=node({checked:true});fields.material_verified=node({checked:true});
const form=node({id:'price-lock-create-form',querySelector(selector){return fields[selector.match(/\[name="([^"]+)"\]/)?.[1]]||null;},querySelectorAll:()=>[]});
const manual=node({querySelectorAll:()=>['material_rate','material_payer','material_verified'].map(name=>fields[name])}),poolRoot=node();nodes.set('#price-lock-create-form',form);nodes.set('#lock-manual-material',manual);nodes.set('#lock-pool-material',poolRoot);
return {nodes,saved,posts,context,run,json,fields,form,manual,poolRoot,use(value=pool()){context.__pool=value;run('materialPoolsCache={rolling:{enabled:true,cutover:state.today},current:__pool,rows:[__pool]};materialPoolsCacheUser=state.user.id;priceLockPoolError="";');}};
}
function lock(extra={}){return {id:'synthetic-lock',date:D,locked_mg:1000,buy_rate:90667,buy_payer:'owner',material_source:'pool',material_pool_id:D,material_amount:90666,sell_rate:100000,netReceived:100000,status:'pending',credit_card_fees:[],materialPool:{poolId:D,date:D,quantity:1000,amount:90666,averageRate:90667,basisAmount:272000,basisMg:3000,prefixMg:1000,prefixAmount:90667,allocations:[{payer:'owner',amount:40000},{payer:'assistant',amount:50666}],frozen:false},...extra};}
test('原锁来源默认手动,标签清楚区分实际付款与已有料池',()=>{
const h=harness(),html=h.run('priceLockCreateMaterialHTML({})');
assert.match(html,/<option value="manual" selected>手动填写料价/);assert.match(html,/<option value="pool" >当日加权料价/);
assert.match(html,/name="material_rate"/);assert.match(html,/name="material_payer"/);assert.match(html,/已核实原锁金料的实际付款/);assert.match(html,/保存锁价不再登记料费付款/);
});
test('切至料池禁用隐藏手动付款,切回保留料价、付款人和核实,草稿可恢复',()=>{
const h=harness();h.use();h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-material-estimate').textContent,'¥10,260.00');
h.fields.material_source.value='pool';h.run('syncPriceLockCreate()');
assert.equal(h.manual.hidden,true);assert.equal(h.poolRoot.hidden,false);for(const name of ['material_rate','material_payer','material_verified']){assert.equal(h.fields[name].disabled,true);assert.equal(h.fields[name].required,false);}
assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'¥10,320.00');assert.match(h.nodes.get('#lock-pool-material-payers').innerHTML,/麦麦.*8,500\.00.*助理.*1,820\.00/);
const data=h.json('collectPriceLockCreate()');assert.deepEqual(data.material,{source:'pool',poolId:D,revision:'synthetic-pool-v1'});assert.equal(Object.hasOwn(data.material,'payer'),false);assert.equal(Object.hasOwn(data.material,'verified'),false);
const draft=JSON.parse(h.saved.get('mm-price-lock-draft-lock-pool-owner'));assert.deepEqual(draft.material.manual,{rate:'855',payer:'assistant2',verified:true});
const restored=h.run('priceLockCreateMaterialHTML('+JSON.stringify(draft.material)+')');assert.match(restored,/name="material_rate" value="855"/);assert.match(restored,/<option value="assistant2" selected>/);
h.fields.material_source.value='manual';h.run('syncPriceLockCreate()');assert.equal(h.manual.hidden,false);assert.equal(h.fields.material_rate.value,'855');assert.equal(h.fields.material_payer.value,'assistant2');assert.equal(h.fields.material_verified.checked,true);assert.equal(h.fields.material_verified.required,true);
});
test('每日料池预览包括匿名锁单占用,修改重量即时按最新可用量和FIFO资金归属计算',()=>{
const h=harness();h.use(pool({usedMg:4000,remainingMg:16000,usages:[{kind:'priceLock',anonymous:true,mg:4000,active:1,fifo_sequence:1,created:D+'T00:00:00Z'}]}));h.fields.material_source.value='pool';
h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'¥10,320.00');assert.match(h.nodes.get('#lock-pool-material-payers').innerHTML,/5,060\.00.*5,260\.00/);assert.match(h.nodes.get('#lock-pool-material-note').textContent,/可用 16\.000g/);
h.fields.quantity.value='17';h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');assert.equal(h.nodes.get('#lock-pool-material-payers').innerHTML,'');assert.match(h.nodes.get('#lock-pool-material-note').textContent,/还缺 1\.000g/);assert.equal(h.poolRoot.dataset.ready,'false');
h.fields.quantity.value='1';h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'¥860.00');assert.match(h.nodes.get('#lock-pool-material-payers').innerHTML,/麦麦.*860\.00/);
});
test('无池、成本缺失、过往日期与读取失败不能显示零成本或沿用旧预览',async()=>{
const h=harness();h.fields.material_source.value='pool';
for(const [value,message] of [[pool({totalMg:0,totalAmount:0}),/尚无可用材料/],[pool({totalAmount:null}),/成本尚未补齐/]]){h.use(value);h.run('syncPriceLockCreate()');assert.match(h.nodes.get('#lock-pool-material-note').textContent,message);assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');await assert.rejects(h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))'),message);}
h.use();h.fields.date.value=OLD;h.run('syncPriceLockCreate()');assert.equal(h.fields.material_pool_date.value,OLD);assert.match(h.nodes.get('#lock-pool-material-note').textContent,/只支持今天锁价/);assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');
h.fields.date.value=D;h.run('priceLockPoolError="每日料池尚未读到:合成读取失败";syncPriceLockCreate()');assert.match(h.nodes.get('#lock-pool-material-note').textContent,/合成读取失败/);assert.equal(h.poolRoot.dataset.revision,'');assert.equal(h.posts.length,0);
});
test('未启用统一料池明确提示并阻止料池锁价,手动实际付款仍可保存',async()=>{
const h=harness();h.use();h.run('materialPoolsCache.rolling={enabled:false}');h.fields.material_source.value='pool';h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-note').textContent,'请先启用统一料池,再选择当日加权料价。');assert.equal(h.poolRoot.dataset.ready,'false');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');await assert.rejects(h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))'),/请先启用统一料池,再选择当日加权料价/);assert.equal(h.posts.length,0);
h.fields.quantity.value='';h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-note').textContent,'请先启用统一料池,再选择当日加权料价。');h.fields.quantity.value='12';h.fields.material_source.value='manual';await h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))');assert.deepEqual(JSON.parse(JSON.stringify(h.posts[0].data.material)),{rate:'855',payer:'assistant2',verified:true});
});
test('池满不足不提交,足额料池只传自动来源与版本,手填仍传原实际付款',async()=>{
const h=harness();h.use();h.fields.material_source.value='pool';h.fields.quantity.value='20.001';await assert.rejects(h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))'),/还缺 0\.001g/);assert.equal(h.posts.length,0);
h.fields.quantity.value='12';h.fields.material_verified.checked=false;await h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))');assert.deepEqual(JSON.parse(JSON.stringify(h.posts[0].data.material)),{source:'pool',poolId:D,revision:'synthetic-pool-v1'});
h.fields.material_source.value='manual';await assert.rejects(h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))'),/核实.*料费实际付款/);h.fields.material_verified.checked=true;await h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))');assert.deepEqual(JSON.parse(JSON.stringify(h.posts[1].data.material)),{rate:'855',payer:'assistant2',verified:true});
});
test('料池异步读完按表单现有日期与重量重算,已离开原表单不会被旧响应改写',async()=>{
const h=harness();let resolve;h.context.__deferred=new Promise(yes=>{resolve=yes;});h.run('readMaterialPools=async()=>{await __deferred;materialPoolsCache={rolling:{enabled:true,cutover:state.today},current:__pool,rows:[__pool]};materialPoolsCacheUser=state.user.id;};');h.context.__pool=pool();h.fields.material_source.value='pool';
const read=h.run('loadPriceLockPoolChoices(true)');h.fields.quantity.value='1';h.fields.date.value=OLD;resolve();await read;assert.match(h.nodes.get('#lock-pool-material-note').textContent,/只支持今天锁价/);assert.equal(h.fields.material_pool_date.value,OLD);assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');
h.fields.date.value=D;let release;h.context.__deferred=new Promise(yes=>{release=yes;});const stale=h.run('loadPriceLockPoolChoices(true)');h.nodes.delete('#price-lock-create-form');h.nodes.get('#lock-pool-material-note').textContent='已离开原表单';release();await stale;assert.equal(h.nodes.get('#lock-pool-material-note').textContent,'已离开原表单');
});
test('切换账号后迟到的读取失败不能污染下一账号的料池错误状态',async()=>{
const h=harness();let reject;h.context.__deferred=new Promise((yes,no)=>{reject=no;});h.run('readMaterialPools=async()=>await __deferred');const read=h.run('loadPriceLockPoolChoices(true)');h.run('state.user={id:"next-account",role:"assistant",member:"assistant"}');reject(new Error('前一账号合成读取失败'));await read;assert.equal(h.run('priceLockPoolError'),'');
});
test('原料池精确累计分币保留前序尾差,少重按快照回池、多重只新增手填补料',()=>{
const h=harness();h.context.__lock=lock();
const unchanged=h.json('priceLockDeliveryCost(__lock,"1","")');assert.equal(unchanged.materialCost,90666);assert.equal(unchanged.leftoverCost,0);
const less=h.json('priceLockDeliveryCost(__lock,"0.5","")');assert.equal(less.originalUsedCost,45333);assert.equal(less.leftoverCost,45333);assert.deepEqual(less.allocations,[{payer:'owner',amount:40000},{payer:'assistant',amount:5333}]);assert.equal(less.leftoverMg,500);
const extra=h.json('priceLockDeliveryCost(__lock,"1.2","900")');assert.equal(extra.originalUsedCost,90666);assert.equal(extra.extraCost,18000);assert.equal(extra.materialCost,108666);assert.equal(extra.extraMg,200);
assert.throws(()=>h.run('priceLockDeliveryCost(__lock,"1.2","")'),/补重进货料价/);
const raw=JSON.stringify(h.context.__lock);h.run('priceLockDeliveryCost(__lock,"0.5","")');assert.equal(JSON.stringify(h.context.__lock),raw);
});
test('手动原料仍沿用旧每克算法,料池资料缺失不能用展示均价冒算',()=>{
const h=harness();h.context.__lock=lock({material_source:'manual',buy_rate:85000,material_amount:85000});const manual=h.json('priceLockDeliveryCost(__lock,"0.5","")');assert.equal(manual.originalUsedCost,42500);assert.equal(manual.leftoverCost,42500);
h.context.__lock=lock({materialPool:{amount:90666,averageRate:90667,allocations:[{payer:'owner',amount:90666}]}});assert.throws(()=>h.run('priceLockDeliveryCost(__lock,"0.5","")'),/未完整读到/);
});
test('锁价详情与列表来源文案保留多人、冻结信息,不能把buy_payer当作唯一付款人',()=>{
const h=harness();h.context.__lock=lock();let html=h.run('priceLockFacts(__lock)');assert.match(html,/当日加权料池/);assert.match(html,/麦麦 ¥400\.00;助理1 ¥506\.66/);assert.match(html,/当天补料继续加权/);assert.doesNotMatch(html,/麦麦支付,进货料价/);
h.context.__lock.materialPool.frozen=true;html=h.run('priceLockFacts(__lock)');assert.match(html,/已冻结锁价日成本/);assert.doesNotMatch(html,/当天补料继续加权/);
});
test('审批影响展示关联锁价的前后成本与多人归属,名称转义且缺来源阻止复核',()=>{
const h=harness(),before={materialAmount:860000,usedMaterialAmount:0,leftoverCost:0,allocations:[{payer:'owner',amount:850000},{payer:'assistant',amount:10000}]},after={materialAmount:870000,usedMaterialAmount:0,leftoverCost:0,allocations:[{payer:'owner',amount:850000},{payer:'assistant2',amount:20000}]};h.context.__related=[{id:'lock-related',date:D,number:'合成<锁单>',customer:'客户<script>',before,after}];
const html=h.run('relatedPriceLocksHTML(__related)');assert.match(html,/同时受影响的锁价单(1 张)/);assert.match(html,/8,600\.00/);assert.match(html,/8,700\.00/);assert.match(html,/助理2.*200\.00/);assert.match(html,/合成&lt;锁单&gt;.*客户&lt;script&gt;/);assert.doesNotMatch(html,/<script>/);
h.context.__related[0].after.allocations=[];assert.throws(()=>h.run('relatedPriceLocksHTML(__related)'),/成本影响未完整返回/);
});
test('销售详情把同一原锁料池的多人分摊合并一行,补重保留独立采购计算',()=>{
const h=harness();h.context.__rows=[{kind:'goods',component:'material',name:'料费成本',source:'商品 1 · 足金999 · 原锁料池',priceLockSource:'original',amount:40000,payer:'owner',calculation:{weighted:true,rate:90667,quantity:1000}},{kind:'goods',component:'material',name:'料费成本',source:'商品 1 · 足金999 · 原锁料池',priceLockSource:'original',amount:50666,payer:'assistant',calculation:{weighted:true,rate:90667,quantity:1000}},{kind:'goods',component:'material',name:'料费成本',source:'商品 1 · 足金999 · 补重采购',priceLockSource:'extra',amount:18000,payer:'assistant2',calculation:{rate:90000,quantity:200}}];
const html=h.run('LedgerCalc={...LedgerCalc,orderCosts:()=>({rows:__rows,goodsExcluded:false,total:{goodsMissing:0,goods:108666}})};orderCostsHTML({goodsCost:108666,directCost:0,corrections:[],expenses:[]})');
assert.equal((html.match(/<td>原锁料费/g)||[]).length,1);assert.equal((html.match(/耗用 1\.000g/g)||[]).length,1);assert.match(html,/麦麦 ¥400\.00<br>助理1 ¥506\.66/);assert.match(html,/0\.200g × 900\.00元\/克/);assert.match(html,/补重料费/);assert.doesNotMatch(html,/1\.000g ×/);
});
test('每日料池明细为锁价提供独立入口,助理只看可见锁单,付款来源缺失不冒充零',()=>{
const h=harness();h.context.__pool=pool({settlement:{legacyReadOnly:true},usages:[{kind:'priceLock',date:D,price_lock_id:'own-lock',member:'assistant',number:'合成可见锁价',customer:'合成客户',product:'足金999',active:1,mg:12000,amount:1032000,allocations:[{payer:'owner',amount:850000},{payer:'assistant',amount:182000}]},{kind:'priceLock',anonymous:true,active:1,mg:1000,amount:86000},{kind:'priceLock',date:D,price_lock_id:'other-lock',member:'assistant2',number:'不应展示他人锁价',active:1,mg:1000,amount:86000}]});
const html=h.run('state.user={id:"synthetic-assistant",role:"assistant",member:"assistant"};materialPoolDetailHTML(__pool)');assert.match(html,/data-action="open-price-lock" data-id="own-lock"/);assert.match(html,/锁价原料 · 足金999/);assert.match(html,/麦麦 ¥8,500\.00 · 助理1 ¥1,820\.00/);assert.doesNotMatch(html,/不应展示他人锁价|商品 NaN|data-id="undefined"|NaN/);assert.equal(h.run('materialPoolUsagePayersText({})'),'付款来源待补齐');
});
@@ -0,0 +1,66 @@
'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
const {Ledger,today,day,money,weight,text,fail,ACCOUNTS,ACTIVE_POCKETS}=require('../ledger'),{createUser}=require('../server');
const Rolling=require('../rolling-material-pools'),PriceLocks=require('../price-locks'),Calc=require('../public/calculations');
const D=today(),P=new Date(Date.parse(D+'T12:00:00Z')-86400000).toISOString().slice(0,10);
function fixture(t){
const l=new Ledger(':memory:');t.after(()=>l.close());const actors={};for(const member of ['owner','assistant','assistant2']){const role=member==='owner'?'owner':'assistant',name='合成'+member;actors[member]={id:createUser(l,name,role,'synthetic-pool-lock-password',member),name,role,member};}l.enableTeamMode();
const run=(data,fn,member='owner',key=randomUUID())=>l.scope(actors[member],()=>l.transact(key,actors[member],data,fn));
const env=date=>({day,money,weight,text,fail,accounts:ACCOUNTS,pockets:ACTIVE_POCKETS,selfPockets:ACTIVE_POCKETS,today:()=>date,now:()=>date+'T01:00:00.000Z',orderIdentity:(v,n,max)=>text(v,n,max),pick:(v,choices,n)=>choices.includes(v)?v:fail(n+'无效')});
const buy=(grams,total,payer='owner',date=D)=>{const input={date,grams,total,payer,note:'合成购料'};return run(input,()=>l.createMaterialPurchase(input,actors.owner));};
const enable=(date=D)=>{const e=env(date),p=Rolling.previewEnable(l,{date},actors.owner,e);return run({},()=>Rolling.enable(l,{date,revision:p.revision,verified:true},actors.owner,e));};
const lock=(grams='1.500',date=D,member='assistant')=>{const pool=l.materialPoolDetail(date),input={date,customer:'合成锁价私密客户',salesperson:'合成开单人',line:{name:'足金挂件',unit:'g',quantity:grams,goldPrice:'2000',laborRate:'0',laborMode:'gram'},material:{source:'pool',poolId:date,revision:pool.revision},payment:{amount:String(Number(grams)*2000),account:'助理微信',verified:true}};return run(input,()=>date===D?l.createPriceLock(input,actors[member]):Rolling.withHistorical(l,()=>PriceLocks.create(l,input,actors[member],env(date))),member);};
const deliver=(id,grams,extra={})=>{const lock=l.priceLockDetail(id),total=Calc.orderTotal([Math.round(Number(grams)*200000)],0,'yuan').total,diff=total-lock.netReceived,input={date:D,revision:lock.revision,verified:true,line:{quantity:grams,laborRate:'0',laborMode:'gram',payer:'assistant',costParts:{labor:'0',accessories:'0',other:'0'},costPayers:{material:'owner',labor:'assistant'}},discount:'0',inventory:{pocket:'现货',original:'stocked'},settlement:{amount:(Math.abs(diff)/100).toFixed(2),account:'助理微信',verified:true},fee_items:[],...extra};return run(input,()=>l.deliverPriceLock(id,input,actors.owner));};
const issue=(grams)=>{const input={date:D,customer:'合成普通客户',salesperson:'合成',payment_account:'助理微信',lines:[{name:'足金999',unit:'g',quantity:grams,pocket:'现货',payer:'owner',sale:String(Number(grams)*2000),costParts:{material:'',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'pool',poolId:D}}],fee_items:[]};return run(input,()=>l.issueOrder(input,actors.owner)).id;};
run({},()=>l.stock({date:P,kind:'opening',pocket:'现货',grams:'100',note:'合成库存'},actors.owner));
return {l,actors,run,env,buy,enable,lock,deliver,issue};
}
function facts(l){return JSON.stringify(l.rows("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").map(({name})=>[name,l.rows('SELECT * FROM "'+name+'" ORDER BY rowid')]));}
test('料池锁价真预留、沿FIFO多人付款归属,客户款之外无新增现金、利润或实物,普通单不会越过锁重',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');f.buy('1.2','1200');f.enable();const stock=f.l.rows('SELECT * FROM movements'),lock=f.lock(),d=f.l.priceLockDetail(lock.id),pool=f.l.materialPools().current;
assert.equal(d.material_source,'pool');assert.equal(d.material_amount,150000);assert.deepEqual(d.materialPool.allocations,[{payer:'assistant',amount:80000},{payer:'owner',amount:70000}]);assert.equal(pool.usedMg,1500);assert.equal(pool.remainingMg,500);assert.equal(d.material_events.length,0);
assert.equal(f.l.rows('SELECT * FROM orders').length,0);assert.equal(f.l.rows('SELECT * FROM journal').length,0);assert.deepEqual(f.l.rows('SELECT * FROM movements'),stock);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").length,0);
const id=f.issue('0.5');assert.equal(f.l.detail(id).goodsCost,50000);assert.equal(f.l.materialPools().current.remainingMg,0);
const before=facts(f.l);f.l.priceLockDetail(lock.id);f.l.materialPools();assert.equal(facts(f.l),before);
});
test('同日少重交付只耗一次,随后补料同步原锁量、实际成本与利润,反向FIFO和分厘均守恒',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');f.buy('1.2','1200');f.enable();const lock=f.lock(),id=f.deliver(lock.id,'1.000').id;let p=f.l.materialPools().current;
assert.equal(p.usedMg,1000);assert.equal(p.remainingMg,1000);assert.equal(f.l.detail(id).goodsCost,100000);assert.deepEqual(f.l.rows("SELECT mg FROM movements WHERE kind='sale'").map(r=>r.mg),[-1000]);assert.equal(f.l.rows("SELECT * FROM movements WHERE kind='lock_purchase'").length,0);
f.buy('1','2000','assistant2');p=f.l.materialPools().current;const d=f.l.priceLockDetail(lock.id),o=f.l.detail(id);
assert.equal(d.material_amount,200000);assert.equal(o.goodsCost,133333);assert.equal(o.profit,66667);assert.equal(d.delivery.leftover_cost,66667);assert.equal(p.consumedCost,133333);assert.equal(p.remainingCost,266667);assert.equal(p.totalAmount,p.consumedCost+p.remainingCost);
assert.deepEqual(o.lines[0].materialAllocations.filter(a=>a.source==='original').map(a=>[a.payer,a.amount]),[['assistant',80000],['owner',53333]]);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").length,0);
});
test('锁价日跨天冻结,少重余料按原成本与付款来源回交付日池,未用原锁重不进入期初',t=>{
const f=fixture(t);f.buy('0.8','800','assistant',P);f.buy('1.2','1200','owner',P);f.enable(P);const lock=f.lock('1.500',P),old=f.l.priceLockDetail(lock.id);f.buy('1','3000');
assert.equal(f.l.priceLockDetail(lock.id).material_amount,old.material_amount);assert.equal(f.l.materialPools().current.opening.mg,500);assert.equal(f.l.materialPools().current.opening.amount,50000);
const id=f.deliver(lock.id,'0.500').id,p=f.l.materialPools().current;assert.equal(f.l.detail(id).goodsCost,50000);assert.equal(p.totalMg,2500);assert.equal(p.totalAmount,450000);assert.equal(p.usedMg,0);assert.equal(p.remainingMg,2500);assert.equal(f.l.priceLockDetail(lock.id).delivery.leftover_cost,100000);
const ret=f.l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?',lock.id);assert.equal(ret.length,1);assert.deepEqual(JSON.parse(ret[0].allocations),[{payer:'assistant',amount:30000},{payer:'owner',amount:70000}]);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").length,0);
});
test('采购删除造成锁价成本待补,拒绝交付并完整回滚,补料恢复成本和付款归属',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');const b=f.buy('1.2','1200');f.enable();const lock=f.lock();f.run({},()=>f.l.deleteMaterialPurchase(b.id,{revision:1},f.actors.owner));
assert.equal(f.l.priceLockDetail(lock.id).materialPool.amount,null);const before=facts(f.l);assert.throws(()=>f.deliver(lock.id,'1.5'),/成本待补/);assert.equal(facts(f.l),before);
f.buy('1.2','2400','assistant2');assert.equal(f.l.priceLockDetail(lock.id).material_amount,240000);assert.equal(f.deliver(lock.id,'1.5').status,'delivered');
});
test('已交付池锁整单退货回池与料费往来冲回,原现金支出不重复',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');f.buy('1.2','1200');f.enable();const lock=f.lock(),id=f.deliver(lock.id,'1').id;
f.run({},()=>f.l.action(id,'return',{date:D,verified:true,reason:'合成实物退回',returnPockets:['金料']},f.actors.owner));const p=f.l.materialPools().current;
assert.equal(p.usedMg,0);assert.equal(p.remainingMg,2000);assert.equal(p.remainingCost,200000);assert.equal(f.l.detail(id).profit,0);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").length,0);
const entries=f.l.rows("SELECT * FROM team_fund_entries WHERE source_kind='price_lock' AND source_id=? AND kind IN ('material_usage','material_return')",lock.id);assert.equal(entries.reduce((n,r)=>n+(r.from_member==='assistant'?r.amount:-r.amount),0),0);
});
test('历史采购更正先试算回滚,批准重算锁价、交付、余料和下游且留存实际流水',t=>{
const f=fixture(t),first=f.buy('0.8','800','assistant',P);f.buy('1.2','1200','owner',P);f.enable(P);const lock=f.lock('1.500',P),delivered=f.deliver(lock.id,'0.500').id,next=f.issue('1.000'),flows={movements:f.l.rows('SELECT * FROM movements'),payments:f.l.rows('SELECT * FROM payments'),events:f.l.rows('SELECT * FROM price_lock_events')};
const before={reservation:f.l.rows('SELECT * FROM price_lock_pool_reservations'),returns:f.l.rows('SELECT * FROM price_lock_pool_returns'),orders:f.l.rows('SELECT * FROM orders'),days:f.l.rows('SELECT * FROM material_rolling_days')},input={action:'edit',revision:1,date:P,grams:'0.8',total:'1600',payer:'assistant',note:'合成核实旧采购',reason:'合成历史更正',verified:true};
assert.throws(()=>f.l.editMaterialPurchase(first.id,input,f.actors.owner),/冻结/);
const request=f.run(input,()=>f.l.requestMaterialPurchaseChange(first.id,input,f.actors.owner));assert.equal(request.preview.relatedPriceLocks[0].id,lock.id);assert.deepEqual(f.l.rows('SELECT * FROM price_lock_pool_reservations'),before.reservation);assert.deepEqual(f.l.rows('SELECT * FROM price_lock_pool_returns'),before.returns);assert.deepEqual(f.l.rows('SELECT * FROM orders'),before.orders);assert.deepEqual(f.l.rows('SELECT * FROM material_rolling_days'),before.days);
f.run({},()=>f.l.approveMaterialPurchaseChange(request.id,{revision:1,verified:true},f.actors.owner));const d=f.l.priceLockDetail(lock.id),pool=f.l.materialPools().current;
assert.equal(d.material_amount,210000);assert.equal(f.l.detail(delivered).goodsCost,70000);assert.equal(d.delivery.leftover_cost,140000);assert.equal(pool.totalMg,1500);assert.equal(pool.totalAmount,210000);assert.equal(f.l.detail(next).goodsCost,140000);assert.equal(pool.remainingCost,70000);
assert.deepEqual(f.l.rows('SELECT * FROM movements'),flows.movements);assert.deepEqual(f.l.rows('SELECT * FROM payments'),flows.payments);assert.deepEqual(f.l.rows('SELECT * FROM price_lock_events'),flows.events);assert.equal(f.l.one('PRAGMA integrity_check').integrity_check,'ok');assert.equal(f.l.rows('PRAGMA foreign_key_check').length,0);
});
test('补重保留手动实际购料,原料池不再扣重或造采购,退货只记非现金回料',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');f.buy('1.2','1200');f.enable();const lock=f.lock('1.500'),id=f.deliver(lock.id,'1.700',{extraMaterial:{rate:'1200',payer:'assistant2',verified:true},inventory:{pocket:'现货',original:'stocked',extra:'receive'}}).id,o=f.l.detail(id);
assert.equal(o.goodsCost,174000);assert.equal(f.l.materialPools().current.usedMg,1500);assert.deepEqual(f.l.rows('SELECT mg FROM movements WHERE order_id=? ORDER BY rowid',id).map(r=>r.mg),[200,-1700]);assert.deepEqual(f.l.priceLockDetail(lock.id).material_events.map(r=>[r.source,r.amount,r.payer]),[['extra',24000,'assistant2']]);
f.run({},()=>f.l.action(id,'return',{date:D,verified:true,reason:'合成补重退回',returnPockets:['金料']},f.actors.owner));const p=f.l.materialPools().current;assert.equal(p.remainingMg,2200);assert.equal(p.remainingCost,224000);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").reduce((n,r)=>n+r.amount,0),24000);
});
test('料池必须显式选择且启用统一结转,无料、旧日期、过期版本及重复入库被拒绝',t=>{
const f=fixture(t);f.buy('2','2000');const before=facts(f.l);assert.throws(()=>f.lock(),/启用统一/);assert.equal(facts(f.l),before);f.enable();const lock=f.lock(),snapshot=facts(f.l);assert.throws(()=>f.deliver(lock.id,'1.5',{inventory:{pocket:'现货',original:'receive'}}),/不能重复入库/);assert.equal(facts(f.l),snapshot);
});