支持耳钉货盘克重与对数同步库存及历史盘点基准
This commit is contained in:
1 parent
ba15795f0a
commit
b6a0213a0c
28 files changed
+906
-161
No files matched your search
+67
-13
@@ -29,6 +29,7 @@ const Recoveries=require('./recoveries');
|
||||
const RecoveryMaterial=require('./recovery-material');
|
||||
const RecoveryChanges=require('./recovery-changes');
|
||||
const Pockets=require('./pockets');
|
||||
const InventoryCounts=require('./inventory-counts');
|
||||
// 仅服务器的新单生成流程能传入,客户端字段不能取得这个权限。
|
||||
const NEW_ORDER_ACTION=Symbol('newOrderAction');
|
||||
const SAME_DAY_ORDER_ACTION=Symbol('sameDayOrderAction');
|
||||
@@ -177,6 +178,13 @@ class Ledger {
|
||||
validatePocket(key,options={}){return Pockets.validate(this,key,options);}
|
||||
createPocket(input,actor=this.actor){return Pockets.create(this,input,actor);}
|
||||
updatePocket(key,input,actor=this.actor){return Pockets.update(this,key,input,actor);}
|
||||
validateStockCount(pocket,value,options={}){return InventoryCounts.validate(this,pocket,value,options);}
|
||||
movementStockCount(id){return InventoryCounts.value(this,id);}
|
||||
movementCountRecord(id){const row=this.one('SELECT * FROM movement_counts WHERE movement_id=?',typeof id==='string'?id:id.id);return row?{stockCount:row.stock_count,effectiveDate:row.effective_date}:null;}
|
||||
attachMovementCount(id,count,options={}){return InventoryCounts.attach(this,id,count,options);}
|
||||
reverseMovementCount(original,id){return InventoryCounts.reverse(this,original,id);}
|
||||
validateCountInventory(deltas=[]){return InventoryCounts.assertInventory(this,deltas);}
|
||||
inventoryCountSnapshot(pockets){return InventoryCounts.snapshot(this,pockets);}
|
||||
businessEnv(){return {...priceLockEnv,pockets:this.activePocketKeys(),selfPockets:this.selfPocketKeys(),validatePocket:(key,options)=>this.validatePocket(key,options)};}
|
||||
enableTeamMode(){
|
||||
const previousMode=this.teamMode;this.db.exec('SAVEPOINT enable_team_mode');
|
||||
@@ -337,11 +345,17 @@ class Ledger {
|
||||
}
|
||||
validateLines(lines,historicalLines=[],businessDate=null,{orderId=null,member=null}={}){
|
||||
if(!Array.isArray(lines)||!lines.length||lines.length>60)fail('每单需要1~60行商品');
|
||||
const countHistoryUsed=new Set();
|
||||
const prepared=lines.map((l,i)=>{
|
||||
const unit=pick(l.unit,['g','件'],'单位');const qty=unit==='g'?weight(l.quantity,`第${i+1}行克重`):fixed(l.quantity,1,'件数')/10;
|
||||
if(qty<=0||(unit==='件'&&!Number.isInteger(qty)))fail('克重必须大于0,件数必须为正整数');
|
||||
const pocket=l.pocket?this.validatePocket(l.pocket,{original:historicalLines[i]?.pocket}):'';if(pocket&&unit!=='g')fail('货盘库存按克重管理,按件商品请选外配/不扣黄金');
|
||||
const name=text(l.name,'商品名称',60);
|
||||
// 仅完整匹配的一行可沿用旧未知数量。删除、重排或新增行不能借用相同下标免填对数。
|
||||
const originalIndex=historicalLines.findIndex((old,index)=>!countHistoryUsed.has(index)&&old.pocket===pocket&&old.unit===unit&&old.quantity===qty&&old.name===name&&String(old.code||'')===String(l.code||'').trim());
|
||||
const original=originalIndex<0?null:historicalLines[originalIndex];if(original)countHistoryUsed.add(originalIndex);
|
||||
const stockCount=this.validateStockCount(pocket,l.stockCount,{original:original?.stockCount??null,allowLegacy:!!original,name:`第${i+1}行库存对数`});
|
||||
if(stockCount!==null&&businessDate&&this.pocket(pocket)?.countSince>businessDate)fail('新对数业务日期不能早于'+this.pocket(pocket).countSince+'盘点基准;历史未知数量请保留原单并核对实物');
|
||||
if(Calc.isSilver(name)&&pocket)fail('银饰不扣黄金货盘,请选择外配/不扣黄金');
|
||||
const mode=pick(l.pricingMode||'manual',['auto','manual'],'计价方式');
|
||||
const priced=Calc.sale({...l,pricingMode:mode});
|
||||
@@ -351,7 +365,7 @@ class Ledger {
|
||||
const costPayers=Calc.costPayers(l.costPayers===undefined?historicalLines?.[i]?.costPayers:l.costPayers);
|
||||
const cost=breakdown?breakdown.total:(l.cost===''||l.cost==null?null:money(l.cost,'货品成本'));
|
||||
const priceNote=pricing?`金价 ${(pricing.goldPrice/100).toFixed(2)}元/克 + 工费 ${(pricing.laborRate/100).toFixed(2)}元/${pricing.laborMode==='gram'?'克':`件 × ${pricing.pieces}件`}`:text(l.priceNote,'客户单价说明',100,true);
|
||||
return {name,code:text(l.code,'商品编号',30,true),unit,quantity:qty,pocket,payer:pick(l.payer,['owner','assistant','assistant2'],'成本垫资人'),...(costPayers?{costPayers}:{}),...(l.costFundings===undefined?{}:{costFundings:costFundingReferences(l.costFundings)}),cost,...(breakdown?{costParts:breakdown.parts,costMaterial:breakdown.costMaterial,costLabor:breakdown.costLabor}:{}),sale:priced.sale,baseSale:priced.baseSale,charges:priced.charges,pricingMode:mode,...(pricing?{goldPrice:pricing.goldPrice,laborRate:pricing.laborRate,laborMode:pricing.laborMode,pieces:pricing.pieces}:{}),priceNote};
|
||||
return {name,code:text(l.code,'商品编号',30,true),unit,quantity:qty,pocket,...(stockCount===null?{}:{stockCount}),payer:pick(l.payer,['owner','assistant','assistant2'],'成本垫资人'),...(costPayers?{costPayers}:{}),...(l.costFundings===undefined?{}:{costFundings:costFundingReferences(l.costFundings)}),cost,...(breakdown?{costParts:breakdown.parts,costMaterial:breakdown.costMaterial,costLabor:breakdown.costLabor}:{}),sale:priced.sale,baseSale:priced.baseSale,charges:priced.charges,pricingMode:mode,...(pricing?{goldPrice:pricing.goldPrice,laborRate:pricing.laborRate,laborMode:pricing.laborMode,pieces:pricing.pieces}:{}),priceNote};
|
||||
});
|
||||
const materialMember=member??(orderId?this.entityMember('order',orderId):null)??(this.actor?this.memberFor(this.actor):null);
|
||||
return MaterialPools.prepareLines(this,prepared,businessDate,this.businessEnv(),{orderId,member:materialMember});
|
||||
@@ -470,6 +484,11 @@ class Ledger {
|
||||
if(missingFees.length)fail(`请补齐附加成本:${missingFees.join('、')};没有发生的费用填0`);
|
||||
}
|
||||
issueOrder(input,actor){
|
||||
this.db.exec('SAVEPOINT issue_order_action');
|
||||
try{const result=this.issueOrderInternal(input,actor);this.db.exec('RELEASE issue_order_action');return result;}
|
||||
catch(error){this.db.exec('ROLLBACK TO issue_order_action');this.db.exec('RELEASE issue_order_action');throw error;}
|
||||
}
|
||||
issueOrderInternal(input,actor){
|
||||
// 调用方用同一事务生成订单、收全款、记录实际费用并交付;任一步失败全部回滚。
|
||||
// 旧定金单仍沿用原动作,仅经明确确认 complete 后完成交付,不自动补收款。
|
||||
const prior=input.id?this.rawOrder(input.id,actor):null;
|
||||
@@ -494,7 +513,8 @@ class Ledger {
|
||||
const rows=this.rows('SELECT pocket,SUM(mg) AS mg FROM movements'+(asOf?' WHERE date<=?':'')+' GROUP BY pocket',...(asOf?[asOf]:[]));
|
||||
const reserved=Object.create(null);if(!asOf)for(const row of this.rows("SELECT lines FROM orders WHERE status='confirmed'"))for(const l of JSON.parse(row.lines))if(l.pocket)reserved[l.pocket]=(reserved[l.pocket]||0)+l.quantity;
|
||||
const keys=[...new Set([...this.pocketCatalog().map(row=>row.key),...rows.map(row=>row.pocket),...Object.keys(reserved)])];
|
||||
return keys.map(p=>({pocket:p,mg:rows.find(r=>r.pocket===p)?.mg||0,reserved:reserved[p]||0,available:(rows.find(r=>r.pocket===p)?.mg||0)-(reserved[p]||0)}));
|
||||
const counts=InventoryCounts.inventory(this,asOf);
|
||||
return keys.map(p=>({pocket:p,mg:rows.find(r=>r.pocket===p)?.mg||0,reserved:reserved[p]||0,available:(rows.find(r=>r.pocket===p)?.mg||0)-(reserved[p]||0),...(counts.get(p)?.countUnit==='pair'?counts.get(p):{})}));
|
||||
}
|
||||
inventoryRevision(date){
|
||||
// 流水只追加。计数使同日先增后减、净重不变的并发登记也能被发现。
|
||||
@@ -508,13 +528,13 @@ class Ledger {
|
||||
inventoryStatus(actor){
|
||||
const date=today(),yesterdayDate=new Date(Date.parse(date+'T00:00:00Z')-86400000).toISOString().slice(0,10);
|
||||
const inventory=this.inventory(),pockets=this.activePocketKeys();
|
||||
return {date,yesterdayDate,pockets,current:inventory.filter(r=>pockets.includes(r.pocket)),yesterday:this.inventorySnapshot(yesterdayDate),todaySnapshot:this.inventorySnapshot(date),revision:this.inventoryRevision(date),legacyInventory:inventory.filter(r=>!pockets.includes(r.pocket)&&(r.mg!==0||r.reserved!==0)),canReview:actor?.role==='owner'};
|
||||
return {date,yesterdayDate,pockets,current:inventory.filter(r=>pockets.includes(r.pocket)),yesterday:this.inventorySnapshot(yesterdayDate),todaySnapshot:this.inventorySnapshot(date),revision:this.inventoryRevision(date),legacyInventory:inventory.filter(r=>!pockets.includes(r.pocket)&&(r.mg!==0||r.reserved!==0||r.count||r.reservedCount||r.unknownReservedCount)),canReview:actor?.role==='owner'};
|
||||
}
|
||||
inventoryMovementSelection(query={}){
|
||||
if(!query||typeof query!=='object'||Array.isArray(query))fail('库存流水筛选无效');
|
||||
const kind=query.kind===undefined?'all':query.kind;
|
||||
if(typeof kind!=='string'||!['all','increase','decrease','transfer','manual'].includes(kind))fail('筛选流水类型无效');
|
||||
const allRows=this.rows('SELECT * FROM movements ORDER BY created DESC,rowid DESC');
|
||||
const allRows=InventoryCounts.decorate(this,this.rows('SELECT * FROM movements ORDER BY created DESC,rowid DESC'));
|
||||
// 库存及盘点流水三人共用;业务详情、修改和审批仍由原权限控制。
|
||||
const visible=allRows;
|
||||
const historical=new Set(visible.map(r=>r.pocket));
|
||||
@@ -591,33 +611,46 @@ class Ledger {
|
||||
inventoryChange(id,actor=this.actor){return InventoryChanges.read(this,id,actor,this.businessEnv());}
|
||||
approveInventoryChange(id,input,actor=this.actor){return InventoryChanges.approve(this,id,input,actor,this.businessEnv());}
|
||||
rejectInventoryChange(id,input,actor=this.actor){return InventoryChanges.reject(this,id,input,actor,this.businessEnv());}
|
||||
move({group=randomUUID(),order=null,date,pocket,mg,kind,note,cost=null,member=null},actor){
|
||||
move({group=randomUUID(),order=null,date,pocket,mg,kind,note,cost=null,member=null,stockCount=null,countEffectiveDate=null},actor){
|
||||
if(stockCount!==null&&stockCount<0)InventoryCounts.requireAvailable(this,pocket,-stockCount);
|
||||
const movementId=randomUUID();this.run('INSERT INTO movements VALUES (?,?,?,?,?,?,?,?,?,?,?)',movementId,group,order,date,pocket,mg,kind,note,cost,actor.name,now());
|
||||
this.attachMovementCount(movementId,stockCount,{effectiveDate:countEffectiveDate});
|
||||
this.assignMember('movement',movementId,order?this.entityMember('order',order)||this.memberFor(actor):member??this.memberFor(actor));
|
||||
// 回填历史日期也逐日检查,防止只看当前余额掩盖过去负库存。
|
||||
let balance=0;for(const r of this.rows('SELECT date,SUM(mg) AS mg FROM movements WHERE pocket=? GROUP BY date ORDER BY date',pocket)){balance+=r.mg;if(balance<0)fail(`${this.pocketLabel(pocket)}在${r.date}库存不足,不能提交`);}
|
||||
const inv=this.inventory().find(r=>r.pocket===pocket);if(inv.available<0)fail(`${this.pocketLabel(pocket)}可用库存不足,已有订单占用${(inv.reserved/1000).toFixed(3)}g`);
|
||||
this.validateCountInventory();
|
||||
this.dirtyInventory(date);
|
||||
return movementId;
|
||||
}
|
||||
stock(input,actor){
|
||||
const kind=pick(input.kind,['increase','decrease','transfer','opening','purchase','adjustment'],'库存动作');const date=day(input.date);const pocket=this.validatePocket(input.pocket);const note=text(input.note,'备注',200,true);
|
||||
let mg=fixed(input.grams,3,'克重',kind==='adjustment');if(!mg)fail('克重不能为0');if(kind==='opening'||kind==='adjustment')owner(actor);
|
||||
if(kind==='opening'&&this.one('SELECT id FROM movements WHERE pocket=? LIMIT 1',pocket))fail('该货盘已有流水,起始库存不能重复登记;差异请核查后调整');
|
||||
let mg=fixed(input.grams,3,'克重',kind==='adjustment');if(kind==='opening'||kind==='adjustment')owner(actor);
|
||||
if(kind==='opening'&&this.one("SELECT id FROM movements WHERE pocket=? AND kind<>'count_opening' LIMIT 1",pocket))fail('该货盘已有流水,起始库存不能重复登记;差异请核查后调整');
|
||||
const group=randomUUID();let cost=null;if(kind==='purchase'&&input.cost!=null&&input.cost!=='')cost=money(input.cost,'本次采购总成本(仅留档,不重复扣订单利润)');
|
||||
const to=kind==='transfer'?this.validatePocket(input.to,{name:'目标货盘'}):null;if(to===pocket)fail('来源和目标货盘不能相同');
|
||||
const countPocket=this.pocket(pocket)?.countUnit==='pair'?pocket:to&&this.pocket(to)?.countUnit==='pair'?to:null;
|
||||
const stockCount=this.validateStockCount(countPocket??pocket,input.stockCount,{signed:kind==='adjustment',allowZero:kind==='adjustment',name:'库存对数'});
|
||||
if(!mg&&(kind!=='adjustment'||stockCount===null||!stockCount))fail('克重和库存对数不能同时为0');
|
||||
if(kind==='adjustment'&&stockCount!==null&&date!==today())fail('对数盘点差异请登记今天的数量调整,不回填旧日盘点基准');
|
||||
// 独立调用也保持两边一起提交,任何库存校验失败都不会留下半笔或过期标记。
|
||||
this.db.exec('SAVEPOINT stock_movement');
|
||||
try{
|
||||
if(kind==='transfer'){
|
||||
this.move({group,date,pocket,mg:-mg,kind,note},actor);this.move({group,date,pocket:to,mg,kind,note},actor);
|
||||
}else this.move({group,date,pocket,mg:kind==='decrease'?-mg:mg,kind,note,cost},actor);
|
||||
this.audit('inventory','库存变动',actor,{group,kind,date,pocket,...(to?{to}:{}),grams:input.grams,note});
|
||||
this.move({group,date,pocket,mg:-mg,stockCount:this.pocket(pocket)?.countUnit==='pair'?-stockCount:null,kind,note},actor);this.move({group,date,pocket:to,mg,stockCount:this.pocket(to)?.countUnit==='pair'?stockCount:null,kind,note},actor);
|
||||
}else this.move({group,date,pocket,mg:kind==='decrease'?-mg:mg,stockCount:stockCount===null?null:kind==='decrease'?-stockCount:stockCount,kind,note,cost},actor);
|
||||
this.audit('inventory','库存变动',actor,{group,kind,date,pocket,...(to?{to}:{}),grams:input.grams,...(stockCount===null?{}:{stockCount}),note});
|
||||
InventoryChanges.register(this,group,actor,this.businessEnv());
|
||||
this.db.exec('RELEASE stock_movement');return {group};
|
||||
}catch(e){this.db.exec('ROLLBACK TO stock_movement');this.db.exec('RELEASE stock_movement');throw e;}
|
||||
}
|
||||
journal(id,date,kind,sales,goods,expense){this.run('INSERT INTO journal VALUES (?,?,?,?,?,?,?,?,?)',randomUUID(),id,date,kind,sales,goods,expense,sales-goods-expense,now());this.dirty(date);}
|
||||
action(id,action,input,actor,context=null){
|
||||
this.db.exec('SAVEPOINT ledger_order_action');
|
||||
try{const result=this.actionInternal(id,action,input,actor,context);this.db.exec('RELEASE ledger_order_action');return result;}
|
||||
catch(error){this.db.exec('ROLLBACK TO ledger_order_action');this.db.exec('RELEASE ledger_order_action');throw error;}
|
||||
}
|
||||
actionInternal(id,action,input,actor,context=null){
|
||||
this.assertAccess('order',id,actor);if(Object.hasOwn(input,'member'))this.selectedMember(input,actor,this.entityMember('order',id));
|
||||
if(context!==NEW_ORDER_ACTION&&!['review','print'].includes(action))this.guardRecoveryOrder(id);
|
||||
const o=this.detail(id);const date=day(input.date||today(),actor.role==='assistant'&&['expense','fees','refund','return'].includes(action)?'2000-01-01':o.date);
|
||||
@@ -645,7 +678,13 @@ class Ledger {
|
||||
if(o.status!=='draft')fail('订单已经确认,请刷新查看',409);
|
||||
if(o.pendingFees.some(f=>f.status!=='estimated')&&input.feesVerified!==true)fail('请核实开单所填快递、包装等费用已实际支付');
|
||||
if(input.feesVerified===true&&o.pendingFees.some(f=>f.amount===null))fail('请补齐附加成本;没有发生的费用填0');
|
||||
for(const p of new Set(o.lines.map(line=>line.pocket).filter(Boolean))){const need=sum(o.lines,l=>l.pocket===p?l.quantity:0);if(need>this.inventory().find(r=>r.pocket===p).available)fail(`${this.pocketLabel(p)}可用库存不足,请先登记入库`);}
|
||||
for(const p of new Set(o.lines.map(line=>line.pocket).filter(Boolean))){
|
||||
const need=sum(o.lines,l=>l.pocket===p?l.quantity:0);if(need>this.inventory().find(r=>r.pocket===p).available)fail(`${this.pocketLabel(p)}可用库存不足,请先登记入库`);
|
||||
if(this.pocket(p)?.countUnit==='pair'){
|
||||
const counts=o.lines.filter(line=>line.pocket===p).map(line=>this.validateStockCount(p,line.stockCount));
|
||||
InventoryCounts.requireAvailable(this,p,sum(counts,count=>count));
|
||||
}
|
||||
}
|
||||
this.run("UPDATE orders SET status='confirmed' WHERE id=?",id);
|
||||
if(input.feesVerified===true&&o.pendingFees.length)this.recordFees(o,o.pendingFees,o.fees_date||date,actor,context);
|
||||
} else if(action==='receipt'||action==='refund'){
|
||||
@@ -698,6 +737,13 @@ class Ledger {
|
||||
if(input.revision!=null&&input.revision!==o.revision)fail('订单有新变动,请重新打开后完成记账',409);
|
||||
if(input.verified!==true)fail('请确认已全额收款、核实费用并实际交付');
|
||||
if(o.balance!==0)fail('未收齐客户款,不能确认交付');
|
||||
// 旧预订单可在实物复称交付时补齐实际对数;不改销售金额、克重或盘点基准。
|
||||
let countsChanged=false;
|
||||
for(const [index,line] of o.lines.entries())if(this.pocket(line.pocket)?.countUnit==='pair'){
|
||||
const supplied=input.stockCounts?.[index],count=this.validateStockCount(line.pocket,supplied,{original:line.stockCount??null});
|
||||
if(count!==line.stockCount){line.stockCount=count;countsChanged=true;}
|
||||
}
|
||||
if(countsChanged){this.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(o.lines),id);this.validateCountInventory();}
|
||||
this.validateCompletedCosts(o.lines,o.fee_items);
|
||||
// 老版本无 status 的费用可能已经入账,只有明确待核实的项目才能在此新增支出。
|
||||
const fees=o.pendingFees;
|
||||
@@ -712,7 +758,10 @@ class Ledger {
|
||||
if(o.payments.some(p=>p.date>date)||o.expenses.some(e=>e.date>date))fail('交付日期不能早于本单已登记的收款或费用日期');
|
||||
this.run("UPDATE orders SET status='delivered',delivered_date=? WHERE id=?",date,id);
|
||||
const delivered=MaterialPools.deliver(this,o,date,actor,this.businessEnv());
|
||||
const group=randomUUID();for(const l of o.lines)if(l.pocket)this.move({group,order:id,date,pocket:l.pocket,mg:-l.quantity,kind:'sale',note:o.number},actor);
|
||||
const group=randomUUID();for(const l of o.lines)if(l.pocket){
|
||||
const stockCount=this.pocket(l.pocket)?.countUnit==='pair'?this.validateStockCount(l.pocket,l.stockCount):null;
|
||||
this.move({group,order:id,date,pocket:l.pocket,mg:-l.quantity,stockCount:stockCount===null?null:-stockCount,kind:'sale',note:o.number},actor);
|
||||
}
|
||||
const knownGoods=sum(delivered.lines,line=>line.cost??sum(Object.values(line.costParts||{}).map(amount=>({amount:amount??0})),'amount'));
|
||||
this.journal(id,date,'交付',o.total,knownGoods,o.directCost);
|
||||
} else if(action==='return'){
|
||||
@@ -724,7 +773,12 @@ class Ledger {
|
||||
const destination=input.returnPockets?.[i]??l.pocket;
|
||||
if(l.costMaterial?.mode==='pool'&&!destination)fail('日购料黄金退货须退回自有货盘,请选择实物退回的货盘;退供应商请先核实购料退款');
|
||||
if(l.pocket&&!destination)fail('原自有货盘商品须选择退回货盘');
|
||||
if(destination){this.validatePocket(destination,{original:l.pocket,name:'退回货盘'});if(l.unit!=='g')fail('按件商品不计黄金货盘');this.move({group,order:id,date,pocket:destination,mg:l.quantity,kind:'return',note:o.number},actor);}
|
||||
if(destination){
|
||||
this.validatePocket(destination,{original:l.pocket,name:'退回货盘'});if(l.unit!=='g')fail('按件商品不计黄金货盘');
|
||||
const stockCount=this.pocket(destination)?.countUnit==='pair'?this.validateStockCount(destination,input.returnCounts?.[i],{original:l.stockCount??null,name:`第${i+1}行实际退回对数`}):null;
|
||||
if(stockCount!==null&&Number.isSafeInteger(l.stockCount)&&stockCount!==l.stockCount)fail(`第${i+1}行是整单退货,退回对数须与原销售${l.stockCount}对一致;原单数量录错请先更正原单`);
|
||||
this.move({group,order:id,date,pocket:destination,mg:l.quantity,stockCount,kind:'return',note:o.number},actor);
|
||||
}
|
||||
});
|
||||
this.journal(id,date,'整单退货',-o.total,-o.knownGoodsCost,0);
|
||||
MaterialPools.release(this,o,date,actor,this.businessEnv());
|
||||
|
||||
Reference in new issue
Block a user