保存同行基础版:店铺配置与员工管理

This commit is contained in:
summer committed 2026-11-14 01:16:35 +08:00
1 parent ecb8d6dec0
commit b7b987064b
84 files changed
+1884 -573

No files matched your search

+20 -14
View File
@@ -3,9 +3,11 @@
const {randomUUID}=require('node:crypto');
const Calc=require('./public/calculations');
const CreditCardFees=require('./public/credit-card-fees');
const CreditCardRates=require('./credit-card-rates');
const TeamMembers=require('./team-members');
const LockPools=require('./price-lock-pools'),MaterialPools=require('./material-pools'),Rolling=require('./rolling-material-pools'),LockLines=require('./price-lock-lines');
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 cardFeeNote=event=>event.card_fee_note||(event.card_fee_rate!==null&&event.card_fee_rate!==undefined?CreditCardFees.note(event.card_fee_rate):'已记录信用卡手续费');
const paymentAccount=(value,env,options)=>env.paymentAccount?env.paymentAccount(value,options):env.pick(CreditCardFees.normalizeAccount(value),env.accounts,'实际收付款账户');
const yuan=value=>(value/100).toFixed(2),grams=value=>(value/1000).toFixed(3);
function initialize(ledger){
ledger.db.exec(`
@@ -49,11 +51,11 @@ function detail(ledger,id,env){
const row=raw(ledger,id,env),allEvents=ledger.rows('SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY date,created,rowid',id),events=allEvents.filter(event=>!event.voided);
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 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!==null?{rate_permille:event.card_fee_rate}:{}),...(event.card_fee_expense_id?{expense_id:event.card_fee_expense_id}:{})}));
const reservations=LockPools.findAll(ledger,id),byIndex=new Map(reservations.map(r=>[r.line_index,r]));
const lines=row.lines.map(item=>{const reservation=byIndex.get(item.line_index);return {...item,material_source:reservation?'pool':'manual',...(reservation?{material_amount:reservation.snapshot.amount??null,buy_rate:reservation.snapshot.averageRate??null,material_pool_id:reservation.pool_id,materialPool:LockPools.detail(ledger,id,env,item.line_index)}:{}),delivery:LockLines.deliveryAt(row,item.line_index)};});
const material_source=reservations.length===0?'manual':reservations.length===lines.length?'pool':'mixed',material_amount=lines.some(line=>line.material_amount===null)?null:lines.reduce((sum,line)=>sum+line.material_amount,0);
return {...row,lines,line:lines[0].line,locked_mg:lines.reduce((sum,line)=>sum+line.locked_mg,0),buy_rate:lines[0].buy_rate,buy_payer:lines[0].buy_payer,material_source,material_amount,...(lines.length===1&&lines[0].materialPool?{material_pool_id:lines[0].material_pool_id,materialPool:lines[0].materialPool}:{}),cash_events,material_events,voided_events:allEvents.filter(event=>event.voided),received,refunded,netReceived:received-refunded,credit_card_fees,credit_card_fee_total:credit_card_fees.reduce((total,fee)=>total+fee.amount,0)};
return {...row,credit_card_rate_permille:CreditCardRates.read(ledger,'price_lock',id),lines,line:lines[0].line,locked_mg:lines.reduce((sum,line)=>sum+line.locked_mg,0),buy_rate:lines[0].buy_rate,buy_payer:lines[0].buy_payer,material_source,material_amount,...(lines.length===1&&lines[0].materialPool?{material_pool_id:lines[0].material_pool_id,materialPool:lines[0].materialPool}:{}),cash_events,material_events,voided_events:allEvents.filter(event=>event.voided),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){
const date=env.day(query.date??query.to??env.today()),from=env.day(query.from??(query.date||query.to?date:'2000-01-01'));
@@ -66,12 +68,13 @@ function list(ledger,query,env){
function event(ledger,lock,values,actor,env){
const id=randomUUID();
const card=values.kind==='receipt'&&values.amount>0&&values.account?.endsWith('信用卡');
const feeAmount=card?CreditCardFees.amount(values.amount):null,feePayer=card?env.pick(values.credit_card_fee_payer??'owner',['owner','assistant','assistant2'],'信用卡手续费付款人'):null;
const feeRate=card?CreditCardRates.read(ledger,'price_lock',lock.id):null;
const feeAmount=card?CreditCardFees.amount(values.amount,feeRate):null,feePayer=card?ledger.validateMember(values.credit_card_fee_payer??'owner','信用卡手续费付款人',{original:values.originalFeePayer}):null;
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?paymentAccount(values.account,env):null,values.payer??null,values.source??null,values.quantity??null,values.rate??null,
id,lock.id,values.date,values.kind,values.amount,values.account?paymentAccount(values.account,env,{original:values.originalAccount}):null,values.payer??null,values.source??null,values.quantity??null,values.rate??null,
lock.number,lock.customer,LockLines.product(lock,values.line_index??null),actor.name,env.now());
if(values.kind==='material')ledger.run('UPDATE price_lock_events SET line_index=? WHERE id=?',values.line_index??0,id);
if(card)ledger.run('UPDATE price_lock_events SET card_fee_amount=?,card_fee_payer=?,card_fee_rate=?,card_fee_note=? WHERE id=?',feeAmount,feePayer,CreditCardFees.ratePermille,CreditCardFees.note(),id);
if(card)ledger.run('UPDATE price_lock_events SET card_fee_amount=?,card_fee_payer=?,card_fee_rate=?,card_fee_note=? WHERE id=?',feeAmount,feePayer,feeRate,CreditCardFees.note(feeRate),id);
return id;
}
function reviseMaterial(ledger,lock,source,values,actor,env){
@@ -109,7 +112,7 @@ function creationLines(input,env){
}
function create(ledger,input,actor,env,options={}){return atomic(ledger,()=>{
if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号开锁价单',403);
const inputs=creationLines(input,env),date=env.day(input.date),member=ledger.selectedMember(input,actor),id=randomUUID();
const inputs=creationLines(input,env),date=env.day(input.date),member=ledger.selectedMember(input,actor,options.originalLock?.member??null),id=randomUUID();
let pool=null,poolMg=0;
const entries=inputs.map((item,index)=>{
if(!item||typeof item!=='object'||Array.isArray(item))env.fail('锁价商品信息无效');
@@ -127,22 +130,24 @@ function create(ledger,input,actor,env,options={}){return atomic(ledger,()=>{
}
const quantity=env.weight(item.quantity,'锁定克重'),sellRate=env.money(item.goldPrice,'锁定销售金价'),buyRate=source==='pool'?pool.eligibleAverageRate:env.money(material?.rate,'原进货料价');
if(quantity<=0||sellRate<=0||buyRate<=0)env.fail('锁定克重、销售金价和进货料价必须大于0');
const payer=source==='pool'?(pool.purchases[0]?.allocations?.[0]?.payer??pool.purchases[0]?.payer??'owner'):env.pick(material?.payer,['owner','assistant','assistant2'],'原料付款人');
const poolPayer=pool?.purchases[0]?.allocations?.[0]?.payer??pool?.purchases[0]?.payer??'owner';
const payer=source==='pool'?(TeamMembers.isActive(ledger,poolPayer)?poolPayer:member):ledger.validateMember(material?.payer,'原料付款人',{original:options.originalLock?.lines.find(row=>row.id===options.lineIds?.[index])?.buy_payer});
if(source==='manual'&&material?.verified!==true)env.fail('请确认原料款已实际支付');
const costs=Calc.priceLockCost({lockedQuantity:item.quantity,quantity:item.quantity,buyRate:yuan(buyRate)});
const line=ledger.validateLines([{...item,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}}],[],date,{member})[0];
const line=ledger.validateLines([{...item,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}}],options.originalLock?.lines.find(row=>row.id===options.lineIds?.[index])?[options.originalLock.lines.find(row=>row.id===options.lineIds?.[index]).line]:[],date,{member})[0];
if(source==='pool')poolMg+=quantity;
return {id:options.lineIds?.[index]??randomUUID(),line_index:index,line,locked_mg:quantity,sell_rate:sellRate,buy_rate:buyRate,buy_payer:payer,material_amount:costs.originalPurchase,material_source:source};
});
if(pool&&poolMg>pool.eligibleRemainingMg)env.fail('当日料池可用克重不足或成本待补,请先核实购料');
if(input.payment?.verified!==true)env.fail('请核实客户实际付款');
const received=env.money(input.payment.amount,'客户实际付款'),account=paymentAccount(input.payment.account,env),discount=env.money(input.discount??'0','整单优惠'),estimated=Calc.orderTotal(entries.map(item=>item.line.sale),discount,'yuan');
const received=env.money(input.payment.amount,'客户实际付款'),account=paymentAccount(input.payment.account,env,{original:options.originalLock?.cash_events.find(row=>row.kind==='receipt')?.account}),discount=env.money(input.discount??'0','整单优惠'),estimated=Calc.orderTotal(entries.map(item=>item.line.sale),discount,'yuan');
const number='SJ'+date.replaceAll('-','')+'-'+id.slice(0,8).toUpperCase(),timestamp=env.now(),customer=env.orderIdentity(input.customer,'客户称呼/代号',60),salesperson=env.orderIdentity(input.salesperson,'开单人',30),note=env.text(input.note,'客户单备注',240,true),first=entries[0];
customerNote({id,number,sell_rate:first.sell_rate,lines:entries,note},undefined,env);
ledger.run('INSERT INTO price_locks(id,number,date,customer,salesperson,note,line,lines,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(first.line),JSON.stringify(entries),entries.reduce((n,row)=>n+row.locked_mg,0),first.sell_rate,first.buy_rate,first.buy_payer,entries.reduce((n,row)=>n+row.material_amount,0),estimated.total,discount,'pending',1,actor.name,timestamp,timestamp);
CreditCardRates.capture(ledger,'price_lock',id,options.creditCardRatePermille??CreditCardRates.current(ledger));
ledger.assignMember('price_lock',id,member,{fresh:!options.temporary});
const lock={id,number,customer,lines:entries,line:first.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,originalFeePayer:options.originalLock?.credit_card_fees?.[0]?.payer,originalAccount:options.originalLock?.cash_events.find(row=>row.kind==='receipt')?.account},actor,env);
for(const entry of entries){
if(entry.material_source==='pool')LockPools.reserve(ledger,{id,locked_mg:entry.locked_mg,line_index:entry.line_index},pool,actor,env);
else event(ledger,lock,{date,kind:'material',source:'original',line_index:entry.line_index,amount:entry.material_amount,payer:entry.buy_payer,quantity:entry.locked_mg,rate:entry.buy_rate},actor,env);
@@ -178,12 +183,12 @@ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
const pocket=ledger.validatePocket(lineInput.inventory?.pocket,{name:'交付货盘'}),originalStock=env.pick(lineInput.inventory?.original,['receive','stocked'],'原锁定黄金库存来源');if(pooled&&originalStock!=='stocked')env.fail('料池锁价使用已有黄金,原锁料不能重复入库');
const stockCount=ledger.validateStockCount(pocket,lineInput.stockCount),countSource=ledger.pocket(pocket)?.countUnit==='pair'?env.pick(lineInput.inventory?.countSource,['receive','stocked'],'成品来源'):null;
let extraStock=null,extraPayer=null,extraRate=null;
if(costs.extraMg){extraStock=env.pick(lineInput.inventory?.extra,['receive','stocked'],'补重黄金库存来源');extraPayer=env.pick(lineInput.extraMaterial?.payer,['owner','assistant','assistant2'],'补重料费付款人');extraRate=env.money(lineInput.extraMaterial.rate,'补重进货料价');if(lineInput.extraMaterial?.verified!==true)env.fail('请确认补重原料款已实际支付');}
if(costs.extraMg){extraStock=env.pick(lineInput.inventory?.extra,['receive','stocked'],'补重黄金库存来源');extraPayer=ledger.validateMember(lineInput.extraMaterial?.payer,'补重料费付款人');extraRate=env.money(lineInput.extraMaterial.rate,'补重进货料价');if(lineInput.extraMaterial?.verified!==true)env.fail('请确认补重原料款已实际支付');}
const payers=Calc.costPayers(lineInput.costPayers);if(!pooled&&payers&&payers.material!==entry.buy_payer)env.fail('原锁价料费付款人不能修改');
actualLines.push({...lineInput,stockCount,name:entry.line.name,code:entry.line.code,unit:'g',pocket,pricingMode:'auto',goldPrice:yuan(entry.sell_rate),costParts:{...lineInput.costParts,material:yuan(costs.materialCost)},costMaterial:{mode:'total'},costPayers:{material:entry.buy_payer,labor:payers?.labor??lineInput.payer}});
results.push({entry,costs,pooled,pocket,stockCount,countSource,originalStock,extraStock,extraPayer,extraRate});
}
const discount=env.money(input.discount??'0','整单优惠'),lines=ledger.validateLines(actualLines,[],date,{member:ledger.entityMember('price_lock',id)??ledger.memberFor(actor)}),fees=ledger.validateFees((input.fee_items??[]).map(fee=>({...fee,status:'estimated'})));
const discount=env.money(input.discount??'0','整单优惠'),lines=ledger.validateLines(actualLines,lock.lines.map(entry=>entry.line),date,{member:ledger.entityMember('price_lock',id)??ledger.memberFor(actor)}),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??'助理微信';
@@ -191,6 +196,7 @@ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
else if(input.settlement?.amount!==undefined&&env.money(input.settlement.amount,'实际补退款金额')!==0)env.fail('本单无需补退款,不能重复记收款');
const note=customerNote(lock,input.note,env),normal={date,customer:lock.customer,salesperson:lock.salesperson,note,discount:yuan(discount),rounding_mode:'yuan',payment_account:settlementAccount,lines:actualLines,fee_items:fees.map(fee=>({...fee,amount:fee.amount===null?'':yuan(fee.amount),status:'estimated'})),fees_date:date};
const finalId=env.saveDeliveryOrder(normal).id,storedLines=ledger.rawOrder(finalId).lines,deliveryRows=[],group=randomUUID();
CreditCardRates.capture(ledger,'order',finalId,lock.credit_card_rate_permille);
for(const [index,result] of results.entries()){
const {entry,costs,pooled,pocket,stockCount,countSource,originalStock,extraStock,extraPayer,extraRate}=result,allocations=pooled?LockPools.materialAllocations(pooled.snapshot,costs.originalUsedMg):[{source:'original',quantity:costs.originalUsedMg,rate:entry.buy_rate,amount:costs.originalUsedCost,payer:entry.buy_payer}];
if(costs.extraMg)allocations.push({source:'extra',quantity:costs.extraMg,rate:extraRate,amount:costs.extraCost,payer:extraPayer});