catch(error){ledger.db.exec('ROLLBACK TO order_cancellation_action');ledger.db.exec('RELEASE order_cancellation_action');throwerror;}
}
functioninitialize(ledger){ledger.db.exec(`
CREATE TABLE IF NOT EXISTS order_cancellations(
id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),order_revision INTEGER NOT NULL,
reason TEXT NOT NULL,snapshot TEXT NOT NULL,snapshot_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_role 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_order_cancellation_pending ON order_cancellations(order_id) WHERE status='pending';
CREATE INDEX IF NOT EXISTS ix_order_cancellation_status ON order_cancellations(status,created);
`);}
functionpending(ledger,id){returnledger.one("SELECT * FROM order_cancellations WHERE order_id=? AND status='pending'",id)||null;}
functionapproved(ledger,id){returnledger.one("SELECT * FROM order_cancellations WHERE order_id=? AND status='approved' ORDER BY created DESC LIMIT 1",id)||null;}
functioneligibility(ledger,order){
if(ledger.one('SELECT id FROM price_locks WHERE final_order_id=?',order.id)||order.lines.some(line=>line.materialAllocations))return'锁价关联订单本次不支持取消申请,请保留原采购与收退款记录';
for(consttableof['payments','expenses','settlements','journal','movements'])tables[table]=ledger.rows('SELECT * FROM '+table+' WHERE order_id=? ORDER BY rowid',id);
tables.corrections=ledger.rows('SELECT * FROM corrections WHERE target IN (SELECT id FROM payments WHERE order_id=? UNION SELECT id FROM expenses WHERE order_id=? UNION SELECT id FROM settlements WHERE order_id=?) ORDER BY rowid',id,id,id);
tables.materialUsages=ledger.rows('SELECT * FROM material_pool_usages WHERE order_id=? ORDER BY rowid',id);
constpriceLock=ledger.one('SELECT id FROM price_locks WHERE final_order_id=?',id)?.id||null;
return{order,...tables,priceLock};
}
functioninventoryReversal(ledger,id){returnledger.rows('SELECT date,pocket,-SUM(mg) AS mg FROM movements WHERE order_id=? GROUP BY date,pocket HAVING SUM(mg)<>0 ORDER BY date,pocket',id);}
constrequests=ledger.rows('SELECT * FROM order_cancellations WHERE order_id=? ORDER BY created DESC,rowid DESC',id).map(row=>rowDetail(ledger,row,actor));
constrows=ledger.rows('SELECT * FROM order_cancellations'+(status==='all'?'':' WHERE status=?')+' ORDER BY created DESC,rowid DESC',...(status==='all'?[]:[status]));
constcounts={pending:0,approved:0,rejected:0};for(constrowofledger.rows('SELECT status,COUNT(*) AS count FROM order_cancellations GROUP BY status'))counts[row.status]=row.count;
ledger.run("INSERT INTO order_cancellations(id,order_id,order_revision,reason,snapshot,snapshot_hash,status,requester_id,requester_name,requester_role,created) VALUES (?,?,?,?,?,?,'pending',?,?,?,?)",requestId,id,order.revision,explanation,JSON.stringify(saved),hash(data),actor.id,actor.name,actor.role,created);
for(constrowoforder.payments)if(row.amount>0&&!corrected.has(row.id)&&!row.reference.startsWith('更正冲回:'))ledger.run('INSERT INTO corrections VALUES (?,?,?,?,?)',row.id,'payment',reason,actor.name,env.now());
// 跨日更正的旧日正数与更正日负数也逐日归零,不能残留虚构收款。
for(constrowofledger.rows('SELECT date,kind,account,SUM(amount) AS amount FROM payments WHERE order_id=? GROUP BY date,kind,account HAVING SUM(amount)<>0 ORDER BY date,kind,account',order.id)){
constid=randomUUID();ledger.run('INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)',id,order.id,row.date,row.kind,-row.amount,row.account,'更正冲回:取消审批作废;'+reason,actor.name,env.now());
if(row.amount<0)ledger.run('INSERT INTO corrections VALUES (?,?,?,?,?)',id,'payment','作废更正的对冲记录,不是新增客户收付款',actor.name,env.now());
for(constrowoforder.expenses)if(row.amount>0&&!corrected.has(row.id)&&!row.note.startsWith('更正冲回:'))ledger.run('INSERT INTO corrections VALUES (?,?,?,?,?)',row.id,'expense',reason,actor.name,env.now());
for(constrowofledger.rows('SELECT date,payer,SUM(amount) AS amount FROM expenses WHERE order_id=? GROUP BY date,payer HAVING SUM(amount)<>0 ORDER BY date,payer',order.id)){
constid=randomUUID();ledger.run('INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)',id,order.id,row.date,-row.amount,row.payer,'更正冲回:取消审批作废;'+reason,actor.name,env.now());
// 跨日更正原先留下的负数需要正数对冲;该正数仍是更正,不是实际支出。
if(row.amount<0)ledger.run('INSERT INTO corrections VALUES (?,?,?,?,?)',id,'expense','作废更正的对冲记录,不是新增费用',actor.name,env.now());
ledger.run("UPDATE order_cancellations SET status='approved',reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=? AND status='pending'",actor.id,actor.name,reviewed,note,id);
ledger.run("UPDATE orders SET status='cancelled',reviewed_revision=0 WHERE id=?",order.id);
for(constentryofledger.rows('SELECT date,SUM(sales) AS sales,SUM(goods) AS goods,SUM(expense) AS expense FROM journal WHERE order_id=? GROUP BY date ORDER BY date',order.id))
if(after.netReceived!==0||after.directCost!==0||after.profit!==0||inventoryReversal(ledger,order.id).length||ledger.one('SELECT id FROM material_pool_usages WHERE order_id=? AND active=1',order.id))env.fail('作废后的财务、库存或用料校验未通过,本次审批已撤回',409);
ledger.run("UPDATE order_cancellations SET status='rejected',reviewer_id=?,reviewer_name=?,reviewed=?,note=? WHERE id=? AND status='pending'",actor.id,actor.name,reviewed,note,id);