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

156 lines
12 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'];
const FINAL_STATUSES=['delivered','returned','cancelled'];
const STATUSES=['all','draft','confirmed',...FINAL_STATUSES,'after_sale'];
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.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 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')
};
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')
};
// 利润沿用账本已记账净额;旧单尚未交付或成本不完整时,不把预估当作利润。
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;
const values=Object.fromEntries(AMOUNTS.map(key=>[key,unknown[key]?null:known[key]]));
const hints=[];
if(draft)hints.push('旧草稿,未计入实际销售、成本和利润');
else{
if(missingCosts)hints.push(`${missingCosts}项成本缺失,金额仅含已知部分`);
if(pendingCosts)hints.push(`${pendingCosts}项旧单费用未入账,预估未计入实际成本`);
if(order.status==='confirmed')hints.push('旧单账务未补齐,利润尚未记账');
if(legacyUnallocated)hints.push('原单货品成本未分项,计入未分项成本');
if(profitMismatch)hints.push('成本与利润流水不一致,待复核');
if(excluded)hints.push('原售价与货品成本已冲回,实际费用保留');
}
return {
id:order.id,number:order.number,paper_number:order.paper_number,date:order.date,created:order.created,
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};
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 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 knownCounts=Object.fromEntries(AMOUNTS.map(key=>[key,actualOrders.filter(row=>row[key]!==null).length]));
const unknownCounts=Object.fromEntries(AMOUNTS.map(key=>[key,actualOrders.filter(row=>row[key]===null).length]));
const amounts=Object.fromEntries(AMOUNTS.map(key=>[key,actual.reduce((total,row)=>total+row.known[key],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','现金']];
const channelOf=account=>names.find(([,name])=>account.endsWith(name))?.[0]||'other';
const accountNames=[...new Set([...accounts,...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.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.order_id)).size
};
}
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.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 orders=orderSources
.map(row=>ledger.detail(row.id)).filter(order=>{
if(status!=='all'&&order.status!==status)return false;
return !terms||[order.number,order.paper_number,order.customer,order.note,order.salesperson,...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.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 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((a,b)=>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));
const rows=displayed.map(record=>record.row);
const payments=ledger.rows('SELECT * FROM payments WHERE date>=? AND date<=? ORDER BY date,created,id',from,date);
const withoutCancelledRows=rows.filter(row=>row.status!=='cancelled');
const withoutCancelledPayments=orders.filter(order=>order.status!=='cancelled').flatMap(order=>order.payments);
return {from,date,today,q,status,rows,summary:summarize(rows),peopleCount:ledger.peopleCountSummary(date,from),
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(orders.flatMap(order=>order.payments),accounts)}
};
}
module.exports={orderBook};