新增锁价与每日购料管理
支持锁价交付、每日加权成本、购料修改与软删除,完善付款归属、结算及利润重算。 244项测试和隔离浏览器验收通过;记录尚未实施的剩料跨日结转与当天资金结清需求。
This commit is contained in:
1 parent
42d75a4968
commit
20bf6e7d24
23 files changed
+2330
-101
No files matched your search
@@ -0,0 +1,157 @@
|
||||
'use strict';
|
||||
// 锁价采购和客户现金只追加;交付才生成销售、消耗成本和库存流水。
|
||||
const {randomUUID}=require('node:crypto');
|
||||
const Calc=require('./public/calculations');
|
||||
const yuan=value=>(value/100).toFixed(2),grams=value=>(value/1000).toFixed(3);
|
||||
function initialize(ledger){
|
||||
ledger.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS price_locks(
|
||||
id TEXT PRIMARY KEY,number TEXT UNIQUE NOT NULL,date TEXT NOT NULL,customer TEXT NOT NULL,salesperson TEXT NOT NULL,note TEXT NOT NULL,
|
||||
line TEXT NOT NULL,locked_mg INTEGER NOT NULL,sell_rate INTEGER NOT NULL,buy_rate INTEGER NOT NULL,buy_payer TEXT NOT NULL,
|
||||
material_amount INTEGER NOT NULL,estimated_total INTEGER NOT NULL,discount INTEGER NOT NULL,
|
||||
status TEXT NOT NULL CHECK(status IN ('pending','delivered')),revision INTEGER NOT NULL,
|
||||
final_order_id TEXT UNIQUE REFERENCES orders(id),delivery TEXT,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS price_lock_events(
|
||||
id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),date TEXT NOT NULL,
|
||||
kind TEXT NOT NULL CHECK(kind IN ('receipt','refund','material')),amount INTEGER NOT NULL CHECK(amount>=0),
|
||||
account TEXT,payer TEXT,source TEXT,quantity INTEGER,rate INTEGER,number TEXT NOT NULL,customer TEXT NOT NULL,product TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,created TEXT NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS ix_price_lock_events_date ON price_lock_events(date,created,id);
|
||||
CREATE INDEX IF NOT EXISTS ix_price_locks_status ON price_locks(status,date);
|
||||
`);
|
||||
}
|
||||
function atomic(ledger,fn){
|
||||
ledger.db.exec('SAVEPOINT price_lock_action');
|
||||
try{const result=fn();ledger.db.exec('RELEASE price_lock_action');return result;}
|
||||
catch(error){ledger.db.exec('ROLLBACK TO price_lock_action');ledger.db.exec('RELEASE price_lock_action');throw error;}
|
||||
}
|
||||
function raw(ledger,id,env){
|
||||
const row=ledger.one('SELECT * FROM price_locks WHERE id=?',id);if(!row)env.fail('锁价单不存在',404);
|
||||
return {...row,kind:'priceLock',line:JSON.parse(row.line),delivery:row.delivery?JSON.parse(row.delivery):null};
|
||||
}
|
||||
function detail(ledger,id,env){
|
||||
const row=raw(ledger,id,env),events=ledger.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY date,created,rowid',id);
|
||||
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);
|
||||
return {...row,cash_events,material_events,received,refunded,netReceived:received-refunded};
|
||||
}
|
||||
function list(ledger,query,env){
|
||||
const date=env.day(query.date??query.to??env.today()),from=env.day(query.from??(query.date||query.to?date:'2000-01-01'));
|
||||
if(from>date)env.fail('开始日期不能晚于结束日期');
|
||||
const status=query.status??'all';env.pick(status,['all','pending','delivered'],'锁价状态');
|
||||
const rows=ledger.rows('SELECT id FROM price_locks WHERE date>=? AND date<=?'+(status==='all'?'':' AND status=?')+' ORDER BY created,rowid',from,date,...(status==='all'?[]:[status])).map(({id})=>detail(ledger,id,env));
|
||||
const counts={pending:0,delivered:0};for(const row of ledger.rows('SELECT status,COUNT(*) AS count FROM price_locks GROUP BY status'))counts[row.status]=row.count;
|
||||
return {from,date,rows,counts};
|
||||
}
|
||||
function event(ledger,lock,values,actor,env){
|
||||
const id=randomUUID();
|
||||
ledger.run('INSERT INTO price_lock_events(id,price_lock_id,date,kind,amount,account,payer,source,quantity,rate,number,customer,product,actor,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
||||
id,lock.id,values.date,values.kind,values.amount,values.account??null,values.payer??null,values.source??null,values.quantity??null,values.rate??null,
|
||||
lock.number,lock.customer,lock.line.name,actor.name,env.now());
|
||||
return id;
|
||||
}
|
||||
function customerNote(lock,value,env){
|
||||
const note=env.text(value===undefined?lock.note:value,'客户单备注',240,true);
|
||||
const remark=`锁价单 ${lock.number};按原锁定金价 ${yuan(lock.sell_rate)}元/克结算`;
|
||||
const final=[note,remark].filter(Boolean).join(';');
|
||||
if(final.length>240)env.fail(`客户备注请控制在${240-remark.length-1}字以内,需为锁价说明预留位置`);
|
||||
return final;
|
||||
}
|
||||
function create(ledger,input,actor,env){return atomic(ledger,()=>{
|
||||
if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号开锁价单',403);
|
||||
if(input.line?.costMaterial?.mode==='pool'||input.line?.materialPool!==undefined)env.fail('锁价单使用独立采购料费,不能关联日料池');
|
||||
if(input.lines!==undefined||!input.line||typeof input.line!=='object'||Array.isArray(input.line))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);
|
||||
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,'原进货料价');
|
||||
if(quantity<=0||sellRate<=0||buyRate<=0)env.fail('锁定克重、销售金价和进货料价必须大于0');
|
||||
const payer=env.pick(input.material?.payer,['owner','assistant'],'原料付款人');
|
||||
if(input.material?.verified!==true)env.fail('请确认原料款已实际支付');
|
||||
if(input.payment?.verified!==true)env.fail('请核实客户实际付款');
|
||||
const received=env.money(input.payment.amount,'客户实际付款'),account=env.pick(input.payment.account,env.accounts,'实际收款账户');
|
||||
const costs=Calc.priceLockCost({lockedQuantity:input.line.quantity,quantity:input.line.quantity,buyRate:input.material.rate});
|
||||
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];
|
||||
const discount=env.money(input.discount??'0','整单优惠'),estimated=Calc.orderTotal([line.sale],discount,'yuan');
|
||||
const id=randomUUID(),number='SJ'+date.replaceAll('-','')+'-'+id.slice(0,8).toUpperCase(),timestamp=env.now();
|
||||
const customer=env.text(input.customer,'客户称呼',60),salesperson=env.text(input.salesperson||actor.name,'开单人',30),note=env.text(input.note,'客户单备注',240,true);
|
||||
customerNote({number,sell_rate:sellRate,note},undefined,env);
|
||||
ledger.run('INSERT INTO price_locks(id,number,date,customer,salesperson,note,line,locked_mg,sell_rate,buy_rate,buy_payer,material_amount,estimated_total,discount,status,revision,actor,created,updated) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
|
||||
id,number,date,customer,salesperson,note,JSON.stringify(line),quantity,sellRate,buyRate,payer,costs.originalPurchase,estimated.total,discount,'pending',1,actor.name,timestamp,timestamp);
|
||||
const lock={id,number,customer,line};
|
||||
if(received>0)event(ledger,lock,{date,kind:'receipt',amount:received,account},actor,env);
|
||||
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.audit('price-lock:'+id,'创建锁价单',actor,{number,date,quantity,sellRate,buyRate,materialPayer:payer,materialAmount:costs.originalPurchase,received,account,revision:1});
|
||||
return {id,price_lock_id:id,status:'pending',revision:1};
|
||||
});}
|
||||
function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
|
||||
if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号交付锁价单',403);
|
||||
if(input.line?.costMaterial?.mode==='pool'||input.line?.materialPool!==undefined)env.fail('锁价单使用独立采购料费,不能关联日料池');
|
||||
const lock=detail(ledger,id,env);
|
||||
if(lock.status!=='pending'||lock.final_order_id)env.fail('这张锁价单已交付,不能重复生成销售单',409);
|
||||
if(!Number.isSafeInteger(input.revision)||input.revision!==lock.revision)env.fail('锁价单已更新,请刷新后再操作',409);
|
||||
if(input.verified!==true)env.fail('请核对实物、实际成本及客户补退款后确认交付');
|
||||
const date=env.day(input.date,lock.date),lineInput=input.line;
|
||||
if(input.lines!==undefined||!lineInput||typeof lineInput!=='object'||Array.isArray(lineInput))env.fail('请填写一件锁价黄金的实际交付信息');
|
||||
if(lineInput.goldPrice!==undefined&&env.money(lineInput.goldPrice,'销售金价')!==lock.sell_rate)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 pocket=env.pick(input.inventory?.pocket,env.pockets,'交付货盘'),originalStock=env.pick(input.inventory?.original,['receive','stocked'],'原锁定黄金库存来源');
|
||||
let extraStock=null,extraPayer=null,extraRate=null;
|
||||
if(costs.extraMg){
|
||||
extraStock=env.pick(input.inventory?.extra,['receive','stocked'],'补重黄金库存来源');extraPayer=env.pick(input.extraMaterial?.payer,['owner','assistant'],'补重料费付款人');
|
||||
extraRate=env.money(input.extraMaterial.rate,'补重进货料价');if(input.extraMaterial?.verified!==true)env.fail('请确认补重原料款已实际支付');
|
||||
}
|
||||
const discount=env.money(input.discount??'0','整单优惠');
|
||||
const payers=Calc.costPayers(lineInput.costPayers);
|
||||
if(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),
|
||||
costParts:{...lineInput.costParts,material:yuan(costs.materialCost)},costMaterial:{mode:'total'},
|
||||
costPayers:{material:lock.buy_payer,labor:payers?.labor??lineInput.payer}};
|
||||
const lines=ledger.validateLines([actualLine]);
|
||||
const fees=ledger.validateFees((input.fee_items??[]).map(fee=>({...fee,status:'estimated'})));
|
||||
ledger.validateCompletedCosts(lines,fees);
|
||||
const total=Calc.orderTotal(lines.map(line=>line.sale),discount,'yuan').total,difference=total-lock.netReceived;
|
||||
let settlementAccount=lock.cash_events.find(event=>event.kind==='receipt')?.account??'助理微信';
|
||||
if(difference){
|
||||
if(input.settlement?.verified!==true)env.fail('请确认客户补款或退款已经实际完成');
|
||||
const amount=env.money(input.settlement.amount,'实际补退款金额');if(amount!==Math.abs(difference))env.fail('实际补退款金额须与最终成交差额一致');
|
||||
settlementAccount=env.pick(input.settlement.account,env.accounts,'实际补退款账户');
|
||||
}else if(input.settlement?.amount!==undefined&&env.money(input.settlement.amount,'实际补退款金额')!==0)env.fail('本单无需补退款,不能重复记收款');
|
||||
const note=customerNote(lock,input.note,env);
|
||||
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};
|
||||
const finalId=ledger.saveOrder(normal,actor).id;
|
||||
const allocations=[{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});
|
||||
const storedLine=ledger.rawOrder(finalId).lines[0];storedLine.materialAllocations=allocations;
|
||||
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);
|
||||
if(difference)event(ledger,lock,{date,kind:difference>0?'receipt':'refund',amount:Math.abs(difference),account:settlementAccount},actor,env);
|
||||
if(costs.extraMg)event(ledger,lock,{date,kind:'material',source:'extra',amount:costs.extraCost,payer:extraPayer,quantity:costs.extraMg,rate:extraRate},actor,env);
|
||||
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(extraStock==='receive')ledger.move({group,order:finalId,date,pocket,mg:costs.extraMg,kind:'lock_purchase',note:lock.number+' 补重黄金入库',cost:costs.extraCost},actor);
|
||||
ledger.action(finalId,'confirm',{date},actor);
|
||||
ledger.action(finalId,'complete',{date,verified:true},actor);
|
||||
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}:{})}};
|
||||
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});
|
||||
return {id:finalId,order_id:finalId,price_lock_id:id,status:'delivered',revision:lock.revision+1};
|
||||
});}
|
||||
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);
|
||||
}
|
||||
function reporting(ledger,query,env){
|
||||
const to=env.day(query.to??query.date??env.today()),from=env.day(query.from??to);if(from>to)env.fail('开始日期不能晚于结束日期');
|
||||
const rows=ledger.rows('SELECT * FROM price_lock_events WHERE date>=? AND date<=? ORDER BY date,created,rowid',from,to);
|
||||
const customerCash=rows.filter(event=>event.kind!=='material').map(({payer,source,quantity,rate,...event})=>event);
|
||||
const materialOutlays=rows.filter(event=>event.kind==='material').map(({account,...event})=>({...event,component:'material'}));
|
||||
const directOutlays=ledger.rows("SELECT e.*,l.id AS price_lock_id,l.number,l.customer FROM expenses e JOIN price_locks l ON l.final_order_id=e.order_id WHERE e.date>=? AND e.date<=? ORDER BY e.date,e.created,e.rowid",from,to)
|
||||
.map(row=>({...row,kind:'fee',component:'fee',product:JSON.parse(ledger.one('SELECT line FROM price_locks WHERE id=?',row.price_lock_id).line).name}));
|
||||
return {from,to,customerCash,materialOutlays,directOutlays};
|
||||
}
|
||||
module.exports={initialize,create,deliver,detail,list,inheritedPayments,reporting};
|
||||
Reference in new issue
Block a user