增加订单退货退款售后、原成本回料及跨日损益核算

This commit is contained in:
summer committed 2026-11-10 02:54:58 +08:00
1 parent b6a0213a0c
commit dab735423e
24 files changed
+1048 -82

No files matched your search

+17 -9
View File
@@ -1,6 +1,7 @@
'use strict';
// 订单簿只读投影:普通订单按开单日,锁价收付按实际发生日,金额始终为整数分。
const Calc=require('./public/calculations');
const OrderAfterSaleReporting=require('./order-after-sale-reporting');
const AMOUNTS=['sale','material','laborAndFees','unallocated','totalCost','profit','ownerCost','assistantCost','assistant2Cost'];
const FINAL_STATUSES=['delivered','returned','cancelled'];
// 旧状态值保留给既有读取调用;新页面按复核事实和业务类型筛选。
@@ -79,6 +80,7 @@ function orderRow(order,pocketLabel){
...(order.cancellationApproved?{cancellationApproved:order.cancellationApproved}:{}),
...(materialPoolIds.length?{materialPoolIds,materialCostPending}:{}),
customer:order.customer,salesperson:order.salesperson,status:order.status,note:order.note,
...(order.orderAfterSale?{orderAfterSale:order.orderAfterSale,current_status:'returned'}:{}),
types:[...new Set(order.lines.map(line=>lineType(line,pocketLabel)))],
mg:add(order.lines.filter(line=>line.unit==='g'),'quantity'),
summaryMg:add(order.lines.filter(line=>line.unit==='g'&&!Calc.isSilver(line.name)),'quantity'),
@@ -119,7 +121,7 @@ function compareDisplay(a,b){
}
function summarize(rows){
const orders=rows.filter(row=>row.kind!=='afterSale'),actualOrders=orders.filter(row=>row.status!=='draft');
const orders=rows.filter(row=>!['afterSale','orderAfterSale'].includes(row.kind)),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]));
@@ -128,7 +130,7 @@ function summarize(rows){
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,
returnedCount:actualOrders.filter(row=>row.status==='returned').length+rows.filter(row=>row.kind==='orderAfterSale').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,
@@ -229,17 +231,21 @@ function orderBook(ledger,query,{today,validateDay,accounts,pockets}){
});
const afterSales=!pocket&&['all','after_sale'].includes(status)?ledger.visibleRows('after_sale',ledger.rows("SELECT s.*,COALESCE(v.revision,1) AS revision,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 LEFT JOIN after_sale_revisions v ON v.after_sale_id=s.id WHERE s.date>=? AND s.date<=? ORDER BY s.date DESC,s.created DESC,s.id",from,date))
.filter(record=>matchesText([record.project,record.customer,record.actor,'售后'])):[];
const orderAfterSales=['all','after_sale','returned'].includes(status)?OrderAfterSaleReporting.records(ledger,from,date).filter(record=>
(!pocket||record.summary.lines.some(line=>pocket==='external'?!line.pocket:line.pocket===pocket))&&
matchesText([record.number,record.paper_number,record.customer,record.note,record.salesperson,'订单售后',...record.summary.lines.map(line=>line.name)])):[];
const recoveries=!pocket&&['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.status='active' AND r.date>=? AND r.date<=? ORDER BY r.created,r.rowid",from,date))
.filter(record=>{const lines=JSON.parse(record.old_lines);return matchesWeight(weight,lines.map(line=>line.foldedMg),JSON.parse(record.data).oldMg)||matchesText([record.number,record.customer,record.salesperson,record.note,'直接回收',...lines.map(line=>line.name)]);}):[];
// 同毫秒创建的记录按原创建审计编号排序;没有旧审计时以原表插入次序稳定回退。
const displayed=[...orders.map(order=>({row:orderRow(order,pocketLabel),sequence:positions.get(order.id)})),
...afterSales.map(record=>({row:afterSaleRow(record),sequence:record.creation_sequence??record.position}))];
const displayed=[...orders.map(order=>({row:orderRow(OrderAfterSaleReporting.originalOrder(ledger,order),pocketLabel),sequence:positions.get(order.id)})),
...afterSales.map(record=>({row:afterSaleRow(record),sequence:record.creation_sequence??record.position})),
...orderAfterSales.map(record=>({row:OrderAfterSaleReporting.financialRow(ledger,record),sequence:0}))];
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);
.sort(compareDisplay).map(record=>record.row.current_status?{...record.row,status:record.row.current_status}:record.row);
const priceLockActivity=lockActivity(ledger,from,date,accounts,sourceOrders.map(order=>OrderAfterSaleReporting.originalOrder(ledger,order)));
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));
@@ -247,13 +253,15 @@ function orderBook(ledger,query,{today,validateDay,accounts,pockets}){
(matchingFinalLocks.has(payment.price_lock_id)||matchesText([payment.number,payment.paper_number,payment.customer,payment.product])));
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];
const ordinaryPayments=items=>items.filter(order=>!order.price_lock_id).flatMap(order=>order.payments.filter(payment=>!payment.price_lock_event_id&&!OrderAfterSaleReporting.isPayment(ledger,payment)));
const matchingAfterSaleIds=new Set(orderAfterSales.map(record=>record.order_id));
const afterSalePayments=OrderAfterSaleReporting.payments(ledger,from,date).filter(payment=>!ledger.one('SELECT id FROM price_locks WHERE final_order_id=?',payment.order_id)&&matchingAfterSaleIds.has(payment.order_id));
const withoutCancelledPayments=[...ordinaryPayments(orders.filter(order=>order.status!=='cancelled')),...matchingLockCash,...afterSalePayments];
return {from,date,today,q,status,pocket,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)}
receiptsByOrderDate:{basis:'orderDate',filterScope:'matchingOrders',from,date,...receiptSummary([...ordinaryPayments(orders),...matchingLockCash,...afterSalePayments],accounts)}
};
}
module.exports={orderBook};