支持耳钉货盘克重与对数同步库存及历史盘点基准

This commit is contained in:
summer committed 2026-11-08 15:47:07 +08:00
1 parent ba15795f0a
commit b6a0213a0c
28 files changed
+906 -161

No files matched your search

+47 -24
View File
@@ -1,6 +1,7 @@
'use strict';
// 手动库存更正保留原流水,整组冲正后重记;助理所有日期均先审批。
const {randomUUID,createHash}=require('node:crypto');
const Counts=require('./inventory-counts');
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const MANUAL_KINDS=new Set(['increase','decrease','transfer','purchase','adjustment','manual']);
const grams=mg=>(mg/1000).toFixed(3);
@@ -32,19 +33,25 @@ function initialize(ledger){ledger.db.exec(`
CREATE INDEX IF NOT EXISTS ix_inventory_changes_status ON inventory_changes(status,created);
`);}
function normalized(rows){
if(!rows.length||rows.some(row=>row.order_id||!MANUAL_KINDS.has(row.kind)||!Number.isSafeInteger(row.mg)||row.mg===0))return null;
if(!rows.length||rows.some(row=>row.order_id||!MANUAL_KINDS.has(row.kind)||!Number.isSafeInteger(row.mg)||(row.mg===0&&(!Number.isSafeInteger(row.stockCount)||row.stockCount===0))))return null;
if(rows.length===2&&rows.every(row=>row.kind==='transfer')){
const from=rows.find(row=>row.mg<0),to=rows.find(row=>row.mg>0);
if(!from||!to||from.mg+to.mg!==0||from.date!==to.date||from.pocket===to.pocket)return null;
return {kind:'transfer',date:from.date,pocket:from.pocket,to:to.pocket,grams:grams(-from.mg),note:from.note,cost:''};
const counts=rows.filter(row=>row.stockCount!==null&&row.stockCount!==undefined);
if(counts.length===2&&counts[0].stockCount+counts[1].stockCount!==0||counts.some(row=>Math.sign(row.stockCount)!==Math.sign(row.mg)))return null;
return {kind:'transfer',date:from.date,pocket:from.pocket,to:to.pocket,grams:grams(-from.mg),...(counts.length?{stockCount:Math.abs(counts[0].stockCount)}:{}),note:from.note,cost:''};
}
if(rows.length!==1||rows[0].kind==='transfer')return null;
const row=rows[0];if(row.kind==='increase'&&row.mg<0||row.kind==='decrease'&&row.mg>0||row.kind==='purchase'&&row.mg<0)return null;
return {kind:row.mg>0?'increase':'decrease',date:row.date,pocket:row.pocket,to:'',grams:grams(Math.abs(row.mg)),note:row.note,cost:row.purchase_cost===null?'':(row.purchase_cost/100).toFixed(2)};
if(row.kind==='adjustment')return {kind:'adjustment',date:row.date,pocket:row.pocket,to:'',grams:grams(row.mg),...(Number.isSafeInteger(row.stockCount)?{stockCount:row.stockCount}:{}),note:row.note,cost:row.purchase_cost===null?'':(row.purchase_cost/100).toFixed(2)};
// 原始 adjustment 可只调整对数;库存变动方向不从0g推断。
const sign=Math.sign(row.mg||row.stockCount);
if(row.mg&&row.stockCount&&Math.sign(row.mg)!==Math.sign(row.stockCount))return {kind:'adjustment',date:row.date,pocket:row.pocket,to:'',grams:grams(row.mg),stockCount:row.stockCount,note:row.note,cost:''};
return {kind:sign>0?'increase':'decrease',date:row.date,pocket:row.pocket,to:'',grams:grams(Math.abs(row.mg)),...(Number.isSafeInteger(row.stockCount)?{stockCount:Math.abs(row.stockCount)}:{}),note:row.note,cost:row.purchase_cost===null?'':(row.purchase_cost/100).toFixed(2)};
}
function manualMovementKinds(ledger,allRows,visibleRows){
// 先排除销售、订单及自动流水;只为手动候选批量读取更正关系,不逐条调用详情。
const candidates=visibleRows.filter(row=>!row.order_id&&MANUAL_KINDS.has(row.kind)&&Number.isSafeInteger(row.mg)&&row.mg!==0),kinds=new Map();
const candidates=visibleRows.filter(row=>!row.order_id&&MANUAL_KINDS.has(row.kind)&&Number.isSafeInteger(row.mg)&&(row.mg!==0||row.stockCount)),kinds=new Map();
if(!candidates.length)return kinds;
const byId=new Map(allRows.map(row=>[row.id,row])),visibleIds=new Set(visibleRows.map(row=>row.id));
const links=new Map(ledger.rows('SELECT * FROM inventory_manual_rows').map(row=>[row.movement_id,row]));
@@ -63,7 +70,7 @@ function manualMovementKinds(ledger,allRows,visibleRows){
}
if(!trusted.get(groupId))continue;
// 每一代流水按当时动作分类,不能用整组更正后的最新 value 重解释原始行。
if(!actions.has(row.group_id))actions.set(row.group_id,normalized(rawGroups.get(row.group_id)||[])?.kind);
if(!actions.has(row.group_id)){const value=normalized(rawGroups.get(row.group_id)||[]);actions.set(row.group_id,value?.kind==='adjustment'?Math.sign(Number(value.grams)||value.stockCount)>0?'increase':'decrease':value?.kind);}
const kind=actions.get(row.group_id);if(kind)kinds.set(row.id,kind);
}
return kinds;
@@ -82,10 +89,11 @@ function state(ledger,id,actor,env,{internal=false}={}){
const movement=ledger.one('SELECT * FROM movements WHERE id=?',id);
const groupId=link?.group_id??movement?.group_id??id;
const stored=ledger.one('SELECT * FROM inventory_manual_groups WHERE group_id=?',groupId);
const originalRows=stored?JSON.parse(stored.original_ids).map(id=>ledger.one('SELECT * FROM movements WHERE id=?',id)):ledger.rows('SELECT * FROM movements WHERE group_id=? ORDER BY rowid',groupId);
let originalRows=stored?JSON.parse(stored.original_ids).map(id=>ledger.one('SELECT * FROM movements WHERE id=?',id)):ledger.rows('SELECT * FROM movements WHERE group_id=? ORDER BY rowid',groupId);
if(!originalRows.length||originalRows.some(row=>!row))env.fail('库存记录不存在或无权访问',404);
if(!internal&&actor.role!=='owner'&&originalRows.some(row=>!ledger.canAccess('movement',row.id,actor)))env.fail('库存记录不存在或无权访问',404);
const currentRows=stored?JSON.parse(stored.current_ids).map(id=>ledger.one('SELECT * FROM movements WHERE id=?',id)):originalRows;
originalRows=Counts.decorate(ledger,originalRows);
const currentRows=stored?Counts.decorate(ledger,JSON.parse(stored.current_ids).map(id=>ledger.one('SELECT * FROM movements WHERE id=?',id))):originalRows;
const value=stored?JSON.parse(stored.value):normalized(originalRows);
const manual=!!value&&!!normalized(originalRows)&&currentRows.every(Boolean);
const creatorId=stored?.creator_id??historicalCreator(ledger,groupId),member=stored?.member??ledger.entityMember('movement',originalRows[0].id)??'owner';
@@ -93,7 +101,7 @@ function state(ledger,id,actor,env,{internal=false}={}){
const canManage=manual&&(actor?.role==='owner'||!!creatorId&&creatorId===actor?.id&&originalRows.every(row=>ledger.canAccess('movement',row.id,actor)));
return {groupId,stored,originalRows,currentRows,value,manual,creatorId,member,revision:stored?.revision??1,status:stored?.status??'active',pending,canManage};
}
function groupHash(group){return hash({groupId:group.groupId,revision:group.revision,status:group.status,value:group.value,rows:group.currentRows});}
function groupHash(group){return hash({groupId:group.groupId,revision:group.revision,status:group.status,value:group.value,rows:group.currentRows.map(({stockCount,countEffectiveDate,countUnit,...row})=>countUnit==='pair'?{...row,countUnit,stockCount,countEffectiveDate}:row)});}
function ensure(ledger,group,actor,env){
if(group.stored)return;
ledger.run('INSERT INTO inventory_manual_groups VALUES (?,?,?,?,?,?,?,?,?,?,?)',group.groupId,group.revision,group.status,group.creatorId,group.originalRows[0].actor,group.member,JSON.stringify(group.originalRows.map(row=>row.id)),JSON.stringify(group.currentRows.map(row=>row.id)),JSON.stringify(group.value),group.originalRows[0].created,env.now());
@@ -104,15 +112,15 @@ function register(ledger,groupId,actor,env){
group.creatorId=actor.id??'';group.member=ledger.memberFor(actor);ensure(ledger,group,actor,env);
}
function proposals(group,after){
const rows=group.currentRows.map(row=>({date:row.date,pocket:row.pocket,mg:-row.mg}));
if(after){const mg=Math.round(Number(after.grams)*1000);if(after.kind==='transfer')rows.push({date:after.date,pocket:after.pocket,mg:-mg},{date:after.date,pocket:after.to,mg});else rows.push({date:after.date,pocket:after.pocket,mg:after.kind==='decrease'?-mg:mg});}
const rows=group.currentRows.map(row=>({date:row.date,pocket:row.pocket,mg:-row.mg,stockCount:row.stockCount==null?null:-row.stockCount,countEffectiveDate:row.countEffectiveDate}));
if(after){const mg=Math.round(Number(after.grams)*1000),count=after.stockCount??null;if(after.kind==='transfer')rows.push({date:after.date,pocket:after.pocket,mg:-mg,stockCount:after.countFrom?-count:null},{date:after.date,pocket:after.to,mg,stockCount:after.countTo?count:null});else rows.push({date:after.date,pocket:after.pocket,mg:after.kind==='decrease'?-mg:mg,stockCount:count===null?null:after.kind==='decrease'?-count:count});}
return rows;
}
function inventoryHash(ledger,group,after){
const pockets=[...new Set([...group.currentRows.map(row=>row.pocket),...(after?[after.pocket,...(after.to?[after.to]:[])]:[])])].sort();
const rows=ledger.rows('SELECT id,group_id,order_id,date,pocket,mg FROM movements ORDER BY rowid').filter(row=>pockets.includes(row.pocket));
const reserved=ledger.inventory().filter(row=>pockets.includes(row.pocket)).map(({pocket,reserved})=>({pocket,reserved}));
return hash({pockets,rows,reserved});
const counts=Counts.snapshot(ledger,pockets);return hash({pockets,rows,reserved,...(counts?{counts}:{})});
}
function validateFinal(ledger,deltas,env){
const dates=new Map();
@@ -122,14 +130,25 @@ function validateFinal(ledger,deltas,env){
const totals=new Map();
for(const [pocket,values] of dates){let balance=0;for(const [date,mg] of [...values].sort(([a],[b])=>a.localeCompare(b))){balance+=mg;if(!Number.isSafeInteger(balance))env.fail('库存克重超出支持范围');if(balance<0)env.fail(`${ledger.pocketLabel(pocket)}在${date}库存不足,不能更正`);}totals.set(pocket,balance);}
for(const row of ledger.inventory())if((totals.get(row.pocket)??0)<row.reserved)env.fail(`${ledger.pocketLabel(row.pocket)}可用库存不足,已有订单占用${grams(row.reserved)}g`);
ledger.validateCountInventory(deltas);
}
function afterValue(input,before,env){
const kind=env.pick(input.kind,['increase','decrease','transfer'],'库存动作'),date=env.day(input.date);
function afterValue(ledger,input,before,group,env){
const kind=env.pick(input.kind,['increase','decrease','transfer',...(before.kind==='adjustment'?['adjustment']:[])],'库存动作'),date=env.day(input.date);
const pocket=env.validatePocket(input.pocket,{original:before.pocket});
const mg=env.weight(input.grams,'克重');if(mg<=0)env.fail('克重须大于0');
if(kind==='adjustment'&&!/^-?\d+(?:\.\d{1,3})?$/.test(String(input.grams)))env.fail('克重须为最多3位小数的数字');
const mg=kind==='adjustment'?Math.round(Number(input.grams)*1000):env.weight(input.grams,'克重');if(!Number.isSafeInteger(mg)||Math.abs(mg)>1e11)env.fail('克重无效');
const to=kind==='transfer'?env.validatePocket(input.to,{original:before.to,name:'目标货盘'}):'';if(to===pocket)env.fail('来源和目标货盘不能相同');
const note=env.text(input.note,'备注',200,true),cost=input.cost===undefined?before.cost:input.cost===null||input.cost===''?'':(env.money(input.cost,'采购金额(仅留档)')/100).toFixed(2);
return {kind,date,pocket,to,grams:grams(mg),note,cost};
const countFrom=ledger.pocket(pocket)?.countUnit==='pair',countTo=to&&ledger.pocket(to)?.countUnit==='pair',countPocket=countFrom?pocket:countTo?to:pocket;
const legacy=group.currentRows.some(row=>ledger.pocket(row.pocket)?.countUnit==='pair'&&row.stockCount==null);
if(legacy){
Counts.verifyLegacy(ledger,group.currentRows,input);
if(pocket!==before.pocket||to!==before.to||input.stockCount!==undefined&&input.stockCount!==null&&input.stockCount!=='')env.fail('启用前的未知对数流水仅可更正原货盘克重;变更成品对数请登记当天数量调整');
}
const stockCount=legacy?null:ledger.validateStockCount(countPocket,input.stockCount,{original:before.stockCount??null,signed:kind==='adjustment',allowZero:kind==='adjustment'});
if(kind==='adjustment'&&date!==env.today())env.fail('对数调整请使用今天的日期');
if(mg<0&&kind!=='adjustment'||!mg&&(stockCount===null||!stockCount))env.fail('克重须大于0;仅对数调整可填写0g');
return {kind,date,pocket,to,grams:grams(mg),...(stockCount===null?{}:{stockCount,countFrom:!!countFrom,countTo:!!countTo}),note,cost};
}
function assertVersion(group,revision,env){if(!Number.isSafeInteger(revision)||revision!==group.revision)env.fail('库存记录已有更正,请刷新后重试',409);}
function publicRequest(ledger,row,actor,env){
@@ -137,11 +156,11 @@ function publicRequest(ledger,row,actor,env){
const currentHash=inventoryHash(ledger,group,after);
return {id:row.id,groupId:row.group_id,action:row.action,revision:row.revision,groupRevision:row.group_revision,status:row.status,reason:row.reason,before:JSON.parse(row.before_value),after,
requesterName:row.requester_name,requesterMember:row.requester_member,created:row.created,reviewerName:row.reviewer_name,reviewed:row.reviewed,note:row.note,
stale:row.status==='pending'&&stale,staleReason:row.status==='pending'&&stale?'原手动库存记录已更正或删除,请驳回后重新申请':'',inventoryChanged:currentHash!==row.inventory_hash,inventoryRevision:currentHash,canApprove:actor.role==='owner'&&row.status==='pending'&&!stale};
...Counts.legacyInfo(ledger,group.currentRows),stale:row.status==='pending'&&stale,staleReason:row.status==='pending'&&stale?'原手动库存记录已更正或删除,请驳回后重新申请':'',inventoryChanged:currentHash!==row.inventory_hash,inventoryRevision:currentHash,canApprove:actor.role==='owner'&&row.status==='pending'&&!stale};
}
function detail(ledger,id,actor,env){
const group=state(ledger,id,actor,env),allowed=group.canManage&&group.status!=='deleted'&&!group.pending;
return {groupId:group.groupId,revision:group.revision,status:group.status,manual:group.manual,canEdit:allowed,canDelete:allowed,requiresApproval:actor.role==='assistant',values:group.value,movements:group.currentRows,pending:group.pending?publicRequest(ledger,group.pending,actor,env):null};
return {groupId:group.groupId,revision:group.revision,status:group.status,manual:group.manual,canEdit:allowed,canDelete:allowed,requiresApproval:actor.role==='assistant',...Counts.legacyInfo(ledger,group.currentRows),values:group.value,movements:group.currentRows,pending:group.pending?publicRequest(ledger,group.pending,actor,env):null};
}
function decorate(ledger,rows,actor,env,{shared=false}={}){
const cache=new Map();return rows.map(row=>{
@@ -152,7 +171,7 @@ function decorate(ledger,rows,actor,env,{shared=false}={}){
const allowed=!foreign&&manual&&current&&group.canManage&&group.status!=='deleted'&&!group.pending;
const pendingRequestId=!foreign&&group.pending&&(actor?.role==='owner'||group.pending.requester_id===actor?.id)?group.pending.id:null;
// 共享盘点仅给出数量、原备注和经办人;不附带他人的成本、业务ID或私有申请内容。
const source=foreign?{id:row.id,group_id:row.group_id,date:row.date,pocket:row.pocket,mg:row.mg,kind:row.kind,note:row.note,actor:row.actor,created:row.created}:row;
const source=foreign?{id:row.id,group_id:row.group_id,date:row.date,pocket:row.pocket,mg:row.mg,stockCount:row.stockCount??null,countUnit:row.countUnit??null,countEffectiveDate:row.countEffectiveDate??null,kind:row.kind,note:row.note,actor:row.actor,created:row.created}:row;
return {...source,groupId:group.groupId,revision:group.revision,manual,current,status:group.status,reversal:link?.role==='reversal',canEdit:allowed,canDelete:allowed,pendingRequestId,pendingApproval:!!group.pending};
});
}
@@ -160,15 +179,16 @@ function append(ledger,group,after,actor,env){
const generation=group.revision+1,created=env.now(),reversalGroup=randomUUID(),newGroup=randomUUID(),current=[];
const insert=(input,role)=>{
const id=randomUUID();ledger.run('INSERT INTO movements VALUES (?,?,?,?,?,?,?,?,?,?,?)',id,input.group,null,input.date,input.pocket,input.mg,input.kind,input.note,input.cost??null,actor.name,created);
ledger.attachMovementCount(id,input.stockCount,{effectiveDate:input.countEffectiveDate});
ledger.assignMember('movement',id,group.member);ledger.run('INSERT INTO inventory_manual_rows VALUES (?,?,?,?)',id,group.groupId,generation,role);return id;
};
for(const row of group.currentRows)insert({group:reversalGroup,date:row.date,pocket:row.pocket,mg:-row.mg,kind:'manual_reversal',note:'手动库存更正冲回:'+group.groupId},'reversal');
for(const row of group.currentRows)insert({group:reversalGroup,date:row.date,pocket:row.pocket,mg:-row.mg,stockCount:row.stockCount==null?null:-row.stockCount,countEffectiveDate:row.countEffectiveDate,kind:'manual_reversal',note:'手动库存更正冲回:'+group.groupId},'reversal');
if(after){
const mg=env.weight(after.grams),cost=after.cost===''?null:env.money(after.cost);
const mg=after.kind==='adjustment'?Math.round(Number(after.grams)*1000):env.weight(after.grams),cost=after.cost===''?null:env.money(after.cost),count=after.stockCount??null;
if(after.kind==='transfer'){
current.push(insert({group:newGroup,date:after.date,pocket:after.pocket,mg:-mg,kind:'transfer',note:after.note},'effective'));
current.push(insert({group:newGroup,date:after.date,pocket:after.to,mg,kind:'transfer',note:after.note},'effective'));
}else current.push(insert({group:newGroup,date:after.date,pocket:after.pocket,mg:after.kind==='decrease'?-mg:mg,kind:after.kind,note:after.note,cost},'effective'));
current.push(insert({group:newGroup,date:after.date,pocket:after.pocket,mg:-mg,stockCount:after.countFrom?-count:null,kind:'transfer',note:after.note},'effective'));
current.push(insert({group:newGroup,date:after.date,pocket:after.to,mg,stockCount:after.countTo?count:null,kind:'transfer',note:after.note},'effective'));
}else current.push(insert({group:newGroup,date:after.date,pocket:after.pocket,mg:after.kind==='decrease'?-mg:mg,stockCount:count===null?null:after.kind==='decrease'?-count:count,kind:after.kind,note:after.note,cost},'effective'));
}
validateFinal(ledger,[],env);
const updated=ledger.run('UPDATE inventory_manual_groups SET revision=?,status=?,current_ids=?,value=?,updated=? WHERE group_id=? AND revision=?',generation,after?'modified':'deleted',JSON.stringify(current),JSON.stringify(after??group.value),created,group.groupId,group.revision);
@@ -179,9 +199,11 @@ function change(ledger,id,action,input,actor,env){return atomic(ledger,()=>{
active(actor,env);object(input,env);const group=state(ledger,id,actor,env);
if(!group.manual)env.fail('只能修改或删除独立手动库存记录;订单和自动流水请回原业务处理',403);
if(!group.canManage)env.fail('只能修改或删除本人创建的手动库存记录',403);
if(group.value.kind==='adjustment'&&actor.role!=='owner')env.fail('盘点调整由麦麦账号完成,助理不能修改或删除',403);
assertVersion(group,input.revision,env);if(group.status==='deleted')env.fail('这组库存记录已经删除',409);if(group.pending)env.fail('这组库存有待审批申请,请先由麦麦处理',409);
if(action==='delete'&&input.verified!==true)env.fail('请确认删除这组手动库存记录');
const after=action==='delete'?null:afterValue(input,group.value,env),reason=env.text(input.reason,'说明',200,true)||(action==='delete'?'删除库存记录':'修改库存记录');
Counts.verifyLegacy(ledger,group.currentRows,input);
const after=action==='delete'?null:afterValue(ledger,input,group.value,group,env),reason=env.text(input.reason,'说明',200,true)||(action==='delete'?'删除库存记录':'修改库存记录');
validateFinal(ledger,proposals(group,after),env);ensure(ledger,group,actor,env);
if(actor.role==='owner'){
append(ledger,group,after,actor,env);ledger.audit('inventory-manual:'+group.groupId,action==='delete'?'删除手动库存记录':'修改手动库存记录',actor,{groupId:group.groupId,revision:group.revision,reason,before:group.value,after,notice:'原流水保留,追加整组冲正及有效记录;不改变订单、收付款或利润'});
@@ -213,6 +235,7 @@ function approve(ledger,id,input,actor,env){return atomic(ledger,()=>{
if(group.revision!==row.group_revision||groupHash(group)!==row.group_hash)env.fail('原手动库存记录已变,这份申请已过期,请驳回后重新申请',409);
if(typeof input.inventoryRevision!=='string'||input.inventoryRevision!==inventoryHash(ledger,group,after))env.fail('库存或订单占用已有新变动,请重新读取申请后核对批准',409);
if(input.verified!==true)env.fail('请核对修改前后库存,再确认批准');
Counts.verifyLegacy(ledger,group.currentRows,input);
validateFinal(ledger,proposals(group,after),env);append(ledger,group,after,actor,env);
const reviewed=env.now(),note=env.text(input.note,'审批意见',200,true);
const result=ledger.run("UPDATE inventory_changes SET status='approved',revision=revision+1,reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=? AND status='pending' AND revision=?",actor.id,actor.name,reviewed,note,id,row.revision);if(result.changes!==1)env.fail('这份库存申请已处理,请刷新',409);