Files
weiguang-jewelry-ledger/新账系统/order-book.js
T

244 lines
21 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
// 订单簿只读投影:普通订单按开单日,锁价收付按实际发生日,金额始终为整数分。
const Calc=require('./public/calculations');
const AMOUNTS=['sale','material','laborAndFees','unallocated','totalCost','profit','ownerCost','assistantCost','assistant2Cost'];
const FINAL_STATUSES=['delivered','returned','cancelled'];
const STATUSES=['all','draft','confirmed',...FINAL_STATUSES,'after_sale','recovery'];
const COST_COMPONENTS=Object.fromEntries(Object.entries(Calc.costLabels).map(([key,name])=>[name,key]));
const add=(rows,key)=>rows.reduce((total,row)=>total+(row[key]??0),0);
function invalid(message){const error=new Error(message);error.status=400;throw error;}
function component(item){return item.component||(item.kind==='goods'?(COST_COMPONENTS[item.name]||'unallocated'):'fee');}
const compareText=(a,b)=>a<b?-1:a>b?1:0;
function lineType(line){
const source=line.pocket==='现货'?'货盘现货':line.pocket?'货盘·'+line.pocket:'配货';
return source+(Calc.isSilver(line.name)?' · 银饰':'');
}
function orderRow(order){
const draft=order.status==='draft',excluded=['returned','cancelled'].includes(order.status);
const materialPoolIds=[...new Set(order.lines.filter(line=>line.costMaterial?.mode==='pool').map(line=>line.costMaterial.poolId))];
const materialCostPending=!draft&&!excluded&&Boolean(order.materialCostPending||order.lines.some(line=>line.materialPool?.status==='pending'));
const costs=Calc.orderCosts(order);
const costItems=draft?[]:costs.rows.filter(item=>!item.excluded&&item.kind!=='pending').map(item=>({...item,component:component(item)}));
const pendingCostItems=draft?[]:costs.rows.filter(item=>item.kind==='pending').map(item=>({...item,component:'fee'}));
const materialItems=costItems.filter(item=>item.component==='material');
const laborAndFeeItems=costItems.filter(item=>!['material','unallocated'].includes(item.component));
const unallocatedItems=costItems.filter(item=>item.component==='unallocated');
const missingItems=costItems.filter(item=>item.amount==null);
const missingCosts=missingItems.length,pendingCosts=pendingCostItems.length;
const legacyUnallocated=unallocatedItems.length>0;
const known={
sale:draft?0:excluded?0:order.total,
material:add(materialItems,'amount'),laborAndFees:add(laborAndFeeItems,'amount'),
unallocated:add(unallocatedItems,'amount'),totalCost:add(costItems,'amount'),profit:0,
ownerCost:add(costItems.filter(item=>item.payer==='owner'),'amount'),
assistantCost:add(costItems.filter(item=>item.payer==='assistant'),'amount'),
assistant2Cost:add(costItems.filter(item=>item.payer==='assistant2'),'amount')
};
const unknown={
sale:draft,
material:draft||legacyUnallocated||materialItems.some(item=>item.amount==null),
laborAndFees:draft||legacyUnallocated||laborAndFeeItems.some(item=>item.amount==null)||pendingCosts>0,
unallocated:draft||unallocatedItems.some(item=>item.amount==null),
totalCost:draft||missingCosts>0||pendingCosts>0,
ownerCost:draft||[...missingItems,...pendingCostItems].some(item=>item.payer==='owner'),
assistantCost:draft||[...missingItems,...pendingCostItems].some(item=>item.payer==='assistant'),
assistant2Cost:draft||[...missingItems,...pendingCostItems].some(item=>item.payer==='assistant2')
};
// 利润沿用账本已记账净额;旧单尚未交付或成本不完整时,不把预估当作利润。
const profitMismatch=FINAL_STATUSES.includes(order.status)&&!unknown.totalCost&&order.profit!==known.sale-known.totalCost;
unknown.profit=!FINAL_STATUSES.includes(order.status)||unknown.totalCost||profitMismatch;
if(!unknown.profit)known.profit=order.profit;
if(!order.member&&!costItems.some(item=>item.payer==='assistant2')&&!pendingCostItems.some(item=>item.payer==='assistant2')){delete known.assistant2Cost;delete unknown.assistant2Cost;}
const values=Object.fromEntries(AMOUNTS.filter(key=>Object.hasOwn(known,key)).map(key=>[key,unknown[key]?null:known[key]]));
const hints=[];
if(draft)hints.push('旧草稿,未计入实际销售、成本和利润');
else{
if(missingCosts)hints.push(`${missingCosts}项成本缺失,金额仅含已知部分`);
if(materialCostPending)hints.push('日料池料费待补,成本和利润尚未核算完整');
if(pendingCosts)hints.push(`${pendingCosts}项旧单费用未入账,预估未计入实际成本`);
if(order.status==='confirmed')hints.push('旧单账务未补齐,利润尚未记账');
if(legacyUnallocated)hints.push('原单货品成本未分项,计入未分项成本');
if(profitMismatch)hints.push('成本与利润流水不一致,待复核');
if(excluded)hints.push(order.cancellationApproved?'录错作废已获麦麦批准,本单销售、成本与收款记账已撤销,原单和审批记录保留':'原售价与货品成本已冲回,实际费用保留');
}
return {
id:order.id,...(order.member?{member:order.member,funds_mode:order.funds_mode}:{}),number:order.number,paper_number:order.paper_number,date:order.date,created:order.created,
...(order.price_lock_id?{price_lock_id:order.price_lock_id}:{}),
...(order.recovery_id?{recovery_id:order.recovery_id,recovery_mode:'exchange',nonCashOffset:order.nonCashOffset,cashPaid:order.cashPaid,netSettlement:order.netSettlement,recovery_immutable_reason:order.recovery_immutable_reason}:{}),
...(order.cancellationPending?{cancellationPending:order.cancellationPending}:{}),
...(order.cancellationApproved?{cancellationApproved:order.cancellationApproved}:{}),
...(materialPoolIds.length?{materialPoolIds,materialCostPending}:{}),
customer:order.customer,salesperson:order.salesperson,status:order.status,note:order.note,
types:[...new Set(order.lines.map(lineType))],
mg:add(order.lines.filter(line=>line.unit==='g'),'quantity'),
summaryMg:add(order.lines.filter(line=>line.unit==='g'&&!Calc.isSilver(line.name)),'quantity'),
pieces:add(order.lines.filter(line=>line.unit==='件'),'quantity'),
originalSale:order.total,...values,known,costItems,laborAndFeeItems,pendingCostItems,
missingCosts,pendingCosts,unknownCosts:missingCosts+pendingCosts,legacyUnallocated,
incomplete:draft||order.status==='confirmed'||unknown.totalCost||profitMismatch,
costHint:hints.join(';'),balance:order.balance,
revision:order.revision,reviewed_revision:order.reviewed_revision
};
}
function afterSaleRow(record){
const known={sale:0,material:0,laborAndFees:record.amount,unallocated:0,totalCost:record.amount,
profit:record.amount===0?0:-record.amount,ownerCost:record.payer==='owner'?record.amount:0,assistantCost:record.payer==='assistant'?record.amount:0,assistant2Cost:record.payer==='assistant2'?record.amount:0};
if(record.payer!=='assistant2'&&!record.member)delete known.assistant2Cost;
const item={kind:'afterSale',after_sale_id:record.id,name:record.project,source:'售后 · '+record.date,
amount:record.amount,payer:record.payer,component:'fee',calculation:null};
return {id:record.id,kind:'afterSale',after_sale_id:record.id,number:'售后',paper_number:'',date:record.date,created:record.created,
customer:record.customer,salesperson:record.actor,status:'after_sale',project:record.project,note:record.project,
amount:record.amount,payer:record.payer,types:['售后'],mg:0,summaryMg:0,pieces:0,originalSale:0,...known,known,
costItems:[item],laborAndFeeItems:[item],pendingCostItems:[],missingCosts:0,pendingCosts:0,unknownCosts:0,
legacyUnallocated:false,incomplete:false,costHint:'独立售后支出,计入所选日期利润',balance:0,revision:1,reviewed_revision:1};
}
function recoveryRow(record){
const data=JSON.parse(record.data);
// 只读展示:回收付款已经由关联购料记账,不再生成销售、费用或收付款行。
return {id:record.id,kind:'recovery',recovery_id:record.id,recovery_mode:'direct',number:record.number,paper_number:'',
date:record.date,created:record.created,customer:record.customer,salesperson:record.salesperson,member:record.member,
status:'recovery',note:record.note,types:['黄金回收'],mg:data.oldMg,summaryMg:0,pieces:0,
cashPayment:data.cashPayment,purchase_id:record.purchase_id,
costHint:'回收付款已计入每日购料,本行不计销售、利润和销售克重'};
}
function compareDisplay(a,b){
return compareText(a.row.created,b.row.created)||a.sequence-b.sequence||compareText(a.row.kind||'order',b.row.kind||'order')||compareText(a.row.id,b.row.id);
}
function summarize(rows){
const orders=rows.filter(row=>row.kind!=='afterSale'),actualOrders=orders.filter(row=>row.status!=='draft');
const actual=rows.filter(row=>row.status!=='draft');
const keys=AMOUNTS.filter(key=>key!=='assistant2Cost'||rows.some(row=>Object.hasOwn(row.known,key)));
const knownCounts=Object.fromEntries(keys.map(key=>[key,actualOrders.filter(row=>row[key]!==null).length]));
const unknownCounts=Object.fromEntries(keys.map(key=>[key,actualOrders.filter(row=>row[key]===null).length]));
const amounts=Object.fromEntries(keys.map(key=>[key,actual.reduce((total,row)=>total+(row.known[key]||0),0)]));
return {
orderCount:orders.length,completedCount:actualOrders.filter(row=>row.status==='delivered').length,
draftCount:orders.length-actualOrders.length,confirmedCount:actualOrders.filter(row=>row.status==='confirmed').length,
returnedCount:actualOrders.filter(row=>row.status==='returned').length,cancelledCount:actualOrders.filter(row=>row.status==='cancelled').length,
incompleteCount:actual.filter(row=>row.incomplete).length,
missingCosts:add(actual,'missingCosts'),pendingCosts:add(actual,'pendingCosts'),unknownCosts:add(actual,'unknownCosts'),
unknownCostCount:unknownCounts.totalCost,unknownProfitCount:unknownCounts.profit,
legacyUnallocatedCount:actual.filter(row=>row.legacyUnallocated).length,
...amounts,mg:add(rows,'summaryMg'),pieces:add(rows,'pieces'),knownCounts,unknownCounts,
partial:rows.some(row=>row.incomplete||row.legacyUnallocated),afterSaleCount:rows.length-orders.length,recordCount:rows.length
};
}
function receiptSummary(payments,accounts){
const names=[['wechat','微信'],['alipay','支付宝'],['cash','现金'],['credit_card','信用卡']];
const channelOf=account=>names.find(([,name])=>account.endsWith(name))?.[0]||'other';
const accountNames=[...new Set([...accounts.filter(account=>!account.endsWith('信用卡')||payments.some(payment=>payment.account===account)),...payments.map(payment=>payment.account)])];
const summarizePayments=items=>{
const receipt=add(items.filter(payment=>payment.kind==='receipt'),'amount');
const refund=add(items.filter(payment=>payment.kind==='refund'),'amount');
return {receipt,refund,net:receipt-refund};
};
const channels=names.filter(([channel])=>channel!=='credit_card'||payments.some(payment=>channelOf(payment.account)===channel)).map(([channel,name])=>({channel,name,...summarizePayments(payments.filter(payment=>channelOf(payment.account)===channel))}));
if(payments.some(payment=>channelOf(payment.account)==='other'))channels.push({channel:'other',name:'其他',...summarizePayments(payments.filter(payment=>channelOf(payment.account)==='other'))});
// 更正用同种类的负数冲回:按日期保留其影响,不能删除原日收款或把冲回当退款。
return {...summarizePayments(payments),channels,
accounts:accountNames.map(account=>({account,...summarizePayments(payments.filter(payment=>payment.account===account))})),
paymentCount:payments.length,orderCount:new Set(payments.map(payment=>payment.price_lock_id?'price-lock:'+payment.price_lock_id:payment.order_id)).size
};
}
function lockActivity(ledger,from,date,accounts,orders){
const raw=typeof ledger.priceLockReporting==='function'?ledger.priceLockReporting({from,to:date}):{};
const customerCash=raw.customerCash||[],materialOutlays=raw.materialOutlays||[],directOutlays=raw.directOutlays||[];
// 交付后的补款、退款和更正仍是锁价收付,不能回到整单的开单日重复汇总。
const orderPayments=typeof ledger.priceLockReporting==='function'?ledger.rows(`SELECT p.*,o.number,o.paper_number,o.customer,o.date AS order_date,l.id AS price_lock_id
FROM payments p JOIN orders o ON o.id=p.order_id JOIN price_locks l ON l.final_order_id=o.id
WHERE p.date>=? AND p.date<=? ORDER BY p.date,p.created,p.id`,from,date).filter(row=>ledger.canAccess('order',row.order_id)&&(!ledger.memberFilter||ledger.entityMember('order',row.order_id)===ledger.memberFilter)):[];
const deliveryGoodsOutlays=orders.filter(order=>order.price_lock_id&&order.status!=='draft').flatMap(order=>{
// 退货冲回的是已消耗成本,已支付的进货工费等仍保留在原支付日。
const costs=Calc.orderCosts({...order,status:'delivered'});
return costs.rows.filter(item=>item.kind==='goods'&&component(item)!=='material').map((item,index)=>({
...item,id:`price-lock-goods:${order.id}:${index}`,price_lock_id:order.price_lock_id,order_id:order.id,
number:order.number,paper_number:order.paper_number,customer:order.customer,date:order.date,
component:component(item),excluded:false
}));
});
const cash=[...customerCash,...orderPayments],receipts=receiptSummary(cash,accounts);
const payerOutlays=Object.fromEntries(['owner','assistant','assistant2'].map(payer=>{
const material=add(materialOutlays.filter(item=>item.payer===payer),'amount');
const goods=material+add(deliveryGoodsOutlays.filter(item=>item.payer===payer),'amount');
const paidFees=add(directOutlays.filter(item=>item.payer===payer),'amount');
return [payer,{payer,material,goods,paidFees,total:goods+paidFees}];
}));
const financialEvents=[...cash,...materialOutlays,...directOutlays,...deliveryGoodsOutlays];
return {basis:'eventDate',from,date,customerCash,orderPayments,materialOutlays,directOutlays,deliveryGoodsOutlays,
receipts,payerOutlays,summary:{receipt:receipts.receipt,refund:receipts.refund,net:receipts.net,
materialOutlay:add(materialOutlays,'amount'),goodsOutlay:Object.values(payerOutlays).reduce((sum,payer)=>sum+payer.goods,0),
feeOutlay:Object.values(payerOutlays).reduce((sum,payer)=>sum+payer.paidFees,0),
ownerOutlay:payerOutlays.owner.total,assistantOutlay:payerOutlays.assistant.total,assistant2Outlay:payerOutlays.assistant2.total,
totalOutlay:Object.values(payerOutlays).reduce((sum,payer)=>sum+payer.total,0),eventCount:financialEvents.length,
lockCount:new Set(financialEvents.map(item=>item.price_lock_id)).size}};
}
function materialPoolActivity(ledger,from,date){
const raw=typeof ledger.materialPoolReporting==='function'?ledger.materialPoolReporting({from,to:date}):{};
const purchases=raw.purchases||[];
const payerOutlays=Object.fromEntries(['owner','assistant','assistant2'].map(payer=>{
const items=purchases.filter(item=>item.payer===payer),material=items.reduce((total,item)=>total+(item.cashAmount??item.amount),0);
return [payer,{payer,material,goods:material,paidFees:0,total:material,purchaseCount:items.length}];
}));
// 采购款包含尚未耗用的金料;退货只释放耗用克重,不产生采购退款。
return {basis:'purchaseDate',from,date,purchases,payerOutlays,summary:{
purchaseCount:purchases.length,poolCount:new Set(purchases.map(item=>item.pool_id)).size,
mg:add(purchases,'mg'),materialOutlay:purchases.reduce((total,item)=>total+(item.cashAmount??item.amount),0),purchaseValue:add(purchases,'amount'),
ownerOutlay:payerOutlays.owner.total,assistantOutlay:payerOutlays.assistant.total,assistant2Outlay:payerOutlays.assistant2.total,
totalOutlay:Object.values(payerOutlays).reduce((sum,payer)=>sum+payer.total,0),eventCount:purchases.length}};
}
function orderBook(ledger,query,{today,validateDay,accounts}){
const date=validateDay(query.date??today),from=validateDay(query.from??date);
if(from>date)invalid('开始日期不能晚于结束日期');
const status=String(query.status??'all');if(!STATUSES.includes(status))invalid('订单状态无效');
const q=String(query.q??'').trim();if(q.length>100)invalid('搜索内容请填写不超过100字');
const terms=q.toLocaleLowerCase('zh-CN');
// 旧读取顺序仅用于保持收款投影兼容;显示行在合并售后后按真实创建先后排序。
const orderSources=ledger.visibleRows('order',ledger.rows("SELECT o.id,o.rowid AS position,(SELECT MIN(a.id) FROM audit a WHERE a.entity=o.id AND a.action='保存草稿') AS creation_sequence FROM orders o WHERE o.date>=? AND o.date<=? ORDER BY o.date DESC,o.paper_number DESC,o.created DESC,o.id",from,date));
const positions=new Map(orderSources.map(row=>[row.id,row.creation_sequence??row.position]));
const sourceOrders=orderSources.map(row=>ledger.detail(row.id));
const orders=sourceOrders.filter(order=>{
if(status!=='all'&&order.status!==status)return false;
return !terms||[order.number,order.paper_number,order.customer,order.note,order.salesperson,...(order.recovery_id?['置换']:[]),...order.lines.flatMap(line=>[line.name,line.code,line.pocket])]
.some(value=>String(value??'').toLocaleLowerCase('zh-CN').includes(terms));
});
const afterSales=['all','after_sale'].includes(status)?ledger.visibleRows('after_sale',ledger.rows("SELECT s.*,s.rowid AS position,(SELECT MIN(a.id) FROM audit a WHERE a.entity='after-sale:'||s.id AND a.action='登记售后') AS creation_sequence FROM after_sales s WHERE s.date>=? AND s.date<=? ORDER BY s.date DESC,s.created DESC,s.id",from,date))
.filter(record=>!terms||[record.project,record.customer,record.actor,'售后'].some(value=>String(value??'').toLocaleLowerCase('zh-CN').includes(terms))):[];
const recoveries=['all','recovery'].includes(status)?ledger.visibleRows('recovery',ledger.rows("SELECT r.*,r.rowid AS position,(SELECT MIN(a.id) FROM audit a WHERE a.entity='recovery:'||r.id AND a.action='登记直接回收') AS creation_sequence FROM recoveries r WHERE r.mode='direct' AND r.date>=? AND r.date<=? ORDER BY r.created,r.rowid",from,date))
.filter(record=>!terms||[record.number,record.customer,record.salesperson,record.note,'直接回收',...JSON.parse(record.old_lines).map(line=>line.name)].some(value=>String(value??'').toLocaleLowerCase('zh-CN').includes(terms))):[];
// 同毫秒创建的记录按原创建审计编号排序;没有旧审计时以原表插入次序稳定回退。
const displayed=[...orders.map(order=>({row:orderRow(order),sequence:positions.get(order.id)})),
...afterSales.map(record=>({row:afterSaleRow(record),sequence:record.creation_sequence??record.position}))];
displayed.sort(compareDisplay);
const rows=displayed.map(record=>record.row);
// 财务行与汇总继续沿用原口径;直接回收只加入订单页显示,不能改变日报和已复核快照。
const displayRows=[...displayed,...recoveries.map(record=>({row:recoveryRow(record),sequence:record.creation_sequence??record.position}))]
.sort(compareDisplay).map(record=>record.row);
const priceLockActivity=lockActivity(ledger,from,date,accounts,sourceOrders);
const poolActivity=materialPoolActivity(ledger,from,date);
const lockCash=[...priceLockActivity.customerCash,...priceLockActivity.orderPayments];
const matchingFinalLocks=new Set(orders.filter(order=>order.price_lock_id).map(order=>order.price_lock_id));
const matchingLockCash=lockCash.filter(payment=>(status==='all'||matchingFinalLocks.has(payment.price_lock_id))&&
(!terms||matchingFinalLocks.has(payment.price_lock_id)||[payment.number,payment.paper_number,payment.customer,payment.product]
.some(value=>String(value??'').toLocaleLowerCase('zh-CN').includes(terms))));
const payments=[...ledger.visibleRows('order',ledger.rows('SELECT * FROM payments WHERE date>=? AND date<=? ORDER BY date,created,id',from,date),'order_id'),...priceLockActivity.customerCash];
const withoutCancelledRows=rows.filter(row=>row.status!=='cancelled');
const ordinaryPayments=items=>items.filter(order=>!order.price_lock_id).flatMap(order=>order.payments.filter(payment=>!payment.price_lock_event_id));
const withoutCancelledPayments=[...ordinaryPayments(orders.filter(order=>order.status!=='cancelled')),...matchingLockCash];
return {from,date,today,q,status,rows,displayRows,recoveryCount:recoveries.length,summary:summarize(rows),peopleCount:ledger.peopleCountSummary(date,from),priceLockActivity,materialPoolActivity:poolActivity,
summaryWithoutCancelled:summarize(withoutCancelledRows),
receiptsWithoutCancelled:{basis:'orderDate',filterScope:'matchingOrdersWithoutCancelled',from,date,...receiptSummary(withoutCancelledPayments,accounts)},
receiptsByPaymentDate:{basis:'paymentDate',filterScope:'dateRange',from,date,...receiptSummary(payments,accounts)},
receiptsByOrderDate:{basis:'orderDate',filterScope:'matchingOrders',from,date,...receiptSummary([...ordinaryPayments(orders),...matchingLockCash],accounts)}
};
}
module.exports={orderBook};