2026-11-10 02:54:58 +08:00
'use strict' ;
// 已交付订单的一次性整单售后。原销售、采购和现金事实保留,售后当天只记差额。
const { randomUUID } = require ( 'node:crypto' );
const Calc = require ( './public/calculations' );
const Allocation = require ( './material-pool-allocation' );
const Rolling = require ( './rolling-material-pools' );
2026-11-14 01:16:35 +08:00
const TeamMembers = require ( './team-members' );
const TeamFunds = require ( './team-funds' );
const Amounts = require ( './material-member-amounts' );
2026-11-10 02:54:58 +08:00
const clone = value => JSON . parse ( JSON . stringify ( value ));
const sum = ( rows , key )=> rows . reduce (( n , row )=> n + ( row [ key ] ?? 0 ), 0 );
const yuan = value =>( value / 100 ). toFixed ( 2 ), grams = value =>( value / 1000 ). toFixed ( 3 );
const ratio = ( amount , n , d )=> Number (( BigInt ( amount ) * BigInt ( n ) + BigInt ( d ) / 2 n ) / BigInt ( d ));
function initialize ( l ){ l . db . exec ( `
CREATE TABLE IF NOT EXISTS order_after_sales(order_id TEXT PRIMARY KEY REFERENCES orders(id),date TEXT NOT NULL,record TEXT NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS ix_order_after_sales_date ON order_after_sales(date,order_id);
CREATE TABLE IF NOT EXISTS returned_stock_lots(id TEXT PRIMARY KEY,order_id TEXT NOT NULL REFERENCES orders(id),line_index INTEGER NOT NULL,date TEXT NOT NULL,pocket TEXT NOT NULL,name TEXT NOT NULL,code TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),stock_count INTEGER,labor_cost INTEGER NOT NULL CHECK(labor_cost>=0),labor_payer TEXT NOT NULL,created TEXT NOT NULL,UNIQUE(order_id,line_index));
` );}
function read ( l , id ){ if ( ! id ) return null ; const row = l . one ( 'SELECT * FROM order_after_sales WHERE order_id=?' , id ); if ( ! row ) return null ; const record = JSON . parse ( row . record ); return {... record , originalOrder : record . original };}
function eligibility ( l , order ){
if ( read ( l , order . id ) || order . status === 'returned' ) return '本单已完成整单退货售后,不能重复退货或继续退款' ;
if ( order . status !== 'delivered' ) return '仅已交付订单可以登记退货退款售后' ;
if ( order . recovery_id || l . one ( 'SELECT id FROM recoveries WHERE order_id=?' , order . id )) return '回收/置换关联订单须在原关联流程处理,不能从普通售后解除物料和抵扣款' ;
if ( order . lines . some ( line => line . unit !== 'g' || Calc . isSilver ( line . name ))) return '本入口支持按克黄金整单售后;按件商品或银饰请核实实际成本后单独处理' ;
if ( order . goodsCost === null || order . profit === null || order . lines . some ( line => ! line . costParts || [ 'material' , 'labor' , 'accessories' , 'other' ]. some ( key => ! Number . isSafeInteger ( line . costParts [ key ]) || line . costParts [ key ] < 0 ))) return '请先核实原单金料、工费、配件及其他分项成本,再登记售后' ;
if ( order . lines . some ( line => sum ( Object . values ( line . costParts ). map ( amount =>({ amount })), 'amount' ) !== line . cost )) return '原商品分项成本与总成本不一致,请先复核原成本再处理售后' ;
if ( order . netReceived !== order . total ) return '原单实收与已确认销售金额不一致,请先复核原收退款' ;
// 原锁日料池含预留、短交余料与补重的多段耗用,不能作为普通池料再回流一次。
if ( order . lines . some ( line => line . priceLockPool ) || l . one ( 'SELECT r.id FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id WHERE p.final_order_id=?' , order . id )) return '此单关联锁价料池预留及余料,本轮暂不支持一体化售后;请由麦麦核对锁价采购、余料与退款,勿使用普通整单退货代替' ;
return '' ;
}
function consumers ( l , lotId , excludeOrder = null ){ return l . rows ( "SELECT id,status,lines FROM orders WHERE status IN ('confirmed','delivered','returned') ORDER BY id" ). flatMap ( row => row . id === excludeOrder ? [] : JSON . parse ( row . lines ). flatMap (( line , lineIndex )=> line . returnedStockId === lotId ? [{ orderId : row . id , status : row . status , lineIndex , quantity : line . quantity }] : []));}
function lotValue ( l , row ,{ excludeOrder = null , date = l . businessEnv (). today ()} = {}){
const used = consumers ( l , row . id , excludeOrder ), available =! used . length ;
const effectivePoolId = Rolling . isDay ( l , date ) ? date : row . date ;
return { id : row . id , orderId : row . order_id , lineIndex : row . line_index , date : row . date , pocket : row . pocket , name : row . name , code : row . code , quantity : row . mg , stockCount : row . stock_count , laborCost : row . labor_cost , laborPayer : row . labor_payer , effectivePoolId , materialPoolNotice : Rolling . isDay ( l , date ) ? '按销售当天滚动料池核算金料;继承原工费不新增付款' : '尚未启用滚动料池,沿用' + row . date + '回料日料池;按该池实际成本核算金料' , remainingMg : available ? row . mg : 0 , remainingCount : row . stock_count === null ? null : available ? row . stock_count : 0 , available , consumers : used };
}
function listLots ( l , query = {}, actor = l . actor ){
const date = l . businessEnv (). day ( query . date || l . businessEnv (). today ()), member = l . queryMember ( query , actor );
if ( query . orderId ) l . rawOrder ( query . orderId , actor );
const lots = l . rows ( 'SELECT * FROM returned_stock_lots WHERE date<=? ORDER BY date,created,rowid' , date ). filter ( row => l . canAccess ( 'order' , row . order_id , actor ) && ( ! query . pocket || row . pocket === query . pocket ) && ( ! member || l . entityMember ( 'order' , row . order_id ) === member ));
return { lots : lots . map ( row => lotValue ( l , row ,{ excludeOrder : query . orderId ?? null , date })). filter ( row => query . all === 'true' || query . all === true || row . available ). map (({ consumers ,... lot })=> lot )};
}
function context ( l , id , actor , env ){
l . assertAccess ( 'order' , id , actor ); const order = l . detail ( id ), record = read ( l , id ), reason = eligibility ( l , order );
const lines = order . lines . map (( line , lineIndex )=>({ lineIndex , name : line . name , code : line . code , quantity : line . quantity , pocket : line . pocket , stockCount : line . stockCount ?? null , materialCost : line . costParts ? . material ?? null , laborCost : line . costParts ? . labor ?? null }));
2026-11-14 01:16:35 +08:00
const account = order . payments . find ( payment => payment . kind === 'receipt' && payment . amount > 0 ) ? . account || order . payment_account , payer = TeamFunds . accountMember ( account , l );
2026-11-10 02:54:58 +08:00
return { orderId : id , revision : order . revision , eligible :! reason , blockedReason : reason , lines , record , directToday :! reason && order . date === env . today (), inputs : { date : env . today (), revision : order . revision , reason : '' , afterSale : { lines : lines . map ( line =>({ lineIndex : line . lineIndex , quantity : grams ( line . quantity ), pocket : line . pocket || '现货' , disposition : 'stock' ,...( line . stockCount === null ? {} : { stockCount : line . stockCount })})), refund : { amount : yuan ( order . netReceived ), account , payer , reference : '' }, deductionReason : '' , expenses : []}}};
}
function scaleParts ( parts , n , d , target = ratio ( sum ( parts , 'amount' ), n , d )){
const total = sum ( parts , 'amount' ); if ( ! total ) return target ? (()=>{ throw new Error ( '金料资金来源缺少分厘归属' );})() : [];
let prefix = 0 , allocated = 0 ; return parts . map (( part , index )=>{ prefix += part . amount ; const cumulative = index === parts . length - 1 ? target : ratio ( prefix , target , total ), amount = cumulative - allocated ; allocated = cumulative ; return {... part , amount };}). filter ( part => part . amount > 0 );
}
function scaledNumbers ( rows , key , n , d , target ){ let prefix = 0 , allocated = 0 ; return rows . map (( row , index )=>{ prefix += row [ key ]; const cumulative = index === rows . length - 1 ? target : ratio ( prefix , n , d ), value = cumulative - allocated ; allocated = cumulative ; return {... row ,[ key ] : value };});}
function sourceSnapshot ( line ){
const amount = line . costParts . material , pool = line . materialPool ?? line . priceLockPool ;
if ( pool ? . materialSources ? . length ) return clone ( pool . materialSources );
if ( line . materialAllocations ? . length ){
const grouped = new Map (); for ( const part of line . materialAllocations ){ const key = part . materialKind === 'personal_recovery' ? 'personal:' + part . materialOwner : 'public' ; if ( ! grouped . has ( key )) grouped . set ( key ,{ kind : part . materialKind === 'personal_recovery' ? 'personal_recovery' : 'public' , member : part . materialOwner ?? null , quantity : 0 , amount : 0 , allocations : [], batches : []}); const source = grouped . get ( key ); source . amount += part . amount ; source . allocations . push ({ payer : part . payer , amount : part . amount });}
const sources = [... grouped . values ()]; let used = 0 ; for ( const [ i , s ] of sources . entries ()){ s . quantity = i === sources . length - 1 ? line . quantity - used : amount ? ratio ( line . quantity , s . amount , amount ) : 0 ; used += s . quantity ;} return sources . filter ( s => s . quantity > 0 );
}
return [{ kind : 'public' , member : null , quantity : line . quantity , amount , allocations : pool ? . allocations ? . length ? clone ( pool . allocations ) : [{ payer : line . costPayers ? . material ?? line . payer , amount }], batches : []}];
}
function returnedSources ( line , mg ){
const original = sourceSnapshot ( line ), amount = ratio ( line . costParts . material , mg , line . quantity );
if ( sum ( original , 'quantity' ) !== line . quantity || sum ( original , 'amount' ) !== line . costParts . material || original . some ( source => sum ( source . allocations , 'amount' ) !== source . amount )) throw new Error ( '原单金料来源与克重或成本不守恒' );
const quantities = scaledNumbers ( original , 'quantity' , mg , line . quantity , mg ), amounts = scaledNumbers ( original , 'amount' , mg , line . quantity , amount );
const result = original . map (( source , i )=>{ const quantity = quantities [ i ]. quantity , partAmount = amounts [ i ]. amount , batches = source . batches ? . length ? scaledNumbers ( source . batches , 'mg' , quantity , source . quantity , quantity ). filter ( batch => batch . mg > 0 ) : []; return {... source , quantity , amount : partAmount , allocations : scaleParts ( source . allocations , mg , line . quantity , partAmount ), batches , basisAmount : partAmount , basisMg : quantity , prefixMg : 0 , prefixAmount : 0 };});
// 同一公私来源的零毫克片段可合并分厘;不同来源不足一毫克时不猜测改归属。
for ( const source of result . filter ( row => ! row . quantity && row . amount )){
const target = result . find ( row => row . quantity > 0 && Allocation . keyOf ( row ) === Allocation . keyOf ( source ));
if ( ! target ){ const error = new Error ( '实际退回克重过小,无法按毫克保持各公私金料来源,请核对实物克重后再登记' ); error . status = 400 ; throw error ;}
target . amount += source . amount ; target . basisAmount = target . amount ; target . allocations . push (... source . allocations ); source . amount = 0 ; source . allocations = [];
}
const returned = result . filter ( source => source . quantity > 0 );
if ( sum ( returned , 'quantity' ) !== mg || sum ( returned , 'amount' ) !== amount || sum ( returned . flatMap ( source => source . allocations ), 'amount' ) !== amount ) throw new Error ( '退回金料毫克及分厘来源不守恒' );
return returned ;
}
function normalizeLine ( l , line , input , index , env ){
if ( ! input || input . lineIndex !== index ) env . fail ( '请按原商品顺序逐行核实整单退回实物,不可遗漏或重复' );
const quantity = env . weight ( input . quantity , `第 ${ index + 1 } 行实际退回克重` ); if ( quantity <= 0 || quantity > line . quantity ) env . fail ( `第 ${ index + 1 } 行实际退回克重须大于0且不超过原销售克重` );
const disposition = env . pick ( input . disposition ,[ 'stock' , 'scrap' ], '退回处置' ), pocket = l . validatePocket ( input . pocket ,{ original : line . pocket , name : '实物退回货盘' });
if ( ! l . selfPocketKeys (). includes ( pocket )) env . fail ( '退回实物须选择自有现货或回收旧料货盘' );
if ( disposition === 'scrap' && l . pocket ( pocket ) ? . countUnit === 'pair' ) env . fail ( '回收旧料不能退入按对计数的成品货盘,请选择旧料货盘' );
let stockCount = null ;
if ( disposition === 'stock' && l . pocket ( pocket ) ? . countUnit === 'pair' ){
stockCount = l . validateStockCount ( pocket , input . stockCount ,{ name : `第 ${ index + 1 } 行实际退回对数` });
if ( Number . isSafeInteger ( line . stockCount ) && stockCount > line . stockCount ) env . fail ( `第 ${ index + 1 } 行实际退回对数不能超过原销售对数` );
} else if ( input . stockCount !== undefined && input . stockCount !== null && input . stockCount !== '' ) env . fail ( '只有退回按对计数的完好成品才填写退回对数' );
const materialSources = returnedSources ( line , quantity ), materialReturnedCost = sum ( materialSources , 'amount' ), materialAllocations = materialSources . flatMap ( source => source . allocations );
const laborPayer = line . costPayers ? . labor ?? line . payer ;
const laborRestockedCost = disposition === 'stock' ? ( stockCount !== null && Number . isSafeInteger ( line . stockCount ) ? ratio ( line . costParts . labor , stockCount , line . stockCount ) : line . costParts . labor ) : 0 ;
const materialLoss = line . costParts . material - materialReturnedCost , costLoss = line . cost - materialReturnedCost - laborRestockedCost ;
return { lineIndex : index , name : line . name , code : line . code , quantity , originalQuantity : line . quantity , pocket , disposition , stockCount , originalMaterialCost : line . costParts . material , materialReturnedCost , materialLoss , laborRestockedCost , laborPayer , costLoss , materialAllocations , materialSources , restockedLaborAllocations : laborRestockedCost ? [{ payer : laborPayer , amount : laborRestockedCost }] : []};
}
function apply ( l , order , date , input , actor , env ){
const blocked = eligibility ( l , order ); if ( blocked ) env . fail ( blocked , 409 );
if ( ! Number . isSafeInteger ( input . revision ) || input . revision !== order . revision ) env . fail ( '订单有新变动,请重新读取并核对售后' , 409 );
if ( input . verified !== true ) env . fail ( '请核实已收回的实物及实际退款凭据' );
const value = input . afterSale ; if ( ! value || typeof value !== 'object' || Array . isArray ( value )) env . fail ( '订单售后内容无效' );
if ( ! Array . isArray ( value . lines ) || value . lines . length !== order . lines . length ) env . fail ( '本轮为整单一次性售后,请逐行填写全部退回实物' );
const reason = env . text ( input . reason , '售后原因' , 200 ), lines = value . lines . map (( row , i )=> normalizeLine ( l , order . lines [ i ], row , i , env ));
const refund = value . refund ; if ( ! refund || typeof refund !== 'object' ) env . fail ( '请填写实际退款金额、账户及付款人' );
const refundAmount = env . money ( refund . amount , '实际退款金额' ); if ( refundAmount > order . netReceived ) env . fail ( '实际退款金额不能超过原单净实收' );
2026-11-14 01:16:35 +08:00
const account = env . paymentAccount ( refund . account ), payer = l . validateMember ( refund . payer , '退款付款人' ), expectedPayer = TeamFunds . accountMember ( account , l );
2026-11-10 02:54:58 +08:00
if ( payer !== expectedPayer ) env . fail ( '退款付款人须与实际付款账户一致' );
const retainedAmount = order . netReceived - refundAmount , deductionReason = env . text ( value . deductionReason , '扣费原因' , 200 , retainedAmount === 0 );
const expenses = value . expenses ?? []; if ( ! Array . isArray ( expenses ) || expenses . length > 60 ) env . fail ( '售后新增费用格式无效' );
2026-11-14 01:16:35 +08:00
const fees = expenses . map ( fee =>({ amount : env . money ( fee . amount , '售后新增费用' ), payer : l . validateMember ( fee . payer , '售后费用付款人' ), note : env . text ( fee . note , '售后费用项目' , 150 )}));
2026-11-10 02:54:58 +08:00
const materialReturnedCost = sum ( lines , 'materialReturnedCost' ), laborRestockedCost = sum ( lines , 'laborRestockedCost' ), costLoss = sum ( lines , 'costLoss' ), newExpenses = sum ( fees , 'amount' ), directCost = order . directCost + newExpenses ;
const profit = retainedAmount - costLoss - directCost , profitAdjustment = profit - order . profit ;
const original = clone ( order ); delete original . audit ; delete original . sync ; delete original . orderAfterSale ;
const originalJournal = l . one ( 'SELECT COALESCE(SUM(sales),0) AS sales,COALESCE(SUM(goods),0) AS goods,COALESCE(SUM(expense),0) AS expense,COALESCE(SUM(profit),0) AS profit FROM journal WHERE order_id=?' , order . id );
const summary = { refundAmount , retainedAmount , materialReturnedCost , laborRestockedCost , materialLoss : sum ( lines , 'materialLoss' ), costLoss , originalDirectCost : order . directCost , newExpenses , directCost , profit , finalProfit : profit , profitAdjustment , lines };
const record = { orderId : order . id , date , reason , deductionReason , refund : { amount : refundAmount , account , payer , reference : env . text ( refund . reference , '退款凭据备注' , 100 , true )}, expenses : fees , original , originalJournal , summary , lines };
// 先建立不可变原单快照,使同日料池后续重算也不能改写已确认售后成本。
l . run ( 'INSERT INTO order_after_sales VALUES (?,?,?,?,?)' , order . id , date , JSON . stringify ( record ), actor . name , env . now ());
if ( Rolling . enabled ( l )) Rolling . assertDate ( l , date , env );
for ( const row of lines ){
const originalLine = order . lines [ row . lineIndex ], usage = l . one ( 'SELECT * FROM material_pool_usages WHERE order_id=? AND line_index=?' , order . id , row . lineIndex ), returnId = randomUUID ();
// 与旧全额退货不同:保留原耗用,并把实际回收作为新来源。缺失克重仍是实际损耗。
l . run ( 'INSERT INTO material_rolling_returns VALUES (?,?,?,?,?,?,?,?,?,?,?)' , returnId , order . id , row . lineIndex , date , row . quantity , row . materialReturnedCost , JSON . stringify ( row . materialAllocations ), usage ? . pool_id ?? '' , 0 , actor . name , env . now ());
Rolling . registerSource ( l , 'return' , returnId ); Allocation . saveReturn ( l , 'order' , returnId , row . materialSources );
l . move ({ group : 'after-sale:' + order . id , order : order . id , date , pocket : row . pocket , mg : row . quantity , stockCount : row . stockCount , kind : 'return' , note : order . number + ' · ' + ( row . disposition === 'stock' ? '售后完好现货' : '售后回收旧料' )}, actor );
if ( row . disposition === 'stock' ) l . run ( 'INSERT INTO returned_stock_lots VALUES (?,?,?,?,?,?,?,?,?,?,?,?)' , randomUUID (), order . id , row . lineIndex , date , row . pocket , originalLine . name , originalLine . code || '' , row . quantity , row . stockCount , row . laborRestockedCost , row . laborPayer , env . now ());
}
if ( refundAmount ) l . run ( 'INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)' , randomUUID (), order . id , date , 'refund' , refundAmount , account , '整单售后退款' + ( record . refund . reference ? ': ' + record . refund . reference : '' ), actor . name , env . now ());
for ( const fee of fees ) if ( fee . amount ) l . run ( 'INSERT INTO expenses VALUES (?,?,?,?,?,?,?,?)' , randomUUID (), order . id , date , fee . amount , fee . payer , '售后:' + fee . note , actor . name , env . now ());
l . run ( "UPDATE orders SET status='returned',returned_date=? WHERE id=?" , date , order . id );
l . journal ( order . id , date , '订单退货退款售后' , retainedAmount - originalJournal . sales , costLoss - originalJournal . goods , directCost - originalJournal . expense );
if ( Rolling . enabled ( l )) Rolling . reconcile ( l , date , actor , env ); else require ( './material-pools' ). reconcile ( l , date , date , actor , env );
return { id : order . id , record : read ( l , order . id ), summary };
}
function prepareLines ( l , lines , inputs , date , env ,{ orderId = null , member = null , actor = l . actor } = {}){
const used = new Set ();
for ( const [ index , line ] of lines . entries ()){
const id = inputs [ index ] ? . returnedStockId ; if ( ! id ) continue ;
if ( used . has ( id )) env . fail ( '同一退回现货批次不能在一单重复选择' ); used . add ( id );
const raw = l . one ( 'SELECT * FROM returned_stock_lots WHERE id=?' , String ( id )); if ( ! raw ) env . fail ( '退回现货批次不存在' , 404 );
l . assertAccess ( 'order' , raw . order_id , actor );
if ( l . teamMode && member && l . entityMember ( 'order' , raw . order_id ) !== member ) env . fail ( '退回现货须沿原订单经营归属再次销售;请先由麦麦核实归属' , 409 );
const lot = lotValue ( l , raw ,{ excludeOrder : orderId , date }); if ( ! lot . available ) env . fail ( '该退回现货已被其他订单占用或销售,请重新选择' , 409 );
if ( date < lot . date ) env . fail ( '再次销售日期不能早于实物退回日期' );
if ( line . unit !== 'g' || line . pocket !== lot . pocket || line . name !== lot . name || line . code !== lot . code || line . quantity !== lot . quantity || ( lot . stockCount !== null && line . stockCount !== lot . stockCount )) env . fail ( '退回现货须按原批次商品、货盘、完整克重及对数再次销售,本轮暂不支持拆批' );
if ( line . costMaterial ? . mode !== 'pool' ) env . fail ( '退回现货再次销售须选择销售当日料池,不能再次手填原购料金料成本' );
if ( line . costMaterial . poolId !== lot . effectivePoolId ) env . fail ( '退回现货须使用' + lot . effectivePoolId + '料池;' + lot . materialPoolNotice );
line . costParts . labor = lot . laborCost ; line . costLabor = { mode : 'total' }; line . costPayers = { material : line . costPayers ? . material ?? line . payer , labor : lot . laborPayer };
if ( line . costFundings ) delete line . costFundings . labor ;
line . cost = Object . values ( line . costParts ). some ( value => value === null ) ? null : sum ( Object . values ( line . costParts ). map ( amount =>({ amount })), 'amount' );
line . returnedStockId = lot . id ; line . returnedStock = { id : lot . id , originOrderId : lot . orderId , laborCost : lot . laborCost , laborPayer : lot . laborPayer };
}
return lines ;
}
function guardMutation ( l , order , action , input , env ){
if ( ! read ( l , order . id )) return ;
if ([ 'refund' , 'return' , 'cost' , 'material' , 'expense' , 'fees' ]. includes ( action ) || action === 'correct' && input . type !== 'settlement' ) env . fail ( '本单已完成一体化售后,扣留款已入最终结果,不能从旧退款或成本入口再次处理' , 409 );
}
function validateStoredLots ( l , order , actor , env ){
if ( ! order . lines . some ( line => line . returnedStockId )) return ;
prepareLines ( l , clone ( order . lines ), order . lines , order . date , env ,{ orderId : order . id , member : l . entityMember ( 'order' , order . id ), actor });
}
function stableRecord ( record ){ if ( ! record ) return null ; const { original , originalOrder ,... value } = record ; return {... value , original : { id : original . id , date : original . date , total : original . total , goodsCost : original . goodsCost , directCost : original . directCost , profit : original . profit , lines : original . lines }};}
function dependencies ( l , id , payload = {}){
const order = l . rawOrder ( id ), ids = [... new Set ([... order . lines ,...( Array . isArray ( payload . lines ) ? payload . lines : [])]. map ( line => line . returnedStockId ). filter ( Boolean ))];
return { record : stableRecord ( read ( l , id )), lots : ids . sort (). map ( lotId =>{ const lot = l . one ( 'SELECT * FROM returned_stock_lots WHERE id=?' , lotId ); return lot ? lotValue ( l , lot ) : { id : lotId , missing : true };}), returns : l . rows ( 'SELECT line_index,date,mg,amount,allocations,origin_pool_id,same_day FROM material_rolling_returns WHERE order_id=? ORDER BY line_index' , id ), createdLots : l . rows ( 'SELECT * FROM returned_stock_lots WHERE order_id=? ORDER BY line_index' , id ). map ( row => lotValue ( l , row ))};
}
function effect ( l , id , payload = {}){ const value = dependencies ( l , id , payload ); return { record : value . record , returns : value . returns , lots : value . lots . map (({ id , consumers ,... lot })=>({... lot , consumers : consumers . map (({ orderId ,... consumer })=> consumer )})), createdLots : value . createdLots . map (({ id , consumers ,... lot })=>({... lot , consumers : consumers . map (({ orderId ,... consumer })=> consumer )}))};}
// 已售后的原料成本不再参与后续当日均价重定价。剩余料独立加权,原公私及付款来源各自守恒。
function allocateFrozen ( l , pool , rows , base ){
const frozen = rows . filter ( row => row . kind !== 'priceLock' && read ( l , row . order_id )); if ( ! frozen . length ) return base ( pool , rows );
2026-11-14 01:16:35 +08:00
const fixed = frozen . map ( row =>{ const original = read ( l , row . order_id ). original . lines [ row . line_index ], sources = sourceSnapshot ( original ); return {... row , amount : original . costParts . material , materialSources : sources ,... Amounts . fields ( sources . flatMap ( source => source . allocations ), original . costParts . material ),... Object . fromEntries ( Amounts . keys ( sources ). map ( payer =>[ payer + '_amount' , sum ( sources . flatMap ( source => source . allocations ). filter ( part => part . payer === payer ), 'amount' )]))};});
2026-11-10 02:54:58 +08:00
const groups = pool . materialGroups ?? Allocation . groups ( pool . purchases ), purchases = [];
for ( const group of groups ){
const sources = fixed . flatMap ( row => row . materialSources ). filter ( source => Allocation . keyOf ( source ) === group . key ), mg = group . totalMg - sum ( sources , 'quantity' ), amount = group . totalAmount === null ? null : group . totalAmount - sum ( sources , 'amount' );
2026-11-14 01:16:35 +08:00
const allocations = Amounts . keys ( group . purchases , sources ). map ( payer =>({ payer , amount : sum ( group . purchases . flatMap ( row => row . allocations ?? [{ payer : row . payer , amount : row . amount }]). filter ( part => part . payer === payer ), 'amount' ) - sum ( sources . flatMap ( source => source . allocations ). filter ( part => part . payer === payer ), 'amount' )}));
2026-11-10 02:54:58 +08:00
if ( mg < 0 || amount !== null && amount < 0 || allocations . some ( part => part . amount < 0 )) l . businessEnv (). fail ( '已售后原单的金料来源已被后续更正改变,请先复核原采购与售后成本,不能改写已确认售后' , 409 );
if ( ! mg && amount ) l . businessEnv (). fail ( '已售后原成本已锁定,本次采购更正会留下无克重的金料成本,请先核对采购与售后,不可改写原已确认成本' , 409 );
const batches = group . purchases . flatMap ( purchase => clone ( purchase . batches ? . length ? purchase . batches : [{ purchaseId : purchase . purchaseId ?? purchase . id , recoveryId : purchase . recovery_id ?? purchase . recoveryId , mg : purchase . mg }])); let unspecified = 0 ;
for ( const source of sources ){ if ( ! source . batches ? . length ){ unspecified += source . quantity ; continue ;} for ( const spent of source . batches ){ let left = spent . mg ; for ( const batch of batches ) if ( batch . purchaseId === spent . purchaseId ){ const taken = Math . min ( left , batch . mg ); batch . mg -= taken ; left -= taken ;} if ( left ) l . businessEnv (). fail ( '已售后原单的实物来源批次已改变,请先复核售后回料' , 409 );}}
for ( const batch of batches ){ const taken = Math . min ( unspecified , batch . mg ); batch . mg -= taken ; unspecified -= taken ;}
if ( unspecified ) l . businessEnv (). fail ( '已售后原单的实物来源不足,请先复核售后回料' , 409 );
if ( mg ) purchases . push ({ id : 'after-sale-remaining:' + group . key , date : pool . date , mg , amount , allocations : allocations . filter ( part => part . amount > 0 ), payer : allocations . find ( part => part . amount > 0 ) ? . payer ?? 'owner' , batches : batches . filter ( batch => batch . mg > 0 ),...( group . member ? { materialOwner : group . member } : {}), created : pool . date + 'T00:00:00Z' });
}
const remainingRows = rows . filter ( row => ! fixed . some ( saved => saved . id === row . id )), materialGroups = Allocation . groups ( purchases ), publicGroup = materialGroups . find ( group => group . kind === 'public' ), residual = {... pool , purchases , totalMg : sum ( purchases , 'mg' ), totalAmount : purchases . some ( row => row . amount === null ) ? null : sum ( purchases , 'amount' ),...( materialGroups . some ( group => group . kind === 'personal_recovery' ) ? { materialGroups } : { materialGroups : undefined })};
if ( residual . materialGroups ){ residual . purchases = publicGroup . purchases ; residual . totalMg = publicGroup . totalMg ; residual . totalAmount = publicGroup . totalAmount ;}
const allocated = Allocation . allocate ({... residual , materialGroups }, remainingRows ), byOriginal = new Map ( remainingRows . map (( row , index )=>[ row , allocated [ index ]]));
return rows . map ( row => fixed . find ( saved => saved . id === row . id && saved . order_id === row . order_id ) || byOriginal . get ( row ));
}
module . exports = { initialize , read , context , apply , listLots , prepareLines , guardMutation , validateStoredLots , dependencies , effect , allocateFrozen , sourceSnapshot , returnedSources , ratio };