Files
weiguang-jewelry-ledger/新账系统/recovery-changes.js
T

246 lines
30 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'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'),Counts=require('./inventory-counts');
const CreditCardRates=require('./credit-card-rates');
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;}}
function initialize(l){
const columns=l.rows('PRAGMA table_info(recoveries)').map(row=>row.name);
for(const [name,definition] of Object.entries({status:"TEXT NOT NULL DEFAULT 'active'",cancelled_at:"TEXT NOT NULL DEFAULT ''",updated:"TEXT NOT NULL DEFAULT ''"}))if(!columns.includes(name))l.db.exec(`ALTER TABLE recoveries ADD COLUMN ${name} ${definition}`);
l.db.exec(`CREATE TABLE IF NOT EXISTS recovery_changes(
id TEXT PRIMARY KEY,recovery_id TEXT NOT NULL REFERENCES recoveries(id),recovery_revision INTEGER NOT NULL,revision INTEGER NOT NULL DEFAULT 1,
action TEXT NOT NULL CHECK(action IN ('update','cancel')),status TEXT NOT NULL CHECK(status IN ('pending','approved','rejected')),
reason TEXT NOT NULL,before_value TEXT NOT NULL,after_value TEXT,summary TEXT NOT NULL,dependency TEXT NOT NULL,snapshot TEXT NOT NULL,
requester_id TEXT NOT NULL,requester_name TEXT NOT NULL,requester_member TEXT NOT NULL,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_recovery_changes_pending ON recovery_changes(recovery_id) WHERE status='pending';`);
}
function active(actor,env){if(!actor||!['owner','assistant'].includes(actor.role))env.fail('请使用麦麦或助理账号处理回收记录',403);}
function object(input,env){if(!input||typeof input!=='object'||Array.isArray(input))env.fail('回收更正内容无效');}
function rowFor(l,id,actor,env){
active(actor,env);const row=l.one('SELECT * FROM recoveries WHERE id=?',id);
if(!row||actor.role!=='owner'&&(row.member!==l.memberFor(actor)||!l.canAccess('recovery',id,actor)))env.fail('回收记录不存在或无权访问',404);
if(row.order_id&&!l.canAccess('order',row.order_id,actor)||row.purchase_id&&!l.canAccess('material_purchase',row.purchase_id,actor))env.fail('关联记录不存在或无权访问',404);
if(l.teamMode&&([['recovery',row.id],['order',row.order_id],['material_purchase',row.purchase_id]].some(([kind,id])=>id&&l.entityMember(kind,id)!==row.member)))env.fail('回收与关联记录归属不一致,请先核对原关联',409);
return row;
}
function pending(l,id){return l.one("SELECT * FROM recovery_changes WHERE recovery_id=? AND status='pending'",id)||null;}
function materialHook(){try{return require('./recovery-material');}catch(e){if(e.code==='MODULE_NOT_FOUND'&&e.message.includes("'./recovery-material'"))return null;throw e;}}
function usageRows(l,row,after,env){
if(!row.purchase_id)return [];
const purchase=l.one('SELECT * FROM material_purchases WHERE id=?',row.purchase_id);if(!purchase||purchase.deleted_at)return [];
const personal=materialHook()?.blockedUsages?.(l,purchase.id);
if(Array.isArray(personal))return personal;
// 历史共享采购只按原池是否仍有足够金料检查,不把旧来源迁成个人批次。
const pool=Material.readPool(l,purchase.pool_id,env,{internal:true});
const own=l.rows('SELECT mg FROM material_pool_usages WHERE order_id=? AND active=1 AND pool_id=?',row.order_id??'',purchase.pool_id);
const remainingUsed=pool.usedMg-(!after?sum(own,'mg'):0),newSameDate=after?.date===purchase.pool_id?after.purchaseMg:0;
const affected=[];
if(pool.totalMg-purchase.mg+newSameDate<remainingUsed)affected.push(...pool.usages.filter(usage=>usage.active&&(!after?usage.order_id!==row.order_id:true)));
if(Rolling.enabled(l))for(const day of l.rows('SELECT date FROM material_rolling_days WHERE date>=? ORDER BY date',purchase.date)){
const current=Rolling.readPool(l,day.date,env,{internal:true,live:true}),delta=(after&&after.date<=day.date?after.purchaseMg:0)-purchase.mg;
if(current.remainingMg+delta<0)affected.push(...current.usages.filter(usage=>usage.active&&(!after?usage.order_id!==row.order_id:true)));
}
return [...new Map(affected.map(usage=>[usage.id,usage])).values()].map(usage=>({orderId:usage.order_id,number:usage.number,mg:usage.mg,...(usage.price_lock_id?{priceLockId:usage.price_lock_id}:{})}));
}
function visibleUsages(l,rows,actor){return rows.map(row=>{
const own=row.priceLockId?l.canAccess('price_lock',row.priceLockId,actor):row.orderId&&l.canAccess('order',row.orderId,actor);
return actor.role==='owner'||own?row:{mg:row.mg,anonymous:true};
});}
function blocking(l,row,after,actor,env){
const purchase=row.purchase_id&&l.one('SELECT * FROM material_purchases WHERE id=?',row.purchase_id),hook=materialHook();
const personal=purchase?hook?.blockedUsages?.(l,purchase.id):null;
const used=Array.isArray(personal)?sum(personal,'mg'):0;
const blocked=Array.isArray(personal)?used>0&&(!after||after.purchaseMg<used||after.date!==purchase.date)?personal:[]:usageRows(l,row,after,env);
const rows=visibleUsages(l,blocked,actor);
if(after&&rows.length){const error=new Error('回收金料已有用料,不能移走或减少到低于已用量;关联用料:'+rows.map(r=>r.number||r.priceLockId||'其他成员订单').join('、'));error.status=409;error.code='RECOVERY_MATERIAL_IN_USE';error.blockedUsages=rows;throw error;}
return blocked;
}
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;
const customerMaterialEvents=l.rows('SELECT * FROM customer_material_events WHERE recovery_id=? ORDER BY rowid',row.id);if(customerMaterialEvents.length)tables.customerMaterialEvents=customerMaterialEvents;
return {record:row,order,...tables};
}
function dependency(l,row){const counts=Counts.snapshot(l,l.pocketCatalog().map(row=>row.key)),customerMaterials=l.rows('SELECT id FROM customer_material_events ORDER BY rowid');return hash({snapshot:snapshot(l,row),pool:Rolling.dependency(l),inventory:l.rows('SELECT id,date,pocket,mg FROM movements ORDER BY rowid'),...(customerMaterials.length?{customerMaterials}:{}),...(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);
const summary=JSON.parse(row.summary);summary.blockedUsages=visibleUsages(l,summary.blockedUsages??[],actor);
return {id:row.id,recoveryId:row.recovery_id,revision:row.revision,recoveryRevision:row.recovery_revision,action:row.action,status:row.status,reason:row.reason,
before:JSON.parse(row.before_value),after:row.after_value?JSON.parse(row.after_value):null,summary,requesterName:row.requester_name,requesterMember:row.requester_member,member:row.member,
created:row.created,reviewerName:row.reviewer_name,reviewed:row.reviewed,note:row.note,stale,canApprove:actor.role==='owner'&&row.status==='pending'&&!stale};
}
function projection(l,row,actor,env){
const waiting=pending(l,row.id),belongs=actor?.role==='owner'||row.member===l.memberFor(actor)&&l.canAccess('recovery',row.id,actor),enabled=belongs&&row.status!=='cancelled'&&!waiting;
return {status:row.status??'active',cancelledAt:row.cancelled_at??'',canEdit:enabled,canCancel:enabled,pendingRequestId:waiting?.id??null};
}
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(),...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'}));
// 对数按自己的生效日净额冲正;旧重量流水没有对数时保持未知,不从克重或工费件数推算。
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){for(const old of Recoveries.oldInventory(after))deltas.push({date:after.date,...old,kind:'recovery_change_old'});if(after.mode==='exchange')for(const product of Recoveries.products(after))if(product.pocket)deltas.push({date:after.date,pocket:product.pocket,mg:-product.quantity,stockCount:product.stockCount==null?null:-product.stockCount,kind:'recovery_change_sale'});}
return deltas;
}
function validateInventory(l,deltas,env){
const grouped=new Map();
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';
const already=new Set(l.rows('SELECT target FROM corrections WHERE type=?',type).map(r=>r.target));
for(const row of l.rows('SELECT * FROM '+table+' WHERE order_id=?',id))if(row.amount>0&&!already.has(row.id))l.run('INSERT INTO corrections VALUES (?,?,?,?,?)',row.id,type,reason,actor.name,env.now());
for(const row of l.rows(`SELECT date,${key}${isPayment?',kind':''},SUM(amount) AS amount FROM ${table} WHERE order_id=? GROUP BY date,${key}${isPayment?',kind':''} HAVING SUM(amount)<>0`,id)){
const newId=randomUUID(),note='更正冲回:回收专用更正;'+reason;
if(isPayment)l.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',newId,id,row.date,row.kind,-row.amount,row.account,note,actor.name,env.now());
else l.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',newId,id,row.date,-row.amount,row.payer,note,actor.name,env.now());
if(row.amount<0)l.run('INSERT INTO corrections VALUES (?,?,?,?,?)',newId,type,'回收更正对冲行,不是新增收付款或费用',actor.name,env.now());
}
}
function purchaseChange(l,row,after,actor,env){
const old=row.purchase_id&&l.one('SELECT * FROM material_purchases WHERE id=?',row.purchase_id);
if(old){
if(l.teamMode)TeamFunds.activate(l,'material_purchase',old.id,{legacy:true},actor,env);
if(after?.purchaseMg){
const allocations=[...(after.offsetAmount?[{payer:row.member,amount:after.offsetAmount,source:'offset'}]:[]),...(after.cashPayment?[{payer:after.payer,amount:after.cashPayment,source:'cash'}]:[])];
if(sum(allocations,'amount')!==after.purchaseAmount)env.fail('回收购料现金与抵扣不守恒');
l.run("UPDATE material_purchases SET pool_id=?,date=?,mg=?,amount=?,payer=?,deleted_at='',revision=revision+1,updated=? WHERE id=?",after.date,after.date,after.purchaseMg,after.purchaseAmount,after.payer,env.now(),old.id);
l.run('UPDATE recovery_purchase_sources SET cash_amount=?,offset_amount=?,allocations=? WHERE purchase_id=?',after.cashPayment,after.offsetAmount,JSON.stringify(allocations),old.id);
l.run("INSERT OR IGNORE INTO material_purchase_payment_origins VALUES (?,'purchase')",old.id);
}else l.run('UPDATE material_purchases SET deleted_at=?,revision=revision+1,updated=? WHERE id=?',env.now(),env.now(),old.id);
}else if(after?.purchaseMg){
const allocations=[...(after.offsetAmount?[{payer:row.member,amount:after.offsetAmount,source:'offset'}]:[]),...(after.cashPayment?[{payer:after.payer,amount:after.cashPayment,source:'cash'}]:[])];
const made=Material.purchase(l,{date:after.date,grams:(after.purchaseMg/1000).toFixed(3),total:yuan(after.purchaseAmount),payer:after.payer,note:'回收更正 · '+row.number},actor,env,{member:row.member,source:{recoveryId:row.id,member:row.member,cashAmount:after.cashPayment,offsetAmount:after.offsetAmount,allocations}});
l.run('UPDATE recoveries SET purchase_id=? WHERE id=?',made.id,row.id);
}
return [...new Set([old?.pool_id,after?.purchaseMg?after.date:null].filter(Boolean))];
}
function appendOrder(l,row,after,actor,reason,env){
if(!row.order_id)return;
const id=row.order_id;
if(after)CreditCardRates.capture(l,'order',id,after.credit_card_rate_permille);
reverseRows(l,id,'payments',actor,reason,env);reverseRows(l,id,'expenses',actor,reason,env);
if(!after){l.run("UPDATE orders SET status='cancelled',fee_items='[]',reviewed_revision=0 WHERE id=?",id);Material.release(l,l.rawOrder(id),row.date,actor,env,{kind:'回收记录取消释放'});return;}
const input=Recoveries.orderInput(after),previous=l.rawOrder(id),lines=l.validateLines(input.lines,previous.lines,after.date,{orderId:id,member:row.member}),line=lines[0];
Recoveries.applyOrderMetadata(l,lines,after,row.id,env,id);
l.run("UPDATE orders SET date=?,customer=?,salesperson=?,note=?,lines=?,discount=?,total=?,rounding_mode=?,payment_account=?,fees_date=?,delivered_date=?,fee_items='[]',reviewed_revision=0 WHERE id=?",after.date,after.customer,after.salesperson,after.note,JSON.stringify(lines),after.discount,after.receivable,after.rounding_mode,after.payment_account,after.date,after.date,id);
const fees=[];for(const fee of after.exchange.fee_items){const expenseId=fee.amount?randomUUID():null;if(expenseId)l.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',expenseId,id,after.date,fee.amount,fee.payer,fee.note,actor.name,env.now());fees.push({...fee,status:'recorded',...(expenseId?{expense_id:expenseId}:{})});}
l.run('UPDATE orders SET fee_items=? WHERE id=?',JSON.stringify(fees),id);
if(after.cashReceipt){const payment={id:randomUUID(),date:after.date,kind:'receipt',amount:after.cashReceipt,account:after.payment_account};l.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',payment.id,id,payment.date,payment.kind,payment.amount,payment.account,'回收更正补记:'+reason,actor.name,env.now());l.recordCardFee(id,payment,actor,{payer:'owner',journal:false});}
}
function replaceJournal(l,row,after){
if(!row.order_id)return;
const id=row.order_id;for(const current of l.rows('SELECT date,SUM(sales) AS sales,SUM(goods) AS goods,SUM(expense) AS expense FROM journal WHERE order_id=? GROUP BY date',id))if(current.sales||current.goods||current.expense)l.journal(id,current.date,'回收专用更正冲回',-current.sales,-current.goods,-current.expense);
if(after){const order=l.detail(id);l.journal(id,after.date,'回收专用更正补记',after.receivable,order.goodsCost??order.knownGoodsCost,order.directCost);}
l.touch(id);
}
function financialInput(value){const {customer,salesperson,note,...rest}=value;return rest;}
function inventoryOnlyInput(value){const {old_pocket,old_stock_count,...rest}=financialInput(value);if(rest.exchange?.items)rest.exchange={...rest.exchange,items:rest.exchange.items.map(({old_pocket,old_stock_count,...item})=>item)};return rest;}
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);
return Counts.legacyInfo(l,[...Recoveries.products(q).filter(product=>product.stockCount==null).map(product=>({id:'',pocket:product.pocket,mg:product.quantity})),...Recoveries.oldInventory(q).filter(p=>p.stockCount==null).map(p=>({id:'',pocket:p.pocket,mg:p.mg}))]);
}
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)));
const inventoryOnly=!!after&&!metadataOnly&&hash(inventoryOnlyInput(Recoveries.inputFor(old)))===hash(inventoryOnlyInput(Recoveries.inputFor(after)));
verifyLegacyCount(l,row,after,input,env);
require('./customer-materials').apply(l,row.id,after,actor,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);
if(metadataOnly){if(row.order_id){l.run('UPDATE orders SET customer=?,salesperson=?,note=?,reviewed_revision=0 WHERE id=?',after.customer,after.salesperson,after.note,row.order_id);l.touch(row.order_id);}}
else{
if(!inventoryOnly){
if(!after&&row.purchase_id)materialHook()?.cancelPurchase?.(l,row.purchase_id);
appendOrder(l,row,after,actor,reason,env);const pools=purchaseChange(l,row,after,actor,env);
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.attachMovementCount(id,movement.stockCount,{effectiveDate:movement.countEffectiveDate??movement.date});l.assignMember('movement',id,row.member);}
l.validateCountInventory();
if(!inventoryOnly){replaceJournal(l,row,after);const hook=materialHook();hook?.recoveryUpdated?.(l,row.id,actor,env);}
else if(row.order_id&&(old.customer!==after.customer||old.salesperson!==after.salesperson||old.note!==after.note)){l.run('UPDATE orders SET customer=?,salesperson=?,note=?,reviewed_revision=0 WHERE id=?',after.customer,after.salesperson,after.note,row.order_id);l.touch(row.order_id);}
}
if(metadataOnly)l.run('UPDATE closes SET stale=1 WHERE date IN (?,?)',row.date,after.date);
else l.dirtyInventory([row.date,after?.date,...before.movements.map(r=>r.date)].filter(Boolean).sort()[0]);
l.syncTeamFunds(actor);
if(row.order_id){const order=l.detail(row.order_id);if(after&&(order.netReceived!==after.cashReceipt||order.balance!==0||order.profit!==null&&order.profit!==after.receivable-order.goodsCost-order.directCost)||!after&&(order.netReceived!==0||order.directCost!==0||order.profit!==0))env.fail('回收更正后关联订单核对未通过,操作已撤回',409);}
l.audit('recovery:'+row.id,after?'修改回收/置换记录':'取消回收/置换记录',actor,{reason,before,after:snapshot(l,l.one('SELECT * FROM recoveries WHERE id=?',row.id)),notice:'原身份与流水保留,追加冲正及补记;不是实际新增收款、退款或重复付款'});
return row.id;
},null));}
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决定,不能把试算许可当成落账权限。
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}));
for(const [index,product] of Recoveries.products(previous).entries())if(product.stockCount==null&&l.pocket(product.pocket)?.countUnit==='pair'){
const physical=product=>JSON.stringify([product.name,product.quantity,product.pocket,product.stockCount??null]);
if(physical(product)!==physical(Recoveries.products(after)[index]??{}))env.fail('启用前已交付的置换新货没有原始对数,只能更正资料和财务;成品变化请先核对实物,再登记今天的数量调整,不能补旧单对数重扣盘点基准');
}
for(const [i,old] of Recoveries.oldInventory(previous).entries())if(old.stockCount==null&&l.pocket(old.pocket)?.countUnit==='pair'){
const physical=value=>JSON.stringify([value?.pocket,value?.mg,value?.stockCount??null]);
if(physical(old)!==physical(Recoveries.oldInventory(after)[i]))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,...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,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)};
});}
function readRow(l,id,actor,env){active(actor,env);const row=l.one('SELECT * FROM recovery_changes WHERE id=?',id);if(!row||actor.role!=='owner'&&row.requester_id!==actor.id)env.fail('回收更正申请不存在或无权访问',404);rowFor(l,row.recovery_id,actor,env);return row;}
function read(l,id,actor,env){return dto(l,readRow(l,id,actor,env),actor,env);}
function list(l,query,actor,env){
active(actor,env);const status=env.pick(query.status??'pending',['pending','approved','rejected','all'],'申请状态'),member=l.queryMember(query,actor),rows=l.rows('SELECT * FROM recovery_changes ORDER BY created DESC,rowid DESC').filter(r=>(actor.role==='owner'||r.requester_id===actor.id&&r.member===l.memberFor(actor))&&(!member||r.member===member));
return {requests:rows.filter(r=>status==='all'||r.status===status).map(r=>dto(l,r,actor,env)),counts:Object.fromEntries(['pending','approved','rejected'].map(status=>[status,rows.filter(r=>r.status===status).length]))};
}
function decision(l,id,input,actor,env){active(actor,env);if(actor.role!=='owner')env.fail('回收更正申请由麦麦审批',403);object(input,env);const row=readRow(l,id,actor,env);if(row.status!=='pending'||input.revision!==row.revision||!Number.isSafeInteger(input.revision))env.fail('申请已经处理或版本已变,请刷新',409);return row;}
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,{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);});}
module.exports={initialize,projection,detail,quote,read,list,approve,reject,update:(l,id,input,actor,env)=>change(l,id,'update',input,actor,env),cancel:(l,id,input,actor,env)=>change(l,id,'cancel',input,actor,env)};