'use strict'; // 利润沿用订单消耗成本;锁价实际收付另按发生日核对,避免定金和料费跨日重复。 const {createHash}=require('node:crypto'); const Calc=require('./public/calculations'); const DailyFunds=require('./daily-funds'); const TeamMembers=require('./team-members'); const OwnershipBusiness=require('./ownership-business'); const COST_COMPONENTS=Object.fromEntries(Object.entries(Calc.costLabels).map(([key,name])=>[name,key])); function payerSummary(payer,name){return {payer,name,goods:0,paidFees:0,total:0,missingCount:0,pendingCount:0,items:[]};} function paidSource(item,order){ // 只有原费用项目能唯一对应商品时才显示商品来源,额外费用和更正不猜归属。 const candidates=(order.fee_items||[]).filter(fee=>fee.status==='recorded'&&fee.note===item.name&&fee.amount===item.amount&&fee.payer===item.payer); const fee=candidates.length===1&&order.fees_date===item.source?candidates[0]:null; const index=fee?order.lines.findIndex(line=>(line.charges||[]).some(charge=>'charge:'+charge.id===fee.key)):-1; const source=index<0?'整单费用':`商品 ${index+1} · ${order.lines[index].name}`; return `${source} · 实付 ${item.source}`; } function costSummaries(ledger,rows,{excludePoolMaterial=false}={}){ const payers={assistant:payerSummary('assistant','助理1'),owner:payerSummary('owner','麦麦'),assistant2:payerSummary('assistant2','助理2')}; for(const row of rows){ const pooled=excludePoolMaterial&&row.materialPoolIds?.length&&row.status!=='draft'&&!row.cancellationApproved; const order=pooled||row.costItems.some(item=>item.kind==='paid')?ledger.rawOrder(row.id):null; let items=row.costItems; if(pooled){ const sources=new Set(order.lines.flatMap((line,index)=>line.costMaterial?.mode==='pool'?[`商品 ${index+1} · ${line.name}`]:[])); // 退货冲回的是耗用成本。已经输入并支付的进货工费、配件等没有退款流水, // 仍留在原开单日的实际支出;同单的手填成本商品继续按原规则处理。 const paidGoods=Calc.orderCosts({...order,status:'delivered'}).rows.filter(item=>item.kind==='goods'&&sources.has(item.source)) .map(item=>({...item,component:item.component||COST_COMPONENTS[item.name]||'unallocated',excluded:false})); items=[...items.filter(item=>!(item.kind==='goods'&&sources.has(item.source))),...paidGoods]; } for(const item of [...items,...row.pendingCostItems]){ if(excludePoolMaterial&&item.materialPoolId&&item.component==='material')continue; const payer=payers[item.payer]; const status=item.kind==='pending'?'pending':item.amount==null?'missing':'recorded'; const identity=row.kind==='afterSale'?{after_sale_id:row.after_sale_id,project:row.project}:{order_id:row.id}; payer.items.push({...item,...identity,number:row.number,paper_number:row.paper_number, date:row.date,customer:row.customer,status,calculation:item.calculation??null, source:item.kind==='paid'?paidSource(item,order):item.source, ...(item.kind==='paid'?{paidDate:item.source}:{})}); if(item.kind==='pending')payer.pendingCount++; else if(item.amount==null)payer.missingCount++; else if(item.kind==='goods')payer.goods+=item.amount; else if(['paid','afterSale'].includes(item.kind))payer.paidFees+=item.amount; } } for(const payer of Object.values(payers))payer.total=payer.goods+payer.paidFees; return payers; } function actualCostSummaries(ledger,book){ const payers=costSummaries(ledger,book.rows.filter(row=>!row.price_lock_id),{excludePoolMaterial:true}); const activity=book.priceLockActivity; const append=item=>{ const payer=payers[item.payer],status=item.amount==null?'missing':'recorded'; payer.items.push({...item,status,calculation:item.calculation??null,actualOutlay:true}); if(item.amount==null)payer.missingCount++; else if(item.kind==='goods')payer.goods+=item.amount; else payer.paidFees+=item.amount; }; for(const item of activity.deliveryGoodsOutlays)append(item); for(const item of activity.materialOutlays)append({...item,kind:'goods',component:'material', name:item.source==='extra'?'补购料费':'锁价料费',materialSource:item.source, source:`锁价采购 · 实付 ${item.date}`,paidDate:item.date, calculation:{rate:item.rate,quantity:item.quantity}}); for(const item of activity.directOutlays)append({...item,kind:'paid',component:'fee', name:item.note,source:`锁价费用 · 实付 ${item.date}`,paidDate:item.date}); for(const item of book.materialPoolActivity.purchases)append({...item,purchaseAmount:item.amount,amount:item.cashAmount??item.amount,kind:'goods',component:'material', materialPoolId:item.pool_id,name:'日料池采购',source:`日料池 ${item.pool_id} · 实付 ${item.date}`,paidDate:item.date, quantity:item.mg,calculation:null}); for(const payer of Object.values(payers))payer.total=payer.goods+payer.paidFees; return payers; } function recipientSummaries(ledger,book,payments){ const recipients={assistant:{recipient:'assistant',name:'助理',receipt:0,refund:0,net:0,items:[]}, owner:{recipient:'owner',name:'麦麦',receipt:0,refund:0,net:0,items:[]},assistant2:{recipient:'assistant2',name:'助理2',receipt:0,refund:0,net:0,items:[]}}; const accountRecipients=Object.fromEntries(['微信','支付宝','现金','信用卡'].flatMap(channel=>[ ['助理'+channel,'assistant'],['麦麦'+channel,'owner'],['助理2'+channel,'assistant2']])); const orders=new Map(book.rows.filter(row=>row.kind!=='afterSale').map(row=>[row.id,row])),locks=new Map(); for(const payment of payments){ const recipient=recipients[accountRecipients[payment.account]]; if(!recipient||!['receipt','refund'].includes(payment.kind))continue; // 只补查每张锁价单的唯一身份。不要展开订单继承的全部付款,否则定金会再次计入。 if(payment.price_lock_id&&!locks.has(payment.price_lock_id))locks.set(payment.price_lock_id,ledger.one(` SELECT l.final_order_id AS order_id,l.number,l.customer,l.note,o.date AS order_date,o.paper_number FROM price_locks l LEFT JOIN orders o ON o.id=l.final_order_id WHERE l.id=?`,payment.price_lock_id)); const lock=locks.get(payment.price_lock_id),order=orders.get(payment.order_id); recipient.items.push({id:payment.id,date:payment.date,kind:payment.kind,amount:payment.amount,account:payment.account, order_id:payment.order_id??lock?.order_id??null,price_lock_id:payment.price_lock_id??order?.price_lock_id??null, order_date:payment.order_date??order?.date??lock?.order_date??null, number:payment.number??order?.number??lock?.number??'',paper_number:payment.paper_number??order?.paper_number??lock?.paper_number??null, customer:payment.customer??order?.customer??lock?.customer??'',reference:payment.reference??'', note:payment.note??order?.note??lock?.note??'',created:payment.created}); // 更正冲回沿用原种类的负数,不改成退款,也不丢弃已作废单据的原始流水。 recipient[payment.kind]+=payment.amount; } for(const recipient of Object.values(recipients))recipient.net=recipient.receipt-recipient.refund; if(!ledger.teamMode&&!payments.some(payment=>payment.account.startsWith('助理2')))delete recipients.assistant2; return recipients; } function ownershipSummaries(ledger,recipients,actor){ // 只重排同一快照已经展示的收退款明细,代收是所属订单收入的一部分,不能再加一次。 // 旧双人模式的原报表仍全量可见,展示分组沿用该快照;三人模式才按固定成员隔离。 const selected=ledger.teamMode?ledger.queryMember({},actor??ledger.actor):null; const members=TeamMembers.MEMBERS.filter(row=>selected?row.member===selected:ledger.teamMode||row.member!=='assistant2'||Object.hasOwn(recipients,'assistant2')); const groups=Object.fromEntries(members.map(({member,label})=>[member,{member,name:label,receipt:0,refund:0,net:0,accounts:[],items:[]}])); const memberships=new Map(),accounts=new Map(members.map(({member})=>[member,new Map()])); const memberOf=(kind,id)=>{const key=kind+':'+id;if(!memberships.has(key))memberships.set(key,ledger.entityMember(kind,id));return memberships.get(key);}; const channels=[['wechat','微信'],['alipay','支付宝'],['cash','现金'],['credit_card','信用卡']]; for(const recipient of Object.values(recipients))for(const item of recipient.items){ const member=(item.price_lock_id?memberOf('price_lock',item.price_lock_id):null)??(item.order_id?memberOf('order',item.order_id):null)??(ledger.teamMode?null:'assistant'); const group=groups[member];if(!group)continue; group.items.push({...item});group[item.kind]+=item.amount; const byAccount=accounts.get(member); if(!byAccount.has(item.account))byAccount.set(item.account,{account:item.account,recipient:recipient.recipient,channel:channels.find(([,name])=>item.account.endsWith(name))?.[0]??'other',receipt:0,refund:0,net:0,entryCount:0}); const account=byAccount.get(item.account);account[item.kind]+=item.amount;account.entryCount++; } for(const group of Object.values(groups)){ group.net=group.receipt-group.refund; // 零净额的实退或冲回仍保留明细;没有任何收退款记录的账户不生成展示行。 group.accounts=[...accounts.get(group.member).values()].map(account=>({...account,net:account.receipt-account.refund})); } return groups; } function reportRevision(book,dailyFundsState=null,ownership=[]){ // 复核、打印、库存和其他日期的账务不会改变本日的财务核对状态。 // 新增展示用计数不改变旧快照版本;售后本身已包含在财务行和金额中。 const {afterSaleCount,recordCount,...summary}=book.summary; // 列表顺序与银饰重量属于显示规则。财务版本继续使用原排序和全商品克重, // 避免仅改变显示方式就使已经保存的财务核对快照过期。 summary.mg=book.rows.reduce((total,row)=>total+row.mg,0); const compare=(a,b)=>ab?1:0; const legacyRows=[...book.rows].sort((a,b)=>{ const date=compare(b.date,a.date);if(date)return date; const aAfter=a.kind==='afterSale',bAfter=b.kind==='afterSale';if(aAfter!==bAfter)return aAfter?-1:1; return (!aAfter?compare(b.paper_number,a.paper_number):0)||compare(b.created,a.created)||compare(a.id,b.id); }); const rows=legacyRows.map(row=>({id:row.id,date:row.date,status:row.status, sale:row.sale,material:row.material,laborAndFees:row.laborAndFees,unallocated:row.unallocated, totalCost:row.totalCost,profit:row.profit,ownerCost:row.ownerCost,assistantCost:row.assistantCost, known:row.known,costItems:row.costItems,pendingCostItems:row.pendingCostItems,balance:row.balance})); const financial={basis:'orderDate',date:book.date,from:book.from,summary,rows,receipts:book.receiptsByOrderDate}; // 仅真正改过的售后加入版本,客户名等展示更正也须重核;旧记录升级不改原指纹。 const afterSaleRevisions=legacyRows.filter(row=>row.kind==='afterSale'&&row.revision>1).map(row=>({id:row.id,revision:row.revision})); if(afterSaleRevisions.length)financial.afterSaleRevisions=afterSaleRevisions; // 未转移过的旧日保留原指纹。实际归属调整使订单日及关联锁价收付日重新核对。 if(ownership.length)financial.orderOwnership=ownership; if(dailyFundsState)financial.dailyFunds=dailyFundsState; if(book.priceLockActivity.summary.eventCount){ // 只把原日不可变的收付款项目纳入版本。之后交付关联出的状态、单号和待交信息, // 不能让已经核对的原锁价日重新过期。没有锁价活动的旧日保持原哈希完全兼容。 // 旧锁价卡费没有费率元数据;展示改成泛称时,财务指纹沿用旧版派生名称, // 避免仅因文字变化使已经核对且金额未变的旧日快照过期。不改展示或原记录。 const immutable=item=>Object.fromEntries(['id','price_lock_id','order_id','date','kind','amount','account','payer', 'component','quantity','rate','note','actor','created'].filter(key=>item[key]!==undefined).map(key=>[key, key==='note'&&String(item.id).startsWith('card-fee:')&&item.note==='已记录信用卡手续费'?'信用卡手续费(4‰)':item[key]])); financial.priceLockCashflow={customerCash:book.priceLockActivity.customerCash.map(immutable), orderPayments:book.priceLockActivity.orderPayments.map(immutable),materialOutlays:book.priceLockActivity.materialOutlays.map(immutable), directOutlays:book.priceLockActivity.directOutlays.map(immutable),deliveryGoodsOutlays:book.priceLockActivity.deliveryGoodsOutlays.map(immutable)}; } if(book.materialPoolActivity.summary.eventCount){ // 只记录真实采购支出,不把后来耗用、剩余克重或退货带回采购日再算一次。 const immutable=item=>Object.fromEntries(['id','pool_id','date','mg','amount','payer','note','actor','created','recovery_id','cashAmount','offsetAmount','allocations'] .filter(key=>item[key]!==undefined).map(key=>[key,item[key]])); financial.materialPoolPurchases=book.materialPoolActivity.purchases.map(immutable); } return createHash('sha256').update(JSON.stringify(financial)).digest('hex'); } function closeState(ledger,date,revision,previous){ if(!previous)return null; const stored=ledger.one('SELECT report FROM closes WHERE date=?',date); let saved=null;try{saved=JSON.parse(stored.report);}catch{} const basis=saved?.basis||'entryDate',sameBasis=basis==='orderDate'&&saved?.from===date&&saved?.date===date; const stale=!sameBasis||saved.reportRevision!==revision; return {...previous,basis,reportRevision:saved?.reportRevision||null,stale, staleReason:stale?(sameBasis?'开单日订单或账务有变动,请重新核对':'核对口径已更新,请重新核对'):null}; } function orderDatePayments(ledger,book){ const payments=ledger.visibleRows('order',ledger.rows('SELECT e.*,o.number,o.paper_number,o.date AS order_date FROM payments e JOIN orders o ON o.id=e.order_id WHERE o.date>=? AND o.date<=? ORDER BY o.date,e.date,e.created,e.id',book.from,book.date),'order_id'); const linkedOrders=new Set(book.rows.filter(row=>row.price_lock_id).map(row=>row.id)); return [...payments.filter(payment=>!linkedOrders.has(payment.order_id)),...book.priceLockActivity.customerCash,...book.priceLockActivity.orderPayments]; } function dailyFundsReceipts(ledger,date){ const book=ledger.orderBook({date,from:date,status:'all'}),payments=orderDatePayments(ledger,book),owner=recipientSummaries(ledger,book,payments).owner; return {ownerReceipts:{receipt:owner.receipt,refund:owner.refund,net:owner.net},hasActivity:payments.length>0}; } function reportByOrderDate(ledger,date,from=date,actor=null,env){ const book=ledger.orderBook({date,from,status:'all'}); const previous=ledger.report(book.date,book.from),orderPayerCosts=costSummaries(ledger,book.rows),payerCosts=actualCostSummaries(ledger,book); const revision=reportRevision(book,DailyFunds.financialState(ledger,book.from,book.date),ledger.orderOwnershipReportState(book.from,book.date)); const entries=table=>ledger.visibleRows('order',ledger.rows(`SELECT e.*,o.number,o.paper_number,o.date AS order_date FROM ${table} e JOIN orders o ON o.id=e.order_id WHERE o.date>=? AND o.date<=? ORDER BY o.date,e.date,e.created,e.id`,book.from,book.date),'order_id'); const pendingMaterialOrders=new Set(book.rows.filter(row=>row.materialCostPending).map(row=>row.id)); const outlayGoods=Object.values(payerCosts).reduce((total,payer)=>total+payer.goods,0),outlayExpense=Object.values(payerCosts).reduce((total,payer)=>total+payer.paidFees,0); const payments=orderDatePayments(ledger,book); const recipientReceipts=recipientSummaries(ledger,book,payments); const ownershipReceipts=ownershipSummaries(ledger,recipientReceipts,actor); const dailyFunds=DailyFunds.report(ledger,{date:book.date,from:book.from},actor,env,day=>{ if(book.from===book.date&&day===book.date){const owner=recipientReceipts.owner;return {ownerReceipts:{receipt:owner.receipt,refund:owner.refund,net:owner.net},hasActivity:payments.length>0};} return dailyFundsReceipts(ledger,day); },{allowLong:true}); const ownershipBusiness=OwnershipBusiness.project(ledger,{rows:book.rows,receipts:ownershipReceipts,from:book.from,date:book.date,team:dailyFunds.team??null}); return {...previous,basis:'orderDate',summary:book.summary,orderRows:book.rows,payerCosts,orderPayerCosts,peopleCount:book.peopleCount, priceLockActivity:book.priceLockActivity,materialPoolActivity:book.materialPoolActivity,outlayGoods,outlayExpense,outlayTotal:outlayGoods+outlayExpense, receiptsByOrderDate:book.receiptsByOrderDate,accounts:book.receiptsByOrderDate.accounts, sales:book.summary.sale,goods:Object.values(orderPayerCosts).reduce((total,payer)=>total+payer.goods,0), knownGoods:Object.values(orderPayerCosts).reduce((total,payer)=>total+payer.goods,0),knownProfit:book.summary.profit, materialCostPending:pendingMaterialOrders.size>0,pendingMaterialCount:pendingMaterialOrders.size, expense:Object.values(orderPayerCosts).reduce((total,payer)=>total+payer.paidFees,0),totalCost:book.summary.totalCost, profit:book.summary.profit,delivered:book.summary.completedCount,returns:book.summary.returnedCount, payments,recipientReceipts,ownershipReceipts,ownershipBusiness, settlements:entries('settlements'),journal:entries('journal').map(row=>pendingMaterialOrders.has(row.order_id)?{...row,goods:null,profit:null,materialCostPending:true}:row), dailyFunds,reportRevision:revision,close:book.from===book.date?closeState(ledger,book.date,revision,previous.close):null}; } module.exports={reportByOrderDate,dailyFundsReceipts};