支持耳钉货盘克重与对数同步库存及历史盘点基准
This commit is contained in:
1 parent
ba15795f0a
commit
b6a0213a0c
28 files changed
+906
-161
No files matched your search
+37
-10
@@ -1,7 +1,7 @@
|
||||
'use strict';
|
||||
// 回收专用更正:身份不变、原流水保留;旧账冲正与新账补记和审批在同一事务中。
|
||||
const {randomUUID,createHash}=require('node:crypto');
|
||||
const Recoveries=require('./recoveries'),Material=require('./material-pools'),Rolling=require('./rolling-material-pools'),TeamFunds=require('./team-funds');
|
||||
const Recoveries=require('./recoveries'),Material=require('./material-pools'),Rolling=require('./rolling-material-pools'),TeamFunds=require('./team-funds'),Counts=require('./inventory-counts');
|
||||
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const yuan=value=>(value/100).toFixed(2),sum=(rows,key)=>rows.reduce((n,row)=>n+(row[key]??0),0);
|
||||
function atomic(l,fn){l.db.exec('SAVEPOINT recovery_change');try{const r=fn();l.db.exec('RELEASE recovery_change');return r;}catch(e){l.db.exec('ROLLBACK TO recovery_change');l.db.exec('RELEASE recovery_change');throw e;}}
|
||||
@@ -61,12 +61,14 @@ function snapshot(l,row){
|
||||
const order=row.order_id?l.rawOrder(row.order_id):null,tables={};
|
||||
for(const table of ['payments','expenses','settlements','journal'])tables[table]=row.order_id?l.rows('SELECT * FROM '+table+' WHERE order_id=? ORDER BY rowid',row.order_id):[];
|
||||
tables.movements=l.rows('SELECT * FROM movements WHERE group_id=? OR order_id=? ORDER BY rowid',row.inventory_group,row.order_id??'');
|
||||
const movementCounts=Counts.decorate(l,tables.movements).filter(row=>row.stockCount!=null).map(({id,stockCount,countEffectiveDate})=>({id,stockCount,countEffectiveDate}));
|
||||
if(movementCounts.length)tables.movementCounts=movementCounts;
|
||||
tables.usages=row.order_id?l.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY rowid',row.order_id):[];
|
||||
tables.purchase=row.purchase_id?l.one('SELECT * FROM material_purchases WHERE id=?',row.purchase_id):null;
|
||||
tables.purchaseSource=row.purchase_id?l.one('SELECT * FROM recovery_purchase_sources WHERE purchase_id=?',row.purchase_id):null;
|
||||
return {record:row,order,...tables};
|
||||
}
|
||||
function dependency(l,row){return hash({snapshot:snapshot(l,row),pool:Rolling.dependency(l),inventory:l.rows('SELECT id,date,pocket,mg FROM movements ORDER BY rowid')});}
|
||||
function dependency(l,row){const counts=Counts.snapshot(l,l.pocketCatalog().map(row=>row.key));return hash({snapshot:snapshot(l,row),pool:Rolling.dependency(l),inventory:l.rows('SELECT id,date,pocket,mg FROM movements ORDER BY rowid'),...(counts?{counts}:{})});}
|
||||
function compact(q){return q?Object.fromEntries(['mode','date','oldMg','newMg','purchaseMg','purchaseAmount','receivable','cashReceipt','cashPayment','offsetAmount','goodsCost','directCost','profit'].map(key=>[key,q[key]])):null;}
|
||||
function dto(l,row,actor,env){
|
||||
const current=rowFor(l,row.recovery_id,actor,env),stale=row.status==='pending'&&(current.revision!==row.recovery_revision||dependency(l,current)!==row.dependency);
|
||||
@@ -83,13 +85,23 @@ function detail(l,id,actor,env){
|
||||
const row=rowFor(l,id,actor,env),current=JSON.parse(row.data),waiting=pending(l,id),history=l.rows('SELECT * FROM recovery_changes WHERE recovery_id=? ORDER BY created DESC,rowid DESC',id).filter(r=>actor.role==='owner'||r.requester_id===actor.id);
|
||||
const usages=usageRows(l,row,null,env),enabled=row.status!=='cancelled'&&!waiting;
|
||||
return {id,revision:row.revision,status:row.status,record:Recoveries.detail(l,id,actor,env),inputs:Recoveries.inputFor(current),
|
||||
permissions:{canEdit:enabled,canCancel:enabled,canDirect:enabled&&(actor.role==='owner'||row.date===env.today()),requiresApproval:actor.role==='assistant'&&row.date!==env.today(),reason:row.status==='cancelled'?'本单已经取消':waiting?'本单有待审批更正':usages.length?'取消后关联用料改用公共料,公共料不足的订单料费待补;减重或移日仍须先处理关联用料':''},
|
||||
permissions:{canEdit:enabled,canCancel:enabled,canDirect:enabled&&(actor.role==='owner'||row.date===env.today()),requiresApproval:actor.role==='assistant'&&row.date!==env.today(),...legacyCountInfo(l,row),reason:row.status==='cancelled'?'本单已经取消':waiting?'本单有待审批更正':usages.length?'取消后关联用料改用公共料,公共料不足的订单料费待补;减重或移日仍须先处理关联用料':''},
|
||||
blockedUsages:visibleUsages(l,usages,actor),pending:waiting?dto(l,waiting,actor,env):null,history:history.filter(r=>r.status!=='pending').map(r=>dto(l,r,actor,env))};
|
||||
}
|
||||
function movements(l,row,after){
|
||||
const existing=l.rows('SELECT date,pocket,SUM(mg) AS mg FROM movements WHERE group_id=? OR order_id=? GROUP BY date,pocket HAVING SUM(mg)<>0',row.inventory_group,row.order_id??'');
|
||||
const deltas=existing.map(r=>({...r,mg:-r.mg,kind:'recovery_change_reverse'}));
|
||||
if(after){deltas.push({date:after.date,pocket:'回收旧料',mg:after.oldMg,kind:'recovery_change_old'});if(after.mode==='exchange')deltas.push({date:after.date,pocket:after.newProduct.pocket,mg:-after.newMg,kind:'recovery_change_sale'});}
|
||||
// 对数按自己的生效日净额冲正;旧重量流水没有对数时保持未知,不从克重或工费件数推算。
|
||||
const counts=new Map();for(const movement of Counts.decorate(l,l.rows('SELECT * FROM movements WHERE group_id=? OR order_id=? ORDER BY rowid',row.inventory_group,row.order_id??''))){
|
||||
if(movement.stockCount==null)continue;
|
||||
const key=JSON.stringify([movement.pocket,movement.countEffectiveDate]),value=counts.get(key)??{pocket:movement.pocket,date:movement.countEffectiveDate,stockCount:0};value.stockCount+=movement.stockCount;counts.set(key,value);
|
||||
}
|
||||
for(const count of counts.values())if(count.stockCount){
|
||||
const matching=deltas.find(movement=>movement.pocket===count.pocket&&movement.date===count.date&&movement.stockCount===undefined);
|
||||
if(matching)Object.assign(matching,{stockCount:-count.stockCount,countEffectiveDate:count.date});
|
||||
else deltas.push({...count,mg:0,stockCount:-count.stockCount,countEffectiveDate:count.date,kind:'recovery_change_reverse'});
|
||||
}
|
||||
if(after){deltas.push({date:after.date,pocket:'回收旧料',mg:after.oldMg,kind:'recovery_change_old'});if(after.mode==='exchange')deltas.push({date:after.date,pocket:after.newProduct.pocket,mg:-after.newMg,stockCount:after.newProduct.stockCount==null?null:-after.newProduct.stockCount,kind:'recovery_change_sale'});}
|
||||
return deltas;
|
||||
}
|
||||
function validateInventory(l,deltas,env){
|
||||
@@ -97,6 +109,7 @@ function validateInventory(l,deltas,env){
|
||||
for(const row of [...l.rows('SELECT date,pocket,SUM(mg) AS mg FROM movements GROUP BY date,pocket'),...deltas]){const dates=grouped.get(row.pocket)??new Map();dates.set(row.date,(dates.get(row.date)??0)+row.mg);grouped.set(row.pocket,dates);}
|
||||
const totals=new Map();for(const [pocket,dates] of grouped){let mg=0;for(const [date,delta] of [...dates].sort(([a],[b])=>a.localeCompare(b))){mg+=delta;if(!Number.isSafeInteger(mg)||mg<0)env.fail(l.pocketLabel(pocket)+'在'+date+'库存不足,不能更正回收记录',409);}totals.set(pocket,mg);}
|
||||
for(const inventory of l.inventory())if((totals.get(inventory.pocket)??0)<inventory.reserved)env.fail(l.pocketLabel(inventory.pocket)+'已有预订单占用,不能更正回收库存',409);
|
||||
l.validateCountInventory(deltas);
|
||||
}
|
||||
function reverseRows(l,id,table,actor,reason,env){
|
||||
const isPayment=table==='payments',key=isPayment?'account':'payer',type=isPayment?'payment':'expense',label=isPayment?'reference':'note';
|
||||
@@ -147,8 +160,15 @@ function replaceJournal(l,row,after){
|
||||
l.touch(id);
|
||||
}
|
||||
function financialInput(value){const {customer,salesperson,note,...rest}=value;return rest;}
|
||||
function execute(l,row,after,actor,reason,env){return Rolling.withHistorical(l,()=>l.scope(null,()=>{
|
||||
function metadataChangeOnly(row,after){return !!after&&hash(financialInput(Recoveries.inputFor(JSON.parse(row.data))))===hash(financialInput(Recoveries.inputFor(after)));}
|
||||
function legacyCountInfo(l,row){
|
||||
const q=JSON.parse(row.data),product=q.mode==='exchange'?q.newProduct:null;
|
||||
return Counts.legacyInfo(l,product&&product.stockCount==null?[{id:'',pocket:product.pocket,mg:q.newMg}]:[]);
|
||||
}
|
||||
function verifyLegacyCount(l,row,after,input,env){const info=legacyCountInfo(l,row);if(info.requiresLegacyCountVerified&&!metadataChangeOnly(row,after)&&input?.legacyCountVerified!==true)env.fail('请核对并确认:'+info.legacyCountNotice);}
|
||||
function execute(l,row,after,actor,reason,env,input={}){return Rolling.withHistorical(l,()=>l.scope(null,()=>{
|
||||
const before=snapshot(l,row),old=JSON.parse(row.data),metadataOnly=!!after&&hash(financialInput(Recoveries.inputFor(old)))===hash(financialInput(Recoveries.inputFor(after)));
|
||||
verifyLegacyCount(l,row,after,input,env);
|
||||
const deltas=metadataOnly?[]:movements(l,row,after);validateInventory(l,deltas,env);
|
||||
const changed=l.run('UPDATE recoveries SET date=?,customer=?,salesperson=?,note=?,old_lines=?,data=?,status=?,cancelled_at=?,updated=?,revision=revision+1 WHERE id=? AND revision=?',after?.date??row.date,after?.customer??row.customer,after?.salesperson??row.salesperson,after?.note??row.note,JSON.stringify(after?.old_lines??old.old_lines),JSON.stringify(metadataOnly?{...old,customer:after.customer,salesperson:after.salesperson,note:after.note}:after??old),after?'active':'cancelled',after?'':env.now(),env.now(),row.id,row.revision);
|
||||
if(changed.changes!==1)env.fail('回收记录已有其他更正,请刷新',409);
|
||||
@@ -159,7 +179,8 @@ function execute(l,row,after,actor,reason,env){return Rolling.withHistorical(l,(
|
||||
if(after&&row.order_id){const order=l.rawOrder(row.order_id);Material.adjust(l,{...order,lines:order.lines.map(line=>line.costMaterial?.mode==='pool'?{...line,quantity:line.costMaterial.consumptionMg??line.quantity}:line)},after.date,actor,env);}
|
||||
for(const pool of pools)Material.reconcile(l,pool,env.today(),actor,env,{skipJournalOrder:row.order_id});
|
||||
if(Rolling.enabled(l))Rolling.rebuildFrom(l,[row.date,after?.date,...pools].filter(Boolean).sort()[0],actor,env);
|
||||
for(const movement of deltas){const id=randomUUID();l.run('INSERT INTO movements VALUES (?,?,?,?,?,?,?,?,?,?,?)',id,row.inventory_group,row.order_id,movement.date,movement.pocket,movement.mg,movement.kind,'回收更正:'+row.number+';'+reason,null,actor.name,env.now());l.assignMember('movement',id,row.member);}
|
||||
for(const movement of deltas){const id=randomUUID();l.run('INSERT INTO movements VALUES (?,?,?,?,?,?,?,?,?,?,?)',id,row.inventory_group,row.order_id,movement.date,movement.pocket,movement.mg,movement.kind,'回收更正:'+row.number+';'+reason,null,actor.name,env.now());l.attachMovementCount(id,movement.stockCount,{effectiveDate:movement.countEffectiveDate??movement.date});l.assignMember('movement',id,row.member);}
|
||||
l.validateCountInventory();
|
||||
replaceJournal(l,row,after);
|
||||
const hook=materialHook();hook?.recoveryUpdated?.(l,row.id,actor,env);
|
||||
}
|
||||
@@ -174,18 +195,24 @@ function normalized(l,row,input,actor,env){
|
||||
if(input.mode!==row.mode)env.fail('回收方式不能直接互转,请取消原单后新建');
|
||||
if(Object.hasOwn(input,'member')&&input.member!==row.member)env.fail('已有回收记录的归属不能修改',403);
|
||||
// 历史试算只读;日期许可仍在change/approve决定,不能把试算许可当成落账权限。
|
||||
return Rolling.withHistorical(l,()=>Recoveries.quote(l,{...input,member:row.member},actor,env,{creating:true,orderId:row.order_id,existingRecovery:JSON.parse(row.data)}));
|
||||
const previous=JSON.parse(row.data),after=Rolling.withHistorical(l,()=>Recoveries.quote(l,{...input,member:row.member},actor,env,{creating:true,orderId:row.order_id,existingRecovery:previous}));
|
||||
if(previous.mode==='exchange'&&previous.newProduct?.stockCount==null&&l.pocket(previous.newProduct.pocket)?.countUnit==='pair'){
|
||||
const physical=product=>JSON.stringify([product.name,product.quantity,product.pocket,product.stockCount??null]);
|
||||
if(physical(previous.newProduct)!==physical(after.newProduct))env.fail('启用前已交付的置换新货没有原始对数,只能更正资料和财务;成品变化请先核对实物,再登记今天的数量调整,不能补旧单对数重扣盘点基准');
|
||||
}
|
||||
return after;
|
||||
}
|
||||
function quote(l,id,input,actor,env){object(input,env);const row=rowFor(l,id,actor,env);if(row.status==='cancelled')env.fail('本单已经取消',409);if(input.revision!==row.revision||!Number.isSafeInteger(input.revision))env.fail('回收记录版本已有变动,请刷新核对',409);return normalized(l,row,input,actor,env);}
|
||||
function change(l,id,action,input,actor,env){return atomic(l,()=>{
|
||||
object(input,env);const row=rowFor(l,id,actor,env);if(row.status==='cancelled')env.fail('这笔回收已经取消,不能重复处理',409);
|
||||
if(!Number.isSafeInteger(input.revision)||input.revision!==row.revision)env.fail('回收记录版本已有变动,请刷新核对',409);if(pending(l,id))env.fail('本单已有待审批更正,请先由麦麦处理',409);
|
||||
if(input.verified!==true)env.fail('请核实关联收付、购料和库存后确认');const reason=env.text(input.reason,'回收更正原因',200),after=action==='cancel'?null:normalized(l,row,input,actor,env),date=after?.date??env.day(input.date??env.today());
|
||||
verifyLegacyCount(l,row,after,input,env);
|
||||
const affected=blocking(l,row,after,actor,env);validateInventory(l,movements(l,row,after),env);
|
||||
const before=Recoveries.inputFor(JSON.parse(row.data)),next=after?Recoveries.inputFor(after):null,requestId=randomUUID(),created=env.now(),direct=actor.role==='owner'||row.date===env.today()&&date===env.today();
|
||||
const summary={before:compact(Recoveries.detail(l,id,actor,env)),after:compact(after),affectedDates:[...new Set([row.date,date])].sort(),blockedUsages:affected};
|
||||
const summary={before:compact(Recoveries.detail(l,id,actor,env)),after:compact(after),affectedDates:[...new Set([row.date,date])].sort(),blockedUsages:affected,...legacyCountInfo(l,row),legacyCountVerified:input.legacyCountVerified===true};
|
||||
l.run('INSERT INTO recovery_changes(id,recovery_id,recovery_revision,action,status,reason,before_value,after_value,summary,dependency,snapshot,requester_id,requester_name,requester_member,member,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',requestId,id,row.revision,action,direct?'approved':'pending',reason,JSON.stringify(before),next?JSON.stringify(next):null,JSON.stringify(summary),dependency(l,row),JSON.stringify(snapshot(l,row)),actor.id,actor.name,l.memberFor(actor),row.member,created);
|
||||
if(direct){execute(l,row,after,actor,reason,env);l.run('UPDATE recovery_changes SET reviewer_id=?,reviewer_name=?,reviewed=? WHERE id=?',actor.id,actor.name,created,requestId);}
|
||||
if(direct){execute(l,row,after,actor,reason,env,input);l.run('UPDATE recovery_changes SET reviewer_id=?,reviewer_name=?,reviewed=? WHERE id=?',actor.id,actor.name,created,requestId);}
|
||||
else l.audit('recovery:'+id,action==='cancel'?'申请取消回收/置换':'申请修改回收/置换',actor,{requestId,reason,before,after:next,notice:'审批前不改变有效收付、购料、库存或利润'});
|
||||
return {id,applied:direct,pending:!direct,requestId,request:read(l,requestId,actor,env),recovery:Recoveries.detail(l,id,actor,env)};
|
||||
});}
|
||||
@@ -199,7 +226,7 @@ function decision(l,id,input,actor,env){active(actor,env);if(actor.role!=='owner
|
||||
function approve(l,id,input,actor,env){return atomic(l,()=>{
|
||||
const request=decision(l,id,input,actor,env),row=rowFor(l,request.recovery_id,actor,env);
|
||||
if(row.revision!==request.recovery_revision||dependency(l,row)!==request.dependency)env.fail('回收关联数据已有变动,申请已过期,请驳回后重新提交',409);if(input.verified!==true)env.fail('请核实回收更正影响后批准');
|
||||
const after=request.after_value?normalized(l,row,JSON.parse(request.after_value),actor,env):null;blocking(l,row,after,actor,env);execute(l,row,after,actor,request.reason,env);
|
||||
const after=request.after_value?normalized(l,row,JSON.parse(request.after_value),actor,env):null;blocking(l,row,after,actor,env);execute(l,row,after,actor,request.reason,env,{legacyCountVerified:JSON.parse(request.summary).legacyCountVerified===true});
|
||||
l.run("UPDATE recovery_changes SET status='approved',revision=revision+1,reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=? AND status='pending'",actor.id,actor.name,env.now(),env.text(input.note,'审批说明',200,true),id);return read(l,id,actor,env);
|
||||
});}
|
||||
function reject(l,id,input,actor,env){return atomic(l,()=>{const request=decision(l,id,input,actor,env),note=env.text(input.note,'驳回原因',200);l.run("UPDATE recovery_changes SET status='rejected',revision=revision+1,reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=?",actor.id,actor.name,env.now(),note,id);l.audit('recovery:'+request.recovery_id,'驳回回收更正申请',actor,{requestId:id,note});return read(l,id,actor,env);});}
|
||||
|
||||
Reference in new issue
Block a user