'use strict'; // 锁价预留只占用已有料池;不生成采购、现金、销售或实物流水。 const { randomUUID } = require('node:crypto'), Calc = require('../../public/calculations'), Allocation = require('../materials/material-pool-allocation'), LockLines = require('./price-lock-lines'); const Amounts = require('../materials/material-member-amounts'); const sum = (rows, key) => rows.reduce((n, r) => n + (r[key] ?? 0), 0); function initialize(l) { l.db.exec(` CREATE TABLE IF NOT EXISTS price_lock_pool_reservations(id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),line_index INTEGER NOT NULL DEFAULT 0,pool_id TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),amount INTEGER,allocations TEXT NOT NULL DEFAULT '[]',snapshot TEXT NOT NULL DEFAULT '{}',revision INTEGER NOT NULL DEFAULT 1,created TEXT NOT NULL,updated TEXT NOT NULL,UNIQUE(price_lock_id,line_index)); CREATE TABLE IF NOT EXISTS price_lock_pool_returns(id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),line_index INTEGER NOT NULL DEFAULT 0,kind TEXT NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL,amount INTEGER,allocations TEXT NOT NULL,origin_pool_id TEXT NOT NULL,same_day INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,UNIQUE(price_lock_id,line_index,kind)); CREATE TABLE IF NOT EXISTS material_usage_order(sequence INTEGER PRIMARY KEY AUTOINCREMENT,kind TEXT NOT NULL,source_id TEXT NOT NULL,UNIQUE(kind,source_id)); INSERT INTO material_usage_order(kind,source_id) SELECT 'order',u.id FROM material_pool_usages u WHERE NOT EXISTS(SELECT 1 FROM material_usage_order s WHERE s.kind='order' AND s.source_id=u.id) ORDER BY u.created,u.rowid; `); // 去掉旧表整单唯一约束,行号0完整承接旧单和来源身份。 for (const [table, definition, columns] of [ [ 'price_lock_pool_reservations', `id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),line_index INTEGER NOT NULL DEFAULT 0,pool_id TEXT NOT NULL,mg INTEGER NOT NULL CHECK(mg>0),amount INTEGER,allocations TEXT NOT NULL DEFAULT '[]',snapshot TEXT NOT NULL DEFAULT '{}',revision INTEGER NOT NULL DEFAULT 1,created TEXT NOT NULL,updated TEXT NOT NULL,UNIQUE(price_lock_id,line_index)`, 'id,price_lock_id,pool_id,mg,amount,allocations,snapshot,revision,created,updated', ], [ 'price_lock_pool_returns', `id TEXT PRIMARY KEY,price_lock_id TEXT NOT NULL REFERENCES price_locks(id),line_index INTEGER NOT NULL DEFAULT 0,kind TEXT NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL,amount INTEGER,allocations TEXT NOT NULL,origin_pool_id TEXT NOT NULL,same_day INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,UNIQUE(price_lock_id,line_index,kind)`, 'id,price_lock_id,kind,date,mg,amount,allocations,origin_pool_id,same_day,actor,created', ], ]) if (!l.rows('PRAGMA table_info(' + table + ')').some(row => row.name === 'line_index')) { l.db.exec('SAVEPOINT price_lock_multi_upgrade'); try { l.db.exec('CREATE TABLE ' + table + '_multi(' + definition + ')'); l.db.exec('INSERT INTO ' + table + '_multi(' + columns + ') SELECT ' + columns + ' FROM ' + table); l.db.exec('DROP TABLE ' + table); l.db.exec('ALTER TABLE ' + table + '_multi RENAME TO ' + table); l.db.exec('RELEASE price_lock_multi_upgrade'); } catch (error) { l.db.exec('ROLLBACK TO price_lock_multi_upgrade'); l.db.exec('RELEASE price_lock_multi_upgrade'); throw error; } } } function sequence(l, kind, id) { if (!l.one('SELECT sequence FROM material_usage_order WHERE kind=? AND source_id=?', kind, id)) l.run('INSERT INTO material_usage_order(kind,source_id) VALUES (?,?)', kind, id); return l.one('SELECT sequence FROM material_usage_order WHERE kind=? AND source_id=?', kind, id).sequence; } function substitution(l, kind, id, quantity, reserved) { const ranges = Allocation.publicSubstitutionRanges(l, kind, id); return ranges.length ? { publicSubstitutionRanges: ranges, publicSubstitutionMg: Allocation.publicSubstitutionMg(l, kind, id, quantity), ...(reserved === undefined ? {} : { reservedPublicSubstitutionMg: Allocation.publicSubstitutionMg(l, kind, id, reserved) }), } : {}; } function decorate(l, rows) { return rows.map(r => ({ ...r, fifo_sequence: l.one("SELECT sequence FROM material_usage_order WHERE kind='order' AND source_id=?", r.id)?.sequence ?? r.fifo_sequence, ...substitution(l, 'order', r.id, r.mg), })); } function decode(r) { return r ? { ...r, allocations: JSON.parse(r.allocations), snapshot: JSON.parse(r.snapshot) } : null; } function find(l, id, lineIndex = 0) { return decode( l.one('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=? AND line_index=?', id, lineIndex), ); } // 原锁预留用非负商品行号;交付补重用 -行号-1,独立保存日期、成本和来源。 const extraIndex = index => -index - 1, itemIndex = index => (index < 0 ? -index - 1 : index); function findAll(l, id) { return l.rows('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=? ORDER BY line_index', id).map(decode); } function splitParts(parts, amount) { let left = amount; const taken = [], rest = []; for (const part of parts) { const n = Math.min(left, part.amount); if (n) taken.push({ payer: part.payer, amount: n }); if (part.amount > n) rest.push({ payer: part.payer, amount: part.amount - n }); left -= n; } if (left) throw new Error('锁价料池付款归属不足'); if (!amount && !taken.length) taken.push({ payer: parts[0]?.payer ?? 'owner', amount: 0 }); return { taken, rest }; } function split(snapshot, used) { if (snapshot.materialSources) { const parts = Allocation.splitSources(snapshot.materialSources, used), actual = Allocation.paidAmounts(parts.taken), leftover = Allocation.paidAmounts(parts.rest); return { usedMg: used, amount: actual.amount, leftoverMg: snapshot.quantity - used, leftoverCost: leftover.amount, allocations: actual.allocations, leftoverAllocations: leftover.allocations, materialSources: parts.taken, leftoverMaterialSources: parts.rest, }; } if (snapshot.amount === null) return { usedMg: used, amount: null, leftoverMg: snapshot.quantity - used, leftoverCost: null, allocations: [], leftoverAllocations: [], }; const amount = Calc.poolMaterialAmount(snapshot.basisAmount, snapshot.basisMg, snapshot.prefixMg + used) - snapshot.prefixAmount; const parts = splitParts(snapshot.allocations, amount); return { usedMg: used, amount, leftoverMg: snapshot.quantity - used, leftoverCost: snapshot.amount - amount, allocations: parts.taken, leftoverAllocations: parts.rest, }; } function detail(l, id, env, lineIndex = 0) { const r = find(l, id, lineIndex); if (!r) return null; return { ...r.snapshot, revision: r.revision, frozen: r.pool_id !== env.today() }; } function reservations(l, date) { return l .rows( `SELECT r.*,s.sequence AS fifo_sequence,p.number,p.customer,p.line,p.lines AS lock_lines,p.status,p.delivery,p.final_order_id,o.status AS order_status,o.returned_date FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id LEFT JOIN material_usage_order s ON s.kind='priceLock' AND s.source_id=r.id LEFT JOIN orders o ON o.id=p.final_order_id WHERE r.pool_id=? ORDER BY r.created,r.rowid`, date, ) .map(r => { const snapshot = JSON.parse(r.snapshot), delivery = LockLines.deliveryLines(r.delivery)[itemIndex(r.line_index)], entry = LockLines.lines({ ...r, id: r.price_lock_id, lines: r.lock_lines })[itemIndex(r.line_index)]; let mg = r.mg; if (delivery?.date === date) mg = r.line_index < 0 ? delivery.extra_mg : delivery.original_used_mg; if (r.order_status === 'returned' && r.returned_date === date) mg = 0; const effective = snapshot.amount === undefined ? { amount: null, allocations: [] } : mg === r.mg ? { amount: r.amount, allocations: JSON.parse(r.allocations), ...(snapshot.materialSources ? { materialSources: snapshot.materialSources } : {}), } : split(snapshot, mg); return { ...r, kind: 'priceLock', member: l.entityMember('price_lock', r.price_lock_id), ...(effective.materialSources ? { materialSources: effective.materialSources } : {}), date, price_lock_id: r.price_lock_id, order_id: r.final_order_id, reserved_mg: r.mg, mg, ...substitution(l, 'priceLock', r.id, mg, r.mg), active: mg > 0 ? 1 : 0, amount: effective.amount, snapshot, allocations: effective.allocations, product: entry?.line.name ?? JSON.parse(r.line).name, ...Object.fromEntries( Amounts.keys(effective.allocations).map(p => [ p + '_amount', effective.amount === null ? null : sum( effective.allocations.filter(a => a.payer === p), 'amount', ), ]), ), }; }); } function combined(l, date, rows) { return [...decorate(l, rows), ...reservations(l, date)].sort((a, b) => a.created < b.created ? -1 : a.created > b.created ? 1 : a.fifo_sequence - b.fifo_sequence, ); } function returns(l, date) { return l .rows( 'SELECT r.*,p.number,p.customer,p.line,p.lines AS lock_lines FROM price_lock_pool_returns r JOIN price_locks p ON p.id=r.price_lock_id WHERE r.date=? ORDER BY r.created,r.rowid', date, ) .map(r => ({ ...r, allocations: JSON.parse(r.allocations), ...(Allocation.returnSources(l, 'lock', r.id) ? { materialSources: Allocation.returnSources(l, 'lock', r.id) } : {}), product: LockLines.product({ ...r, id: r.price_lock_id, lines: r.lock_lines }, itemIndex(r.line_index)), sourceKind: 'return', cashAmount: 0, payer: JSON.parse(r.allocations)[0]?.payer ?? 'owner', sameDay: !!r.same_day, note: r.kind === 'cancel' ? '锁价作废回料(原成本)' : r.kind === 'leftover' ? '锁价余料回池' : '锁价退货回料', source_sequence: l.one("SELECT sequence FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?", r.id) ?.sequence ?? 0, })); } function fundingParts(purchases, start, amount) { let skip = start, left = amount; const result = []; for (const p of purchases) for (const part of p.allocations ?? [{ payer: p.payer, amount: p.amount }]) { if (skip >= part.amount) { skip -= part.amount; continue; } const n = Math.min(left, part.amount - skip); if (n) result.push({ payer: part.payer, amount: n }); left -= n; skip = 0; } if (left) throw new Error('锁价料池来源金额不足'); return result; } function allocate(pool, rows, allocatePayers) { if ( Allocation.enabled(pool) || rows.some(row => row.publicSubstitutionMg > 0 || row.reservedPublicSubstitutionMg > 0) ) return Allocation.allocate( { ...pool, materialGroups: pool.materialGroups ?? Allocation.groups(pool.purchases) }, rows, ); const missing = pool.totalAmount === null || sum(rows, 'mg') > pool.totalMg; let mg = 0, previous = 0; return rows.map(row => { const prefixMg = mg, prefixAmount = previous; mg += row.mg; const cumulative = missing ? null : Calc.poolMaterialAmount(pool.totalAmount, pool.totalMg, mg), amount = cumulative === null ? null : cumulative - previous; const paid = amount === null ? { owner_amount: null, assistant_amount: null, assistant2_amount: null } : allocatePayers( pool.purchases.filter(p => p.amount > 0), previous, amount, ); let lockSnapshot; if (row.kind === 'priceLock') { const full = missing ? null : Calc.poolMaterialAmount(pool.totalAmount, pool.totalMg, prefixMg + row.reserved_mg) - prefixAmount; let parts = []; if (full !== null) { if (prefixMg + row.reserved_mg <= pool.totalMg) parts = fundingParts( pool.purchases.filter(p => p.amount > 0), prefixAmount, full, ); else { // 短交已经释放的尾料可以被前序订单使用;只要求本单实际耗用有真实资金来源。 // 原预留与同日回料的尾段保持相同归属,二者净额为零,不能再次占用可用料。 parts = fundingParts( pool.purchases.filter(p => p.amount > 0), prefixAmount, amount, ); let tail = full - amount; const oldTail = row.snapshot.amount === null ? [] : split(row.snapshot, row.mg).leftoverAllocations; for (const p of oldTail) { const n = Math.min(tail, p.amount); if (n) parts.push({ payer: p.payer, amount: n }); tail -= n; } if (tail) parts.push({ payer: oldTail.at(-1)?.payer ?? row.snapshot.allocations?.at(-1)?.payer ?? paid.zero_payer ?? 'owner', amount: tail, }); } if (full === 0 && !parts.length) parts.push({ payer: paid.zero_payer ?? 'owner', amount: 0 }); } lockSnapshot = { poolId: pool.id, date: pool.date, quantity: row.reserved_mg, amount: full, averageRate: pool.averageRate, allocations: parts, status: full === null ? 'pending' : 'allocated', basisAmount: pool.totalAmount, basisMg: pool.totalMg, prefixMg, prefixAmount, rolling: !!pool.rolling, }; } previous = cumulative ?? 0; const result = { ...row, amount, ...paid, ...(lockSnapshot ? { lockSnapshot } : {}) }; for (const key of Object.keys(result)) if (key.endsWith('_amount') && Amounts.isKey(key.slice(0, -7)) && !Object.hasOwn(paid, key)) delete result[key]; if (!paid.allocations && row.kind !== 'priceLock') delete result.allocations; return result; }); } function returnRow(l, lock, kind, date, mg, amount, allocations, origin, actor, env, materialSources = null) { if (!mg) return; const lineIndex = lock.line_index ?? 0, old = l.one( 'SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=? AND kind=?', lock.id, lineIndex, kind, ), id = old?.id ?? randomUUID(); if (old) l.run( 'UPDATE price_lock_pool_returns SET date=?,mg=?,amount=?,allocations=?,origin_pool_id=?,same_day=? WHERE id=?', date, mg, amount, JSON.stringify(allocations), origin, origin === date ? 1 : 0, id, ); else { l.run( 'INSERT INTO price_lock_pool_returns(id,price_lock_id,line_index,kind,date,mg,amount,allocations,origin_pool_id,same_day,actor,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)', id, lock.id, lineIndex, kind, date, mg, amount, JSON.stringify(allocations), origin, origin === date ? 1 : 0, actor.name, env.now(), ); require('../materials/rolling-material-pools').registerSource(l, 'lock_return', id); } if (materialSources) Allocation.saveReturn(l, 'lock', id, materialSources); else l.run("DELETE FROM material_return_sources WHERE return_kind='lock' AND return_id=?", id); } function materialAllocations(snapshot, used) { const part = split(snapshot, used); if (part.materialSources) return part.materialSources.flatMap(s => s.allocations.map(p => ({ source: 'original', quantity: s.quantity, rate: s.averageRate ?? snapshot.averageRate, amount: p.amount, payer: p.payer, weighted: true, poolId: s.poolId ?? snapshot.poolId, materialKind: s.kind, materialOwner: s.member, })), ); return part.amount === null ? [] : part.allocations.map(p => ({ source: 'original', quantity: used, rate: snapshot.averageRate, amount: p.amount, payer: p.payer, weighted: true, poolId: snapshot.poolId, })); } function update(l, row, pool, actor, env, { skipJournalOrder = null } = {}) { const snapshot = row.lockSnapshot, old = row.snapshot, changed = JSON.stringify(snapshot) !== JSON.stringify(old); if (!changed) return; const revision = row.revision + 1; l.run( 'UPDATE price_lock_pool_reservations SET amount=?,allocations=?,snapshot=?,revision=?,updated=? WHERE id=?', snapshot.amount, JSON.stringify(snapshot.allocations), JSON.stringify(snapshot), revision, env.now(), row.id, ); l.run('UPDATE price_locks SET revision=revision+1,updated=? WHERE id=?', env.now(), row.price_lock_id); if (row.line_index < 0) { updateExtra(l, row, snapshot, actor, env, skipJournalOrder); return; } const lock = l.one('SELECT * FROM price_locks WHERE id=?', row.price_lock_id), lockedLines = LockLines.lines(lock), entry = lockedLines[row.line_index], lockedLine = entry.line; entry.material_amount = snapshot.amount; entry.buy_rate = snapshot.averageRate; entry.material_source = 'pool'; lockedLine.costParts = { ...lockedLine.costParts, material: snapshot.amount }; lockedLine.cost = Object.values(lockedLine.costParts).some(v => v === null) ? null : sum( Object.values(lockedLine.costParts).map(amount => ({ amount })), 'amount', ); LockLines.save(l, lock, lockedLines); if (lock.status === 'cancelled') { const returned = l.one( "SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=? AND kind='cancel'", lock.id, row.line_index, ); if (returned) returnRow( l, { ...lock, line_index: row.line_index }, 'cancel', returned.date, row.mg, snapshot.amount, snapshot.allocations, snapshot.poolId, actor, env, snapshot.materialSources ?? null, ); } if (lock.final_order_id) { const order = l.rawOrder(lock.final_order_id), line = order.lines[row.line_index], deliveries = LockLines.deliveryLines(lock.delivery), delivery = deliveries[row.line_index], part = split(snapshot, delivery.original_used_mg), before = line.costParts.material, lineLock = { ...lock, line_index: row.line_index }; const extra = (line.materialAllocations ?? []).filter(a => a.source === 'extra'); line.materialAllocations = [...materialAllocations(snapshot, delivery.original_used_mg), ...extra]; line.priceLockPool = { ...snapshot, quantity: delivery.original_used_mg, amount: part.amount, allocations: part.allocations, ...(part.materialSources ? { materialSources: part.materialSources } : {}), priceLockId: lock.id, lineId: entry.id, line_index: row.line_index, }; line.costParts.material = part.amount === null || line.priceLockExtraPool?.amount === null ? null : part.amount + sum(extra, 'amount'); line.cost = Object.values(line.costParts).some(v => v === null) ? null : sum( Object.values(line.costParts).map(amount => ({ amount })), 'amount', ); l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(order.lines), order.id); deliveries[row.line_index] = { ...delivery, leftover_cost: part.leftoverCost }; l.run( 'UPDATE price_locks SET delivery=? WHERE id=?', JSON.stringify(LockLines.aggregateDelivery(JSON.parse(lock.delivery), deliveries)), lock.id, ); returnRow( l, lineLock, 'leftover', delivery.date, part.leftoverMg, part.leftoverCost, part.leftoverAllocations, snapshot.poolId, actor, env, part.leftoverMaterialSources, ); if (order.status === 'returned') returnRow( l, lineLock, 'goods', order.returned_date, delivery.original_used_mg, part.amount, part.allocations, snapshot.poolId, actor, env, part.materialSources, ); const delta = (line.costParts.material ?? 0) - (before ?? 0); if (order.id !== skipJournalOrder) { if (delta && order.status === 'delivered') l.journal(order.id, order.delivered_date, '锁价料池成本调整', 0, delta, 0); if (delta && order.status === 'returned') { l.journal(order.id, order.delivered_date, '锁价料池原耗用调整', 0, delta, 0); l.journal(order.id, order.returned_date, '锁价退货成本冲回调整', 0, -delta, 0); } l.touch(order.id); l.dirty(order.date); } } l.dirty(lock.date); l.audit('price-lock:' + lock.id, '锁价料池加权更新', actor, { poolId: pool.id, line_index: row.line_index, before: old, after: snapshot, }); } function reserve(l, lock, pool, actor, env) { const available = Allocation.eligible(pool, l.entityMember('price_lock', lock.id) ?? l.memberFor(actor)); if (available.eligibleRemainingMg < lock.locked_mg) env.fail('当日料池可用克重不足或成本待补,请先核实购料'); const id = randomUUID(), created = env.now(); l.run( 'INSERT INTO price_lock_pool_reservations(id,price_lock_id,line_index,pool_id,mg,created,updated) VALUES (?,?,?,?,?,?,?)', id, lock.id, lock.line_index ?? 0, pool.id, lock.locked_mg, created, created, ); sequence(l, 'priceLock', id); } function prepareDelivery(l, lock, date, used, actor, env) { const reservation = find(l, lock.id, lock.line_index ?? 0); if (!reservation) return null; const snapshot = reservation.snapshot; if (snapshot.amount === null || snapshot.amount === undefined) env.fail('锁价原料池成本待补,请先核实购料后交付', 409); const part = split(snapshot, used); return { ...part, snapshot }; } function finishDelivery(l, lock, delivery, actor, env) { const r = find(l, lock.id, lock.line_index ?? 0); if (!r) return; const part = split(r.snapshot, delivery.original_used_mg); returnRow( l, lock, 'leftover', delivery.date, part.leftoverMg, part.leftoverCost, part.leftoverAllocations, r.pool_id, actor, env, part.leftoverMaterialSources, ); } function updateExtra(l, row, snapshot, actor, env, skipJournalOrder) { const lock = l.one('SELECT * FROM price_locks WHERE id=?', row.price_lock_id), index = itemIndex(row.line_index); if (lock.final_order_id) { const order = l.rawOrder(lock.final_order_id), line = order.lines[index], before = line.costParts.material; line.priceLockExtraPool = { ...snapshot, priceLockId: lock.id, line_index: index }; line.materialAllocations = [ ...(line.materialAllocations ?? []).filter(a => a.source === 'original'), ...materialAllocations(snapshot, row.mg).map(a => ({ ...a, source: 'extra' })), ]; line.costParts.material = snapshot.amount === null || line.priceLockPool?.amount === null ? null : sum(line.materialAllocations, 'amount'); line.cost = Object.values(line.costParts).some(v => v === null) ? null : Object.values(line.costParts).reduce((a, b) => a + b, 0); l.run('UPDATE orders SET lines=? WHERE id=?', JSON.stringify(order.lines), order.id); if (order.status === 'returned') returnRow( l, { ...lock, line_index: row.line_index }, 'goods', order.returned_date, row.reserved_mg, snapshot.amount, snapshot.allocations, snapshot.poolId, actor, env, snapshot.materialSources, ); const delta = (line.costParts.material ?? 0) - (before ?? 0); if (order.id !== skipJournalOrder) { if (delta) l.journal(order.id, order.delivered_date, '锁价补重料池成本调整', 0, delta, 0); if (delta && order.status === 'returned') l.journal(order.id, order.returned_date, '锁价补重退货成本冲回', 0, -delta, 0); l.touch(order.id); l.dirty(order.date); } } l.dirty(row.pool_id); l.audit('price-lock:' + lock.id, '交付补重料池加权更新', actor, { line_index: index, poolId: row.pool_id, before: row.snapshot, after: snapshot, }); } function recordReturn(l, order, date, input, actor, env) { const lock = l.one('SELECT * FROM price_locks WHERE final_order_id=?', order.id), rows = lock ? findAll(l, lock.id) : []; if (!rows.length) return false; const indices = [...new Set(rows.map(r => itemIndex(r.line_index)))]; for (const index of indices) { const line = order.lines[index], destination = input.returnPockets?.[index] ?? line.pocket; if (!env.selfPockets?.includes(destination)) env.fail('料池锁价黄金须退回自有货盘'); const delivery = LockLines.deliveryAt(lock, index); for (const source of ['original', 'extra']) { const mg = source === 'original' ? delivery.original_used_mg : delivery.extra_mg; if (!mg) continue; const key = source === 'original' ? index : extraIndex(index), r = rows.find(r => r.line_index === key), lineLock = { ...lock, line_index: key }; if (r) { const part = split(r.snapshot, mg); if (part.amount === null) env.fail('锁价料池成本待补,不能退货回料', 409); returnRow( l, lineLock, 'goods', date, mg, part.amount, part.allocations, r.pool_id, actor, env, part.materialSources, ); } else { const parts = (line.materialAllocations ?? []).filter(a => a.source === source); returnRow( l, { ...lock, line_index: index }, source === 'extra' ? 'extra' : 'manual_original', date, mg, sum(parts, 'amount'), parts.map(a => ({ payer: a.payer, amount: a.amount })), '', actor, env, ); } } } return indices; } function atomicEdit(l, fn) { l.db.exec('SAVEPOINT price_lock_pool_order_edit'); try { const value = fn(); l.db.exec('RELEASE price_lock_pool_order_edit'); return value; } catch (error) { l.db.exec('ROLLBACK TO price_lock_pool_order_edit'); l.db.exec('RELEASE price_lock_pool_order_edit'); throw error; } } function editableLock(l, value, actor, env) { if (!actor || !['owner', 'assistant'].includes(actor.role)) env.fail('请使用麦麦或助理账号修改锁价料池', 403); const id = typeof value === 'string' ? value : value?.id; l.assertAccess('price_lock', id, actor); const lock = l.one('SELECT * FROM price_locks WHERE id=?', id); if (!lock) env.fail('锁价单不存在', 404); return lock; } function affectedDates(reservation, rows, extra = []) { return [ ...new Set( [reservation?.pool_id, ...rows.flatMap(row => [row.origin_pool_id, row.date]), ...extra].filter(Boolean), ), ].sort(); } function assertEditDates(l, dates, actor, env) { const rolling = require('../materials/rolling-material-pools'); if (!rolling.enabled(l)) return; if (actor.role !== 'owner' && dates.some(date => date !== env.today())) env.fail('历史锁价料池更正须由麦麦复核', 403); for (const date of dates) rolling.assertDate(l, date, env); } function rebuildAffected(l, dates, actor, env, options = {}) { if (!dates.length) return; const rolling = require('../materials/rolling-material-pools'); // 共同料池重算需要读取所有成员来源,写入权限仍在外层按本单及日期检查。 return l.scope( null, () => { if (rolling.enabled(l)) { for (const date of dates) if (!rolling.isDay(l, date)) require('../materials/material-pools').reconcile(l, date, date, actor, env, options); return rolling.rebuildFrom(l, dates[0], actor, env, { ...options, ensureDates: dates }); } for (const date of dates) require('../materials/material-pools').reconcile(l, date, date, actor, env, options); }, null, ); } // 调用方先保存独立手填的最终成本与商品行;此处只解除池关系,不造采购、现金或实物。 function releaseForOrderEdit(l, value, actor, env, options = {}) { return atomicEdit(l, () => { const lock = editableLock(l, value, actor, env), lineIndex = options.lineIndex ?? 0, reservation = find(l, lock.id, lineIndex), rows = l.rows( 'SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=? ORDER BY rowid', lock.id, lineIndex, ), dates = affectedDates(reservation, rows); if (!reservation && !rows.length) return { released: false, reservation: null, returns: [], affectedDates: [], earliestDate: null }; assertEditDates(l, dates, actor, env); for (const row of rows) l.run("DELETE FROM material_return_sources WHERE return_kind='lock' AND return_id=?", row.id); for (const row of rows) l.run("DELETE FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?", row.id); l.run('DELETE FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=?', lock.id, lineIndex); if (reservation) { l.run("DELETE FROM material_usage_order WHERE kind='priceLock' AND source_id=?", reservation.id); l.run("DELETE FROM material_public_substitutions WHERE kind='priceLock' AND source_id=?", reservation.id); l.run('DELETE FROM price_lock_pool_reservations WHERE id=?', reservation.id); } rebuildAffected(l, dates, actor, env, options); for (const date of dates) l.dirty(date); return { released: true, reservation, returns: rows, affectedDates: dates, earliestDate: dates[0] }; }); } // 跨天作废保留原日占用事实,以原成本在实际生效日回料;不倒改历史加权。 function cancelReservations(l, value, actor, env) { return atomicEdit(l, () => { const lock = editableLock(l, value, actor, env), date = env.today(), rows = findAll(l, lock.id), cross = rows.filter(row => row.pool_id < date), same = rows.filter(row => row.pool_id === date); if (rows.some(row => row.pool_id > date)) env.fail('锁价料池日期晚于作废日期,请先核对', 409); for (const row of cross) { if ( !Number.isSafeInteger(row.amount) || row.amount < 0 || row.snapshot.amount !== row.amount || row.snapshot.quantity !== row.mg || sum(row.allocations, 'amount') !== row.amount ) env.fail('原锁价料费或付款来源待核实,不能按未知成本回池,请先核实原料费', 409); } // 先建立当日结转,冻结的是原日预留仍有效时的剩料,避免回料重复结转。 const rolling = require('../materials/rolling-material-pools'); if (cross.length && rolling.enabled(l)) rolling.reconcile(l, date, actor, env); for (const row of cross) returnRow( l, { ...lock, line_index: row.line_index }, 'cancel', date, row.mg, row.amount, row.allocations, row.pool_id, actor, env, row.snapshot.materialSources ?? null, ); for (const row of same) releaseForOrderEdit(l, lock, actor, env, { lineIndex: row.line_index, preservePriceLockIds: [lock.id] }); if (cross.length) rebuildAffected(l, [date], actor, env, { preservePriceLockIds: [lock.id] }); return { date, returned: cross.map(row => ({ lineIndex: row.line_index, mg: row.mg, amount: row.amount, originPoolId: row.pool_id, allocations: row.allocations, })), releasedSameDay: same.map(row => row.line_index), }; }); } // 仅挪动交付日时原锁定分厘和付款归属冻结;余料沿原回料身份移日,不能成为第二笔采购。 function moveDeliveryDate(l, value, nextDate, actor, env, { skipJournalOrder = null } = {}) { return atomicEdit(l, () => { const lock = editableLock(l, value, actor, env), reservations = findAll(l, lock.id); if (!reservations.length) return { moved: false, affectedDates: [], earliestDate: null }; const delivery = lock.delivery ? JSON.parse(lock.delivery) : null; if (!delivery || !lock.final_order_id) env.fail('只有已交付锁价单可以调整交付日期'); const date = env.day(nextDate, lock.date); if (date < lock.date) env.fail('交付日期不能早于锁价日期'); if (date === delivery.date) return { moved: false, affectedDates: [], earliestDate: null }; // 两个交付日都跨过原锁日时,原预留占用完全相同;只从余料实际变动的最早日重建。 const rows = l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY rowid', lock.id), dates = [...new Set([delivery.date, date])].sort(); assertEditDates(l, dates, actor, env); for (const row of reservations.filter(row => row.line_index < 0)) l.run('UPDATE price_lock_pool_reservations SET pool_id=? WHERE id=?', date, row.id); const updated = LockLines.aggregateDelivery( { ...delivery, date }, LockLines.deliveryLines(delivery).map(row => ({ ...row, date })), ); l.run('UPDATE price_locks SET delivery=?,updated=? WHERE id=?', JSON.stringify(updated), env.now(), lock.id); for (const row of rows.filter(row => row.kind === 'leftover')) l.run( 'UPDATE price_lock_pool_returns SET date=?,same_day=? WHERE id=?', date, row.origin_pool_id === date ? 1 : 0, row.id, ); rebuildAffected(l, dates, actor, env, { skipJournalOrder, preservePriceLockIds: [lock.id], repriceExtraPriceLockIds: [lock.id], }); for (const row of findAll(l, lock.id).filter(row => row.line_index < 0)) if (row.amount === null) env.fail('更改交付日期后补重料池不足或成本待补,请先核实料源', 409); const rolling = require('../materials/rolling-material-pools'); if (rolling.enabled(l)) for (const row of l.rows('SELECT date FROM material_rolling_days WHERE date>=? ORDER BY date', dates[0])) { const pool = rolling.readPool(l, row.date, env, { internal: true }); if (pool.shortageMg > 0) env.fail( '调整交付日期后,' + row.date + '料池短料;原日余料已被其他订单使用,请先核实金料来源后再改交付日期', 409, ); } for (const date of dates) l.dirty(date); return { moved: true, affectedDates: dates, earliestDate: dates[0], delivery: updated }; }); } module.exports = { extraIndex, itemIndex, initialize, sequence, decorate, find, findAll, detail, reservations, combined, returns, allocate, update, reserve, split, materialAllocations, prepareDelivery, finishDelivery, recordReturn, releaseForOrderEdit, cancelReservations, moveDeliveryDate, };