Files
weiguang-jewelry-ledger/新账系统/recovery-material.js
T

86 lines
6.5 KiB
JavaScript

'use strict';
// 只给新回收采购标记个人料来源;既有回收采购没有标记时继续作为历史公共料。
const {createHash}=require('node:crypto');
const MEMBERS=['owner','assistant','assistant2'];
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 CHECK(member IN ('owner','assistant','assistant2')),created TEXT NOT NULL);
CREATE INDEX IF NOT EXISTS ix_recovery_material_member ON recovery_material_batches(member,purchase_id);
`);}
function registerSource(l,purchaseId,{recoveryId,member}={}){
if(!MEMBERS.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){
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=? ORDER BY r.rowid",lockId))
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,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))
add('order:'+row.order_id,{orderId:row.order_id,number:row.number,mg:batches(row.sources).get(purchaseId)||0});
if(exists(l,'price_lock_pool_reservations'))for(const row of l.rows('SELECT 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)).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 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));
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 reservation=l.one('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);
if(reservation){
dates.add(reservation.pool_id);
const net=lockBatches(l,reservation.lock_id,JSON.parse(reservation.snapshot));
personal||=[...net].some(([id,mg])=>mg>0&&purchaseSource(l,id));
}
if(!personal&&target)for(const date of dates){
const pool=require('./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,dependency,ownershipReason};