'use strict'; // 只给新回收采购标记个人料来源;既有回收采购没有标记时继续作为历史公共料。 const { createHash } = require('node:crypto'); const TeamMembers = require('../team/team-members'); const exists = (l, table) => !!l.one("SELECT name FROM sqlite_master WHERE type='table' AND name=?", table); function fail(message) { const error = new Error(message); error.status = 409; throw error; } function initialize(l) { l.db.exec(` CREATE TABLE IF NOT EXISTS recovery_material_batches( purchase_id TEXT PRIMARY KEY REFERENCES material_purchases(id),recovery_id TEXT NOT NULL REFERENCES recoveries(id), member TEXT NOT NULL,created TEXT NOT NULL); CREATE INDEX IF NOT EXISTS ix_recovery_material_member ON recovery_material_batches(member,purchase_id); `); require('../../core/member-schema').removeMemberCheck(l, 'recovery_material_batches', 'member'); } function registerSource(l, purchaseId, { recoveryId, member } = {}) { if (!TeamMembers.keys(l).includes(member)) fail('个人回收料缺少有效业务归属'); const purchase = l.one('SELECT id,created FROM material_purchases WHERE id=?', purchaseId), recovery = l.one('SELECT id,member FROM recoveries WHERE id=?', recoveryId); if (!purchase || !recovery || recovery.member !== member) fail('个人回收料与原回收归属不一致'); const existing = l.one('SELECT * FROM recovery_material_batches WHERE purchase_id=?', purchaseId); if (existing) { if (existing.recovery_id !== recoveryId || existing.member !== member) fail('已有回收料批次归属不能更换'); return false; } l.run('INSERT INTO recovery_material_batches VALUES (?,?,?,?)', purchaseId, recoveryId, member, purchase.created); return true; } function purchaseSource(l, purchaseId) { if (!exists(l, 'recovery_material_batches')) return null; const row = l.one('SELECT recovery_id,member FROM recovery_material_batches WHERE purchase_id=?', purchaseId); return row ? { materialOwner: row.member, materialKind: 'personal_recovery', recoveryId: row.recovery_id } : null; } function sources(value) { if (value === undefined || value === null || value === '') return []; const result = typeof value === 'string' ? JSON.parse(value) : value; if (!Array.isArray(result)) fail('回收料批次追溯资料无效'); return result; } function batches(value) { const totals = new Map(); for (const source of sources(value)) for (const batch of source.batches ?? []) { if (typeof batch.purchaseId !== 'string' || !Number.isSafeInteger(batch.mg) || batch.mg < 0) fail('回收料批次追溯克重无效'); totals.set(batch.purchaseId, (totals.get(batch.purchaseId) || 0) + batch.mg); } return totals; } function lockBatches(l, lockId, snapshot, lineIndex = 0) { const result = batches(snapshot.materialSources); if (exists(l, 'material_return_sources')) for (const returned of l.rows( "SELECT s.sources FROM material_return_sources s JOIN price_lock_pool_returns r ON s.return_kind='lock' AND s.return_id=r.id WHERE r.price_lock_id=? AND r.line_index=? ORDER BY r.rowid", lockId, lineIndex, )) for (const [purchaseId, mg] of batches(returned.sources)) result.set(purchaseId, (result.get(purchaseId) || 0) - mg); for (const mg of result.values()) if (mg < 0) fail('锁价回收料耗用与回料克重不一致,请先核对料池'); return result; } function blockedUsages(l, purchaseId) { if (!purchaseSource(l, purchaseId)) return null; const result = new Map(); const add = (key, row) => { if (!row.mg) return; const previous = result.get(key); result.set(key, previous ? { ...previous, mg: previous.mg + row.mg } : row); }; if (exists(l, 'material_usage_sources')) for (const row of l.rows( 'SELECT u.order_id,u.line_index,o.number,s.sources FROM material_usage_sources s JOIN material_pool_usages u ON u.id=s.usage_id JOIN orders o ON o.id=u.order_id WHERE u.active=1 AND instr(s.sources,?)>0 ORDER BY u.created,u.rowid', purchaseId, )) { let mg = batches(row.sources).get(purchaseId) || 0; // 一体售后保留原耗用以锁定历史成本;实物已回流的批次不能仍作为第二份已用量。 if ( exists(l, 'order_after_sales') && l.one('SELECT order_id FROM order_after_sales WHERE order_id=?', row.order_id) ) for (const returned of l.rows( "SELECT s.sources FROM material_return_sources s JOIN material_rolling_returns r ON s.return_kind='order' AND s.return_id=r.id WHERE r.order_id=? AND r.line_index=?", row.order_id, row.line_index, )) mg -= batches(returned.sources).get(purchaseId) || 0; if (mg < 0) fail('售后退回批次超过原实际耗用,请先核对原单与回料'); add('order:' + row.order_id, { orderId: row.order_id, number: row.number, mg }); } if (exists(l, 'price_lock_pool_reservations')) for (const row of l.rows( 'SELECT r.id AS reservation_id,r.line_index,r.snapshot,p.id,p.final_order_id,p.number FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id WHERE instr(r.snapshot,?)>0 ORDER BY r.created,r.rowid', purchaseId, )) add('lock:' + row.id, { orderId: row.final_order_id ?? null, number: row.number, mg: lockBatches(l, row.id, JSON.parse(row.snapshot), row.line_index).get(purchaseId) || 0, priceLockId: row.id, }); return [...result.values()]; } function purchaseStatus(l, purchaseId) { const source = purchaseSource(l, purchaseId); if (!source) return null; const purchase = l.one('SELECT mg,deleted_at FROM material_purchases WHERE id=?', purchaseId); if (!purchase) return null; const usages = blockedUsages(l, purchaseId), usedMg = usages.reduce((total, row) => total + row.mg, 0); if (usedMg > purchase.mg) fail('回收批次耗用超过原克重,请先核对料池'); return { purchaseId, recoveryId: source.recoveryId, member: source.materialOwner, mg: purchase.mg, usedMg, remainingMg: purchase.deleted_at ? 0 : purchase.mg - usedMg, usages, }; } function cancelPurchase(l, purchaseId) { if (!purchaseSource(l, purchaseId)) return; const allocation = require('../materials/material-pool-allocation'); // 包含已退回的历史头尾段;重建原日及后续回料时,不能让已取消批次重新流入个人池。 for (const row of l.rows( 'SELECT u.id,s.sources FROM material_usage_sources s JOIN material_pool_usages u ON u.id=s.usage_id WHERE instr(s.sources,?)>0 ORDER BY u.rowid', purchaseId, )) allocation.substitutePurchase(l, 'order', row.id, purchaseId, sources(row.sources)); for (const row of l.rows( 'SELECT id,snapshot FROM price_lock_pool_reservations WHERE instr(snapshot,?)>0 ORDER BY rowid', purchaseId, )) allocation.substitutePurchase( l, 'priceLock', row.id, purchaseId, sources(JSON.parse(row.snapshot).materialSources), ); } function dependency(l) { if (!exists(l, 'recovery_material_batches') || !l.one('SELECT purchase_id FROM recovery_material_batches LIMIT 1')) return null; const names = ['recovery_material_batches', 'material_usage_sources', 'material_return_sources'].filter(name => exists(l, name), ); if ( exists(l, 'material_public_substitutions') && l.one('SELECT source_id FROM material_public_substitutions LIMIT 1') ) names.push('material_public_substitutions'); return createHash('sha256') .update(JSON.stringify(names.map(name => [name, l.rows('SELECT * FROM ' + name + ' ORDER BY rowid')]))) .digest('hex'); } function ownershipReason(l, order, target = null, env) { if (!exists(l, 'recovery_material_batches') || !l.one('SELECT purchase_id FROM recovery_material_batches LIMIT 1')) return ''; const usages = exists(l, 'material_usage_sources') ? l.rows( 'SELECT u.pool_id,s.sources FROM material_pool_usages u JOIN material_usage_sources s ON s.usage_id=u.id WHERE u.order_id=? AND u.active=1', order.id, ) : []; const dates = new Set(usages.map(row => row.pool_id)); let personal = usages.some(row => sources(row.sources).some(source => source.kind === 'personal_recovery' && source.quantity > 0), ); const reservations = l.rows( 'SELECT r.*,p.id AS lock_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, ); for (const reservation of reservations) { dates.add(reservation.pool_id); const net = lockBatches(l, reservation.lock_id, JSON.parse(reservation.snapshot), reservation.line_index); personal ||= [...net].some(([id, mg]) => mg > 0 && purchaseSource(l, id)); } if (!personal && target) for (const date of dates) { const pool = require('../materials/material-pools').readPool(l, date, env, { internal: true }); if (pool.personalPools?.[target]?.totalMg > 0) { personal = true; break; } } return personal ? '本单涉及个人回收料,不能直接转给其他归属人;请先更正用料并释放个人料占用,再调整归属。' : ''; } module.exports = { initialize, registerSource, purchaseSource, blockedUsages, purchaseStatus, cancelPurchase, dependency, ownershipReason, };