'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); function active(actor,env){if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号处理库存记录',403);} function owner(actor,env){active(actor,env);if(actor.role!=='owner')env.fail('库存修改和删除申请必须由麦麦审批',403);} function object(input,env){if(!input||typeof input!=='object'||Array.isArray(input))env.fail('库存更正内容无效');} function atomic(ledger,fn){ ledger.db.exec('SAVEPOINT inventory_change_action'); try{const result=fn();ledger.db.exec('RELEASE inventory_change_action');return result;} catch(error){ledger.db.exec('ROLLBACK TO inventory_change_action');ledger.db.exec('RELEASE inventory_change_action');throw error;} } function initialize(ledger){ledger.db.exec(` CREATE TABLE IF NOT EXISTS inventory_manual_groups( group_id TEXT PRIMARY KEY,revision INTEGER NOT NULL DEFAULT 1,status TEXT NOT NULL CHECK(status IN ('active','modified','deleted')), creator_id TEXT NOT NULL,creator_name TEXT NOT NULL,member TEXT NOT NULL,original_ids TEXT NOT NULL,current_ids TEXT NOT NULL,value TEXT NOT NULL, created TEXT NOT NULL,updated TEXT NOT NULL); CREATE TABLE IF NOT EXISTS inventory_manual_rows( movement_id TEXT PRIMARY KEY REFERENCES movements(id),group_id TEXT NOT NULL REFERENCES inventory_manual_groups(group_id), generation INTEGER NOT NULL,role TEXT NOT NULL CHECK(role IN ('effective','reversal'))); CREATE INDEX IF NOT EXISTS ix_inventory_manual_rows_group ON inventory_manual_rows(group_id); CREATE TABLE IF NOT EXISTS inventory_changes( id TEXT PRIMARY KEY,group_id TEXT NOT NULL REFERENCES inventory_manual_groups(group_id),group_revision INTEGER NOT NULL, action TEXT NOT NULL CHECK(action IN ('update','delete')),revision INTEGER NOT NULL DEFAULT 1, reason TEXT NOT NULL,before_value TEXT NOT NULL,after_value TEXT,group_hash TEXT NOT NULL,inventory_hash TEXT NOT NULL, status TEXT NOT NULL CHECK(status IN ('pending','approved','rejected')), requester_id TEXT NOT NULL,requester_name TEXT NOT NULL,requester_member TEXT NOT NULL,created TEXT NOT NULL, reviewer_id TEXT,reviewer_name TEXT,reviewed TEXT,note TEXT NOT NULL DEFAULT ''); CREATE UNIQUE INDEX IF NOT EXISTS ix_inventory_change_pending ON inventory_changes(group_id) WHERE status='pending'; 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&&(!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; 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; 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||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])); const stored=new Map(ledger.rows('SELECT * FROM inventory_manual_groups').map(row=>[row.group_id,row])); const rawIds=new Set(candidates.map(row=>row.group_id)),rawGroups=new Map(); for(const row of allRows)if(rawIds.has(row.group_id)){if(!rawGroups.has(row.group_id))rawGroups.set(row.group_id,[]);rawGroups.get(row.group_id).push(row);} const trusted=new Map(),actions=new Map(); for(const row of candidates){ const link=links.get(row.id);if(link?.role==='reversal')continue; const groupId=link?.group_id??row.group_id; if(!trusted.has(groupId)){ const group=stored.get(groupId),original=group?JSON.parse(group.original_ids).map(id=>byId.get(id)):rawGroups.get(groupId)||[]; const current=group?JSON.parse(group.current_ids).map(id=>byId.get(id)):original; // 与手动详情相同的可信边界;已删除组的空 current_ids 仍保留历史手动身份。 trusted.set(groupId,!!(group?JSON.parse(group.value):normalized(original))&&original.every(item=>item&&visibleIds.has(item.id))&&!!normalized(original)&¤t.every(Boolean)); } if(!trusted.get(groupId))continue; // 每一代流水按当时动作分类,不能用整组更正后的最新 value 重解释原始行。 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; } function historicalCreator(ledger,groupId){ for(const row of ledger.rows("SELECT detail FROM audit WHERE entity='inventory' AND action='库存变动' AND detail LIKE ? ORDER BY id DESC",'%'+groupId+'%')){ let value;try{value=JSON.parse(row.detail);}catch{continue;} if(value.group!==groupId)continue; const identity=value.actorIdentity;if(identity&&typeof identity.id==='string'&&['owner','assistant'].includes(identity.role))return identity.id; } return ''; } function state(ledger,id,actor,env,{internal=false}={}){ if(!internal)active(actor,env); const link=ledger.one('SELECT * FROM inventory_manual_rows WHERE movement_id=?',id); 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); 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); 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)&¤tRows.every(Boolean); const creatorId=stored?.creator_id??historicalCreator(ledger,groupId),member=stored?.member??ledger.entityMember('movement',originalRows[0].id)??'owner'; const pending=ledger.one("SELECT * FROM inventory_changes WHERE group_id=? AND status='pending'",groupId)||null; 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.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()); for(const row of group.currentRows)ledger.run("INSERT INTO inventory_manual_rows VALUES (?,?,1,'effective')",row.id,group.groupId); } function register(ledger,groupId,actor,env){ const group=state(ledger,groupId,actor,env);if(!group.manual)return; 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,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})); const counts=Counts.snapshot(ledger,pockets);return hash({pockets,rows,reserved,...(counts?{counts}:{})}); } function validateFinal(ledger,deltas,env){ const dates=new Map(); for(const row of [...ledger.rows('SELECT date,pocket,SUM(mg) AS mg FROM movements GROUP BY pocket,date'),...deltas]){ const values=dates.get(row.pocket)??new Map();values.set(row.date,(values.get(row.date)??0)+row.mg);dates.set(row.pocket,values); } 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)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); 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){ const group=state(ledger,row.group_id,actor,env),after=row.after_value===null?null:JSON.parse(row.after_value),stale=group.revision!==row.group_revision||groupHash(group)!==row.group_hash; 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, ...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',...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=>{ const key=ledger.one('SELECT group_id FROM inventory_manual_rows WHERE movement_id=?',row.id)?.group_id??row.group_id; const foreign=shared&&!ledger.canAccess('movement',row.id,actor); if(!cache.has(key))cache.set(key,state(ledger,row.id,actor,env,{internal:shared})); const group=cache.get(key),link=ledger.one('SELECT role FROM inventory_manual_rows WHERE movement_id=?',row.id),current=group.currentRows.some(item=>item.id===row.id),manual=group.manual&&link?.role!=='reversal'; const allowed=!foreign&&manual&¤t&&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,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}; }); } 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,stockCount:row.stockCount==null?null:-row.stockCount,countEffectiveDate:row.countEffectiveDate,kind:'manual_reversal',note:'手动库存更正冲回:'+group.groupId},'reversal'); if(after){ 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,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); if(updated.changes!==1)env.fail('库存记录已由其他操作更正,请刷新',409); const date=[...group.currentRows.map(row=>row.date),...(after?[after.date]:[])].sort()[0];ledger.dirtyInventory(date); } 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('请确认删除这组手动库存记录'); 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:'原流水保留,追加整组冲正及有效记录;不改变订单、收付款或利润'}); return {groupId:group.groupId,applied:true,pending:false,group:detail(ledger,group.groupId,actor,env)}; } const requestId=randomUUID(),created=env.now(); ledger.run("INSERT INTO inventory_changes(id,group_id,group_revision,action,reason,before_value,after_value,group_hash,inventory_hash,status,requester_id,requester_name,requester_member,created) VALUES (?,?,?,?,?,?,?,?,?,'pending',?,?,?,?)",requestId,group.groupId,group.revision,action,reason,JSON.stringify(group.value),after===null?null:JSON.stringify(after),groupHash(group),inventoryHash(ledger,group,after),actor.id,actor.name,ledger.memberFor(actor),created); ledger.audit('inventory-manual:'+group.groupId,action==='delete'?'申请删除手动库存':'申请修改手动库存',actor,{requestId,groupId:group.groupId,revision:group.revision,reason,before:group.value,after,notice:'申请不改变库存,由麦麦审批后原子生效;当天也须审批'}); return {groupId:group.groupId,applied:false,pending:true,requestId,request:read(ledger,requestId,actor,env),group:detail(ledger,group.groupId,actor,env)}; });} function requestRow(ledger,id,actor,env){ active(actor,env);const row=ledger.one('SELECT * FROM inventory_changes WHERE id=?',id); if(!row||actor.role!=='owner'&&row.requester_id!==actor.id)env.fail('库存申请不存在或无权访问',404);return row; } function read(ledger,id,actor,env){return publicRequest(ledger,requestRow(ledger,id,actor,env),actor,env);} function list(ledger,query,actor,env){ active(actor,env);const status=query.status??'pending';env.pick(status,['pending','approved','rejected','all'],'审批状态'); const rows=ledger.rows('SELECT * FROM inventory_changes ORDER BY created DESC,rowid DESC').filter(row=>actor.role==='owner'||row.requester_id===actor.id); const requests=rows.filter(row=>status==='all'||row.status===status).map(row=>publicRequest(ledger,row,actor,env)); return {requests,counts:Object.fromEntries(['pending','approved','rejected'].map(key=>[key,rows.filter(row=>row.status===key).length]))}; } function decision(ledger,id,input,actor,env){ owner(actor,env);object(input,env);const row=requestRow(ledger,id,actor,env); if(row.status!=='pending'||!Number.isSafeInteger(input.revision)||input.revision!==row.revision)env.fail('库存申请已经处理或版本已变,请刷新',409);return row; } function approve(ledger,id,input,actor,env){return atomic(ledger,()=>{ const row=decision(ledger,id,input,actor,env),group=state(ledger,row.group_id,actor,env),after=row.after_value===null?null:JSON.parse(row.after_value); if(after){ledger.validatePocket(after.pocket,{original:group.value.pocket});if(after.to)ledger.validatePocket(after.to,{original:group.value.to,name:'目标货盘'});} 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); ledger.audit('inventory-manual:'+row.group_id,row.action==='delete'?'同意删除手动库存':'同意修改手动库存',actor,{requestId:id,groupId:row.group_id,reason:row.reason,before:JSON.parse(row.before_value),after,requestedBy:row.requester_id,reviewed,note,notice:'原流水保留,追加整组冲正及有效记录'}); return {groupId:row.group_id,applied:true,pending:false,requestId:id,request:read(ledger,id,actor,env),group:detail(ledger,row.group_id,actor,env)}; });} function reject(ledger,id,input,actor,env){return atomic(ledger,()=>{ const row=decision(ledger,id,input,actor,env),note=env.text(input.note,'驳回意见',200),reviewed=env.now(); ledger.run("UPDATE inventory_changes SET status='rejected',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); ledger.audit('inventory-manual:'+row.group_id,'驳回库存更正申请',actor,{requestId:id,groupId:row.group_id,action:row.action,note,reviewed,notice:'不改变库存'}); return {groupId:row.group_id,applied:false,pending:false,requestId:id,request:read(ledger,id,actor,env),group:detail(ledger,row.group_id,actor,env)}; });} module.exports={initialize,register,detail,decorate,manualMovementKinds,list,read,change,approve,reject};