Files

26 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

'use strict';
// 单据级现金与折扣只记录一次;行级锁重、料费及交付使用稳定身份关联。
const sum=(rows,key)=>rows.reduce((n,row)=>n+(row[key]??0),0);
function lines(lock){
const stored=typeof lock.lines==='string'?JSON.parse(lock.lines):lock.lines;
if(Array.isArray(stored)&&stored.length)return stored.map((row,index)=>({...row,id:row.id??(index?lock.id+':'+index:lock.id),line_index:index}));
return [{id:lock.id,line_index:0,line:typeof lock.line==='string'?JSON.parse(lock.line):lock.line,locked_mg:lock.locked_mg,sell_rate:lock.sell_rate,buy_rate:lock.buy_rate,buy_payer:lock.buy_payer,material_amount:lock.material_amount}];
}
function deliveryLines(delivery){
const value=typeof delivery==='string'?JSON.parse(delivery):delivery;
return !value?[]:Array.isArray(value.lines)?value.lines:[value];
}
function deliveryAt(lock,index=0){return deliveryLines(lock.delivery)[index]??null;}
function aggregateDelivery(delivery,rows){
const result={...delivery,lines:rows};
for(const key of ['quantity','original_used_mg','extra_mg','leftover_mg'])result[key]=sum(rows,key);
result.leftover_cost=rows.some(row=>row.leftover_cost===null)?null:sum(rows,'leftover_cost');
if(rows.length===1)result.inventory=rows[0].inventory;else delete result.inventory;
return result;
}
function save(ledger,lock,rows){
const first=rows[0],amount=rows.some(row=>row.material_amount===null)?null:sum(rows,'material_amount');
ledger.run('UPDATE price_locks SET lines=?,line=?,locked_mg=?,sell_rate=?,buy_rate=COALESCE(?,buy_rate),buy_payer=?,material_amount=COALESCE(?,material_amount) WHERE id=?',JSON.stringify(rows),JSON.stringify(first.line),sum(rows,'locked_mg'),first.sell_rate,first.buy_rate,first.buy_payer,amount,lock.id);
}
function product(lock,index=null){const rows=lines(lock);return index===null?rows.map(row=>row.line.name).join('、'):rows[index]?.line?.name??rows[0]?.line?.name??'';}
module.exports={lines,deliveryLines,deliveryAt,aggregateDelivery,save,product};