增加订单退货退款售后、原成本回料及跨日损益核算

This commit is contained in:
summer committed 2026-11-10 02:54:58 +08:00
1 parent b6a0213a0c
commit dab735423e
24 files changed
+1048 -82

No files matched your search

+11 -8
View File
@@ -45,9 +45,9 @@ function remainingParts(purchases,consumed){
if(skip)throw new Error('料池结转资金不守恒');return result;
}
function legacyOpening(l,cutover,env){
const ids=l.rows("SELECT DISTINCT pool_id FROM material_purchases WHERE pool_id<? AND deleted_at='' UNION SELECT DISTINCT pool_id FROM material_pool_usages WHERE pool_id<? ORDER BY pool_id",cutover,cutover).map(r=>r.pool_id);
const ids=l.rows("SELECT DISTINCT pool_id FROM material_purchases WHERE pool_id<? AND deleted_at='' UNION SELECT DISTINCT pool_id FROM material_pool_usages WHERE pool_id<? UNION SELECT date AS pool_id FROM material_rolling_returns WHERE date<? AND order_id IN (SELECT order_id FROM order_after_sales) ORDER BY pool_id",cutover,cutover,cutover).map(r=>r.pool_id);
const pools=ids.map(id=>legacy().readPool(l,id,env,{internal:true}));
const returned=l.rows('SELECT * FROM material_rolling_returns WHERE origin_pool_id<>? AND origin_pool_id<? AND same_day=0','',cutover);
const returned=l.rows('SELECT * FROM material_rolling_returns WHERE origin_pool_id<>? AND origin_pool_id<? AND same_day=0 AND order_id NOT IN (SELECT order_id FROM order_after_sales)','',cutover);
if(pools.some(pool=>pool.materialGroups)){
const balances=pools.flatMap(pool=>Allocation.balances({...pool,materialGroups:pool.materialGroups??Allocation.groups(pool.purchases)},pool.usages.filter(u=>u.active&&l.one('SELECT date FROM orders WHERE id=?',u.order_id)?.date<cutover)));
const common=balances.filter(g=>g.kind==='public'),personal=balances.filter(g=>g.kind==='personal_recovery'),pending=balances.some(g=>g.status==='pending');
@@ -63,7 +63,7 @@ function legacyOpening(l,cutover,env){
const grossAmount=pending?null:sum(frozen.map(v=>({amount:v.pool.totalAmount-sum(v.usages,'amount')})),'amount');
const allocations=frozen.flatMap(({pool,usages})=>{
const consumed=Object.fromEntries(PARTIES.map(payer=>[payer,sum(usages,payer+'_amount')]));
return pool.purchases.flatMap(p=>parts(p).flatMap(a=>{const take=Math.min(consumed[a.payer],a.amount);consumed[a.payer]-=take;return take===a.amount?[]:[{...a,amount:a.amount-take,source_id:p.id,created:p.created,source_sequence:l.one('SELECT rowid AS n FROM material_purchases WHERE id=?',p.id).n}];}));
return pool.purchases.flatMap(p=>parts(p).flatMap(a=>{const take=Math.min(consumed[a.payer],a.amount);consumed[a.payer]-=take;return take===a.amount?[]:[{...a,amount:a.amount-take,source_id:p.id,created:p.created,source_sequence:l.one('SELECT rowid AS n FROM material_purchases WHERE id=?',p.id)?.n??p.source_sequence??0}];}));
}).sort((a,b)=>String(a.created).localeCompare(String(b.created))||a.source_sequence-b.source_sequence);
// 切换后退回的旧耗用已由当日回料承接,不能再次抬高切换日结转。
const reversed=Object.fromEntries(PARTIES.map(p=>[p,0]));for(const r of returned)for(const a of JSON.parse(r.allocations))reversed[a.payer]+=a.amount;
@@ -161,7 +161,7 @@ function readPool(l,date,env,{internal=false,live=false,member=null}={}){
}
const result=member?Allocation.eligible(pool,member):pool;return internal?result:legacy().visiblePool(l,result);
}
function allocations(pool,usages){return LockPools.allocate(pool,usages,legacy().allocatePayers);}
function allocations(pool,usages,l=null){const base=(value,rows)=>LockPools.allocate(value,rows,legacy().allocatePayers);return l?require('./order-after-sales').allocateFrozen(l,pool,usages,base):base(pool,usages);}
function applyLine(line,row,pool){
const a=PARTIES.map(p=>({payer:p,amount:row[p+'_amount']??0})).filter(p=>p.amount>0);if(row.amount===0&&!a.length)a.push({payer:row.zero_payer??'owner',amount:0});
line.costParts={...line.costParts,material:row.amount};line.cost=Object.values(line.costParts).some(v=>v===null)?null:sum(Object.values(line.costParts).map(amount=>({amount})),'amount');
@@ -172,14 +172,15 @@ function prepareLines(l,lines,businessDate,env,{orderId=null,member=null}={}){
for(const {line} of selected){if(line.costMaterial.poolId!==businessDate)env.fail('滚动日料池须使用订单当天日期');if(line.unit!=='g'||Calc.isSilver(line.name))env.fail('日购料成本只支持按克黄金商品');}
const pool=readPool(l,businessDate,env,{internal:true}),original=LockPools.decorate(l,l.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId??'')),last=l.one('SELECT COALESCE(MAX(sequence),0) AS n FROM material_usage_order').n;
const usages=pool.usages.filter(u=>u.active&&(!orderId||u.order_id!==orderId));for(const {line,index} of selected){const before=original.find(u=>u.line_index===index);usages.push({...before,member:member??(orderId?l.entityMember('order',orderId):null)??l.memberFor(l.actor),mg:line.costMaterial?.consumptionMg??line.quantity,preview_index:index,created:before?.created??env.now(),fifo_sequence:before?.fifo_sequence??last+index+1});}
usages.sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);for(const u of allocations(pool,usages))if(u.preview_index!==undefined)applyLine(lines[u.preview_index],u,pool);return lines;
usages.sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);for(const u of allocations(pool,usages,l))if(u.preview_index!==undefined)applyLine(lines[u.preview_index],u,pool);return lines;
}
function reconcile(l,...args){return l.scope(null,()=>reconcileInternal(l,...args),null);}
function reconcileInternal(l,date,actor,env,{skipJournalOrder=null,preservePriceLockIds=[]}={}){
assertDate(l,date,env);ensureDay(l,date,env);const pool=readSources(l,date,env),updates=new Map();
const preserved=new Set(preservePriceLockIds);
for(const u of allocations(pool,pool.usages.filter(u=>consumed(l,u,date)||u.kind==='priceLock'&&u.reservedPublicSubstitutionMg>0))){
for(const u of allocations(pool,pool.usages.filter(u=>consumed(l,u,date)||u.kind==='priceLock'&&u.reservedPublicSubstitutionMg>0),l)){
if(u.kind==='priceLock'){if(!preserved.has(u.price_lock_id))LockPools.update(l,u,pool,actor,env,{skipJournalOrder});continue;}
if(require('./order-after-sales').read(l,u.order_id))continue;
if(!updates.has(u.order_id))updates.set(u.order_id,{order:l.rawOrder(u.order_id),delta:0,changed:false});const v=updates.get(u.order_id),line=v.order.lines[u.line_index];
if(!line||line.costMaterial?.poolId!==date)env.fail('滚动料池与商品来源不一致',409);
const before=line.costParts?.material,oldAlloc=line.materialPool?.allocations,oldRate=line.materialPool?.averageRate,oldSources=line.materialPool?.materialSources;
@@ -217,6 +218,7 @@ function list(l,query,env){
}
function syncReturnSources(l,origin){
for(const r of l.rows('SELECT * FROM material_rolling_returns WHERE origin_pool_id=?',origin)){
if(require('./order-after-sales').read(l,r.order_id))continue;
const o=l.rawOrder(r.order_id),line=o.lines[r.line_index],amount=line.costParts?.material,allocations=line.materialPool?.allocations;
const pending=amount===null&&line.materialPool?.status==='pending'&&line.materialPool?.materialSources?.some(s=>s.kind==='public'&&s.amount===null);
if(!pending&&(!Number.isSafeInteger(amount)||!allocations||sum(allocations,'amount')!==amount))throw new Error('复核后的退货回料来源无法核对');
@@ -227,7 +229,8 @@ function repriceLegacyReturns(l,actor,env){
const c=config(l),origins=l.rows("SELECT DISTINCT origin_pool_id FROM material_rolling_returns WHERE origin_pool_id<>'' AND origin_pool_id<?",c.cutover).map(r=>r.origin_pool_id);
for(const origin of origins){const pool=legacy().readPool(l,origin,env,{internal:true});
const candidates=pool.usages.filter(u=>u.active||l.one('SELECT id FROM material_rolling_returns WHERE order_id=? AND line_index=? AND origin_pool_id=?',u.order_id,u.line_index,origin));
for(const u of allocations(pool,candidates)){
for(const u of allocations(pool,candidates,l)){
if(require('./order-after-sales').read(l,u.order_id))continue;
const order=l.rawOrder(u.order_id),line=order.lines[u.line_index],old=line.costParts?.material,oldAlloc=line.materialPool?.allocations;applyLine(line,u,pool);const delta=(u.amount??0)-(old??0);
l.run('UPDATE material_pool_usages SET amount=?,owner_amount=?,assistant_amount=?,revision=revision+1,updated=? WHERE id=?',u.amount,u.owner_amount,u.assistant_amount,env.now(),u.id);
if(u.assistant2_amount!==undefined)l.run('INSERT INTO material_usage_parties VALUES (?,?) ON CONFLICT(usage_id) DO UPDATE SET assistant2_amount=excluded.assistant2_amount',u.id,u.assistant2_amount);else l.run('DELETE FROM material_usage_parties WHERE usage_id=?',u.id);
@@ -260,4 +263,4 @@ function rebuild(l,actor,env,{fromDate=null,skipJournalOrder=null,preservePriceL
});}
// 调用方必须先取得历史复核权限;局部重建本身不能绕过冻结检查。
function rebuildFrom(l,date,actor,env,options={}){assertDate(l,date,env);return rebuild(l,actor,env,{...options,fromDate:date});}
module.exports={initialize,config,enabled,isDay,withHistorical,assertDate,dependency,previewEnable,enable,status,legacySnapshot,readPool,prepareLines,reconcile,recordReturns,release,list,rebuild,rebuildFrom,registerSource};
module.exports={initialize,config,enabled,isDay,withHistorical,assertDate,dependency,previewEnable,enable,status,legacySnapshot,readPool,prepareLines,reconcile,recordReturns,release,list,rebuild,rebuildFrom,registerSource,returnsFor};