Files
weiguang-jewelry-ledger/新账系统/ownership-business.js
T

212 lines
18 KiB
JavaScript

'use strict';
// 个人经营只读展示:复用原收入、有效耗用成本与利润,不写入或改变原债务。
const TeamMembers=require('./team-members');
const Calc=require('./public/calculations');
const OrderAfterSaleReporting=require('./order-after-sale-reporting');
const members=TeamMembers.MEMBERS,keys=TeamMembers.KEYS;
const name=member=>members.find(row=>row.member===member)?.label??member;
const sum=(rows,read)=>rows.reduce((total,row)=>total+read(row),0);
function recordMember(ledger,kind,id){return ledger.entityMember(kind,id)??(ledger.teamMode?null:'assistant');}
function legacyCounts(ledger,date,groups){
const counts=Object.fromEntries(Object.keys(groups).map(member=>[member,0]));
for(const [kind,table,extra] of [['order','orders',"AND e.status<>'draft'"],['after_sale','after_sales',''],['price_lock','price_locks',"AND e.status<>'cancelled' AND (e.final_order_id IS NULL OR EXISTS(SELECT 1 FROM orders o WHERE o.id=e.final_order_id AND o.date>?))"]]){
const rows=ledger.visibleRows(kind,ledger.rows(`SELECT e.id FROM ${table} e LEFT JOIN team_fund_sources s ON s.kind=? AND s.source_id=e.id WHERE e.date<=? AND (s.source_id IS NULL OR s.legacy=1) ${extra}`,kind,date,...(kind==='price_lock'?[date]:[])));
for(const row of rows){const member=recordMember(ledger,kind,row.id);if(Object.hasOwn(counts,member))counts[member]++;}
}
return counts;
}
function settlement(member,team,from,date,legacyCount,incomplete){
const available=!!team,pendingCount=team?.pending.filter(row=>row.member===member).length??0;
const counterparts=(team?.pairs??[]).filter(pair=>pair.members.includes(member)).map(pair=>{
const other=pair.members.find(value=>value!==member),sign=pair.members[0]===member?1:-1;
const signed=value=>value?value*sign:0,period=Object.fromEntries(['obligationNet','transferred','receivedForNet','advancedNet'].map(key=>[key,signed(pair.period[key])]));
const closingDue=signed(pair.net),periodNew=period.obligationNet,periodTransferred=period.transferred;
return {member:other,name:name(other),dueOut:Math.max(0,closingDue),dueIn:Math.max(0,-closingDue),
openingDue:closingDue-periodNew+periodTransferred,periodNew,periodTransferred,closingDue,offset:pair.offset,period};
});
const partial=!!(legacyCount||pendingCount||incomplete),notices=[];
if(!available)notices.push('旧双人账请在原订单结算入口核对,不在三人往来中判断已结清。');
else notices.push('截至所选日的累计往来,已抵扣实际转账与代收;逐人核对,不将他人付款成本直接当作应转。');
if(legacyCount)notices.push('存在历史来源,历史单待结请核对原结算;三人余额不代表历史全部结清。');
if(pendingCount||incomplete)notices.push('成本或账务待补,往来仅为当前已记金额。');
return {available,basis:'cumulative-through-date',from,date,
dueOut:available?sum(counterparts,row=>row.dueOut):null,dueIn:available?sum(counterparts,row=>row.dueIn):null,
partial,pendingCount,legacyCount,notice:notices.join(''),counterparts};
}
function difference(group,rows,receipts){
const amount=receipts.net-group.sales,reasons=[];
const add=(code,text)=>reasons.push({code,text});
if(amount){
if(receipts.items.some(item=>item.price_lock_id)||rows.some(row=>row.price_lock_id))add('price_lock_timing','锁价定金、尾款与退款按实际发生日核对,销售与利润按成交单日期核算。');
if(rows.some(row=>row.balance>0&&!['returned','cancelled'].includes(row.status)))add('outstanding_customer_balance','部分订单尚有客户未付金额,销售净额与已经收到的经营款不同。');
if(rows.some(row=>row.kind==='orderAfterSale'))add('order_after_sale','订单售后按实际发生日确认退款和利润调整,原开单日结果保留;扣留客户款已计入最终结果。');
if(rows.some(row=>['returned','cancelled'].includes(row.status)&&!row.orderAfterSale))add('refund_or_cancellation','退货或作废已按原账冲回销售;尚未退清的客户款或不同日期的退款不作为销售利润。');
if(rows.some(row=>row.recovery_mode==='exchange'&&row.nonCashOffset>0))add('exchange_offset','置换旧料抵扣属于非现金成交金额,不能把本次现金净收直接当作完整销售额。');
if(rows.some(row=>['draft','confirmed'].includes(row.status)))add('unfinalized_orders','存在草稿或未完成订单,款项与已确认的订单利润分开核对。');
if(!reasons.length)add('payment_sales_difference','客户净收款与原账销售净额不一致,利润继续按原销售净额与有效成本核算。');
}
if(group.incomplete)add('costs_incomplete','成本、费用或订单账务尚未补齐,仅显示已知成本与已核算利润,不能视为完整利润。');
return {amount,reconciled:amount===0,reasons};
}
function poolMaterialCosts(ledger,rows,group){
const empty=()=>({mg:0,amount:0,knownAmount:0,missingCount:0,byPayer:Object.fromEntries(keys.map(member=>[member,{amount:0,knownAmount:0}]))});
const total={...empty(),hasPriceLocks:false},days=new Map();
// 只用真实加权基准区分料价,不把各订单不同个人/公共比例的混合均价当成日均价。
const rateKey=source=>{
if(!Number.isSafeInteger(source.basisAmount)||!Number.isSafeInteger(source.basisMg)||source.basisMg<=0)return null;
let a=BigInt(source.basisAmount),b=BigInt(source.basisMg);while(b){const next=a%b;a=b;b=next;}
return BigInt(source.basisAmount)/a+':'+BigInt(source.basisMg)/a;
};
// 只展开本次已经过归属权限过滤的有效交付单。采购、未交付的预估和锁价预留不冒充耗用。
for(const row of rows){
if(row.kind==='afterSale'||row.status!=='delivered'||!row.costItems.some(item=>item.materialPoolId&&item.component==='material'))continue;
const order=OrderAfterSaleReporting.originalOrder(ledger,ledger.rawOrder(row.id));
for(const line of order.lines.flatMap(line=>line.priceLockExtraPool?[{...line,priceLockExtraPool:undefined,materialAllocations:line.materialAllocations.filter(a=>a.source==='original'),costParts:{...line.costParts,material:line.priceLockPool?line.priceLockPool.amount:sum(line.materialAllocations.filter(a=>a.source==='original'),a=>a.amount)}},{...line,priceLockPool:line.priceLockExtraPool,priceLockExtraPool:undefined,materialAllocations:line.materialAllocations.filter(a=>a.source==='extra'),costParts:{...line.costParts,material:line.priceLockExtraPool.amount}}]:[line])){
const pool=line.costMaterial?.mode==='pool'?line.materialPool:line.priceLockPool;
const poolId=line.costMaterial?.mode==='pool'?line.costMaterial.poolId:pool?.poolId;
if(!poolId)continue;
if(line.priceLockPool)total.hasPriceLocks=true;
const items=Calc.orderCosts({status:order.status,lines:[line]}).rows.filter(item=>item.kind==='goods'&&item.component==='material'&&item.materialPoolId);
if(!items.length)continue;
// 一件商品可能由多人垫付:金额沿原分摊相加,克重只记一次;不拿显示均价重算分币。
const missing=items.some(item=>item.amount===null),sources=pool?.materialSources?.length?pool.materialSources:[{
kind:'public',member:null,poolId,quantity:pool?.quantity??line.quantity,averageRate:pool?.averageRate??null,
amount:missing?null:sum(items,item=>item.amount),basisAmount:pool?.basisAmount,basisMg:pool?.basisMg
}];
for(const id of new Set(items.map(item=>item.materialPoolId))){
const parts=sources.filter(source=>(source.poolId??poolId)===id),costs=items.filter(item=>item.materialPoolId===id);
if(!days.has(id))days.set(id,{...empty(),poolId:id,date:id,averageRate:null,sources:new Map()});
const day=days.get(id),mg=sum(parts,source=>source.quantity),pending=costs.some(item=>item.amount===null);
for(const value of [day,total]){
value.mg+=mg;
if(pending)value.missingCount++;
for(const item of costs)if(item.amount!==null){value.knownAmount+=item.amount;value.byPayer[item.payer].knownAmount+=item.amount;}
}
for(const source of parts){
const kind=source.kind,member=kind==='personal_recovery'?source.member:null,priceLocked=!!line.priceLockPool;
const averageRate=source.amount===null?null:source.averageRate??pool?.averageRate??null;
const basis=rateKey(source),siblings=[...day.sources.entries()].filter(([,value])=>value.kind===kind&&value.member===member&&value.averageRate===averageRate);
let key=JSON.stringify([kind,member,averageRate,basis]);
// 旧普通单没有完整加权基准;只有同日唯一同价来源时,才与已知来源合并。
if(basis===null&&siblings.length===1)key=siblings[0][0];
else if(basis!==null&&!day.sources.has(key)){
const legacy=siblings.find(([,value])=>value.rateBasis===null);
if(legacy){const value=legacy[1];day.sources.delete(legacy[0]);value.rateBasis=basis;day.sources.set(key,value);}
}
if(!day.sources.has(key))day.sources.set(key,{kind,member,priceLocked,mg:0,averageRate,amount:0,knownAmount:0,missingCount:0,rateBasis:basis});
const target=day.sources.get(key);target.mg+=source.quantity;target.priceLocked=target.priceLocked||priceLocked;
if(source.amount===null)target.missingCount++;else target.knownAmount+=source.amount;
}
}
}
}
const finish=value=>{
value.amount=value.missingCount?null:value.knownAmount;
// 成本待补时真实的FIFO垫付归属也未确定,不能把表单默认付款人当成已核实垫付。
for(const payer of Object.values(value.byPayer))payer.amount=value.missingCount?null:payer.knownAmount;
return value;
};
total.days=[...days.values()].sort((a,b)=>a.date.localeCompare(b.date)).map(day=>{
day.sources=[...day.sources.values()].sort((a,b)=>(a.kind==='personal_recovery'?0:1)-(b.kind==='personal_recovery'?0:1)||(a.member??'').localeCompare(b.member??'')||(a.averageRate??0)-(b.averageRate??0)).map(({rateBasis,...source})=>({...source,amount:source.missingCount?null:source.knownAmount}));
day.averageRate=day.sources.length===1?day.sources[0].averageRate:null;
return finish(day);
});
finish(total);
total.otherCosts={knownAmount:group.knownTotalCost-total.knownAmount,amount:group.draftCount||group.pendingCostCount||group.missingCostCount>total.missingCount?null:group.knownTotalCost-total.knownAmount};
return total;
}
function ownerAdvances(rows,from,date){
const days=new Map();
for(const row of rows){
if(row.status==='draft'||row.date<from||row.date>date)continue;
for(const item of [...row.costItems,...row.pendingCostItems]){
if(item.kind==='goods'&&row.status!=='delivered'&&row.kind!=='orderAfterSale')continue;
const poolMaterial=item.component==='material'&&!!item.materialPoolId,allocationPending=poolMaterial&&item.amount===null;
if((item.payer!=='owner'&&!allocationPending)||item.amount===0)continue;
if(!days.has(row.date))days.set(row.date,{date:row.date,items:[]});
const pending=item.kind==='pending',status=pending?'pending':item.amount===null?'missing':'recorded';
days.get(row.date).items.push({date:row.date,kind:row.kind==='afterSale'?'afterSale':'order',id:row.id,
number:row.number,paperNumber:row.paper_number??'',customer:row.customer,
name:poolMaterial?(allocationPending?'料池料费 · 麦麦份额待补':'料池料费 · 麦麦垫付部分'):item.name,
source:item.source,component:item.component,poolId:item.materialPoolId??null,poolMaterial,allocationPending,
amount:pending?null:item.amount,estimatedAmount:pending?item.amount:null,status,...(item.nonCash?{nonCash:true}:{})});
}
}
return {basis:'orderDate',from,date,days:[...days.values()].sort((a,b)=>a.date.localeCompare(b.date)).map(day=>{
const recorded=day.items.filter(item=>item.status==='recorded'),missing=day.items.filter(item=>item.status==='missing');
const knownAmount=sum(recorded,item=>item.amount),knownPoolAmount=sum(recorded.filter(item=>item.poolMaterial),item=>item.amount),knownOtherAmount=knownAmount-knownPoolAmount;
return {...day,knownAmount,amount:missing.length?null:knownAmount,missingCount:missing.length,pendingCount:day.items.filter(item=>item.status==='pending').length,
poolAmount:missing.some(item=>item.poolMaterial)?null:knownPoolAmount,knownPoolAmount,
otherAmount:missing.some(item=>!item.poolMaterial)?null:knownOtherAmount,knownOtherAmount};
})};
}
function currentAccount(rows,income,advances,from,date){
const days=new Map(),dayOf=day=>{
if(!days.has(day))days.set(day,{date:day,recordCount:0,knownMaterialCost:0,knownOtherCost:0,knownProfit:0,
ownerNetReceipts:0,missingCostCount:0,pendingCostCount:0,unknownProfitCount:0,incomplete:false,
materialMissing:false,otherMissing:false});
return days.get(day);
};
for(const row of rows){
const day=dayOf(row.date);day.recordCount++;day.knownProfit+=row.known.profit;
if(row.profit===null)day.unknownProfitCount++;
day.incomplete ||= row.incomplete||row.profit===null;
}
for(const advance of advances.days){
const day=dayOf(advance.date);day.missingCostCount+=advance.missingCount;day.pendingCostCount+=advance.pendingCount;
day.incomplete ||= !!(advance.missingCount||advance.pendingCount);
for(const item of advance.items){
// 手填料费、锁价料费和料池分摊都沿用原成本金额,不能再叠加整池采购或显示均价。
const material=item.component==='material';
if(item.status==='recorded')day[material?'knownMaterialCost':'knownOtherCost']+=item.amount;
if(item.status==='missing')day[material?'materialMissing':'otherMissing']=true;
}
}
const ownerAccounts=new Set(income.accounts.filter(account=>account.recipient==='owner').map(account=>account.account));
for(const item of income.items){
// 和所属订单收款表一致:普通单按开单日,锁价收退款按实际发生日。
const dateKey=item.price_lock_id||item.order_after_sale?item.date:item.order_date;
if(!dateKey||dateKey<from||dateKey>date)continue;
const day=dayOf(dateKey);
if(ownerAccounts.has(item.account))day.ownerNetReceipts+=item.kind==='receipt'?item.amount:-item.amount;
}
return {basis:'orderDate',from,date,days:[...days.values()].sort((a,b)=>a.date.localeCompare(b.date)).map(({materialMissing,otherMissing,...day})=>{
const knownAmount=day.knownMaterialCost+day.knownOtherCost+day.knownProfit-day.ownerNetReceipts;
return {...day,materialCost:materialMissing?null:day.knownMaterialCost,otherCost:otherMissing?null:day.knownOtherCost,
profit:day.unknownProfitCount?null:day.knownProfit,knownAmount,amount:day.incomplete?null:knownAmount};
})};
}
function project(ledger,{rows,receipts,from,date,team}){
const byMember=new Map(Object.keys(receipts).map(member=>[member,[]]));
for(const row of rows){const member=row.member??recordMember(ledger,row.kind==='afterSale'?'after_sale':'order',row.order_id??row.id);byMember.get(member)?.push(row);}
const legacy=legacyCounts(ledger,date,receipts),result={};
for(const [member,memberRows] of byMember){
const income=receipts[member],draftCount=memberRows.filter(row=>row.status==='draft').length;
const costByPayer=Object.fromEntries(members.map(({member,label})=>[member,{member,name:label,totalCost:0,knownTotalCost:0,missingCount:0,pendingCount:0}]));
for(const row of memberRows){
for(const item of row.costItems){const payer=costByPayer[item.payer];if(!payer)continue;if(item.amount===null)payer.missingCount++;else payer.knownTotalCost+=item.amount;}
for(const item of row.pendingCostItems){const payer=costByPayer[item.payer];if(payer)payer.pendingCount++;}
}
for(const payer of Object.values(costByPayer))payer.totalCost=draftCount||payer.missingCount||payer.pendingCount?null:payer.knownTotalCost;
const unknownProfitCount=memberRows.filter(row=>row.profit===null).length,unknownCost=memberRows.some(row=>row.totalCost===null),other=keys.filter(key=>key!==member).map(key=>costByPayer[key]);
const knownTotalCost=sum(memberRows,row=>row.known.totalCost),knownProfit=sum(memberRows,row=>row.known.profit);
const group={member,name:name(member),basis:'orderDate',from,date,recordCount:memberRows.length,orderCount:memberRows.filter(row=>!['afterSale','orderAfterSale'].includes(row.kind)).length,
afterSaleCount:memberRows.filter(row=>['afterSale','orderAfterSale'].includes(row.kind)).length,draftCount,sales:sum(memberRows,row=>row.known.sale),netReceipts:income.net,
totalCost:unknownCost?null:knownTotalCost,knownTotalCost,selfCost:costByPayer[member].totalCost,knownSelfCost:costByPayer[member].knownTotalCost,
otherCost:other.some(row=>row.totalCost===null)?null:sum(other,row=>row.totalCost),knownOtherCost:sum(other,row=>row.knownTotalCost),
profit:unknownProfitCount?null:knownProfit,knownProfit,incomplete:memberRows.some(row=>row.incomplete)||unknownProfitCount>0,
missingCostCount:sum(memberRows,row=>row.missingCosts),pendingCostCount:sum(memberRows,row=>row.pendingCosts),unknownProfitCount,costByPayer};
group.poolMaterial=poolMaterialCosts(ledger,memberRows,group);
group.ownerAdvances=ownerAdvances(memberRows,from,date);
group.currentAccount=currentAccount(memberRows,income,group.ownerAdvances,from,date);
group.difference=difference(group,memberRows,income);
const useReceipts=group.difference.reconciled&&!group.incomplete&&group.profit!==null&&group.totalCost!==null&&group.sales-group.totalCost===group.profit;
group.equation={basis:useReceipts?'netReceipts':'sales',revenue:useReceipts?income.net:group.sales,totalCost:group.totalCost,profit:group.profit,complete:!group.incomplete&&group.profit!==null&&group.totalCost!==null};
group.settlement=settlement(member,team,from,date,legacy[member],group.incomplete);
group.hasActivity=!!(group.recordCount||income.items.length||group.settlement.legacyCount||group.settlement.pendingCount||group.settlement.counterparts.some(row=>row.openingDue||row.periodNew||row.periodTransferred||row.closingDue));
result[member]=group;
}
return result;
}
module.exports={project,currentAccount};