每日对账底部新增按归属人逐日利润表

This commit is contained in:
summer committed 2026-11-03 00:29:34 +08:00
1 parent d8daf90b00
commit f4ac7502d3
8 files changed
+141 -10

No files matched your search

+25 -2
View File
@@ -1494,9 +1494,19 @@ function reportRecipientReceiptsText(r){
}
function reportQueryState(range,error=''){
const body=$('#report-content');if(!body)return;
const profits=$('#report-daily-profits-content');if(profits)profits.innerHTML='';
currentReport=null;reportLoadedUser='';body.setAttribute('aria-busy',String(!error));
body.innerHTML=`<div class="cards report-cards">${['销售净额','累计实收','累计实退','订单净利润'].map(title=>card(title,'—',error?'尚未取得数据':'正在读取')).join('')}</div><section class="panel report-query-message${error?' error':''}"><p>${error?e(error):'正在读取'+e(reportPeriod(range))+'订单与售后的当前结果…'}</p>${error?button('重新读取','report-retry'):''}</section>`;
}
function reportDailyProfitAmount(value,known,profit=false){return value===null?(profit?'待核算(已核算 ¥':'待补齐(已知 ¥')+yuan(known)+')':'¥'+yuan(value);}
function reportDailyProfitsHTML(r){
const table=r.dailyProfits,amounts=row=>`<td class="number">¥${yuan(row.sales)}</td><td class="number">${e(reportDailyProfitAmount(row.totalCost,row.knownTotalCost))}</td><td class="number${(row.profit??row.knownProfit)<0?' danger-text':''}">${e(reportDailyProfitAmount(row.profit,row.knownProfit,true))}</td>`;
return `<section class="panel report-daily-profits" aria-label="每日利润表"><h2>每日利润表</h2><p class="small muted">${e(reportPeriod(table))} · 按日期、订单归属人核对。勾选“汇总当月”可查看当月逐日利润。</p><div class="table-wrap"><table aria-label="每日利润明细"><thead><tr><th scope="col">日期</th><th scope="col">归属人</th><th scope="col" class="number">销售净额</th><th scope="col" class="number">成本</th><th scope="col" class="number">利润</th></tr></thead><tbody>${table.rows.map(row=>`<tr data-date="${e(row.date)}" data-member="${e(row.member)}"><td>${e(row.date)}</td><td>${e(row.name)}<small class="muted">销售 ${row.orderCount} 单${row.afterSaleCount?' · 售后 '+row.afterSaleCount+' 笔':''}${row.draftCount?' · 旧草稿 '+row.draftCount+' 单未计金额':''}</small></td>${amounts(row)}</tr>`).join('')||'<tr><td colspan="5" class="muted">所选范围暂无订单或售后记录。</td></tr>'}</tbody><tfoot><tr><td colspan="2">所选范围合计</td>${amounts(table.summary)}</tr></tfoot></table></div><p class="small muted report-daily-profit-note">普通订单按开单日、锁价成单按交付日、售后按记录日归集。成本含实际耗用料费和费用;退货、作废沿原账冲回。${table.summary.unknownProfitCount?'待核算项目不按0计作完整利润,括号内仅为已核算部分。':''}</p></section>`;
}
function reportDailyProfitsText(r){
const table=r.dailyProfits,rowText=row=>`销售净额 ¥${yuan(row.sales)} / 成本 ${reportDailyProfitAmount(row.totalCost,row.knownTotalCost)} / 利润 ${reportDailyProfitAmount(row.profit,row.knownProfit,true)}`;
return ['每日利润表(按日期与订单归属人;普通订单按开单日、锁价成单按交付日、售后按记录日)',...(table.rows.length?table.rows.map(row=>`${row.date} / ${row.name} / ${rowText(row)}`):['所选范围暂无订单或售后记录。']),`所选范围合计:${rowText(table.summary)}`,''];
}
function validateReport(r,range){
if(r.basis!=='orderDate'||r.date!==range.date||r.from!==range.from)throw new Error('返回口径或日期与当前选择不一致,请重新读取。');
if(!r.summary||!Array.isArray(r.orderRows)||!Array.isArray(r.accounts)||!r.receiptsByOrderDate||!teamDataKeys(r.payerCosts).length||!teamDataKeys(r.payerCosts).every(key=>{
@@ -1506,6 +1516,18 @@ function validateReport(r,range){
if(!recipientKeys.length||!recipients.every((person,index)=>person&&person.recipient===recipientKeys[index]&&typeof person.name==='string'&&person.name&&Array.isArray(person.items)&&['receipt','refund','net'].every(key=>Number.isSafeInteger(person[key]))&&person.items.every(item=>item&&['receipt','refund'].includes(item.kind)&&Number.isSafeInteger(item.amount)&&typeof item.account==='string'&&validOrderDate(item.date))&&person.net===person.receipt-person.refund&&['receipt','refund'].every(kind=>person.items.filter(item=>item.kind===kind).reduce((sum,item)=>sum+item.amount,0)===person[kind]))||!['receipt','refund','net'].every(key=>recipients.reduce((sum,person)=>sum+person[key],0)===r.receiptsByOrderDate[key]))throw new Error('收款人汇总与明细未完整返回或金额不一致,请重新读取。');
validateOwnershipReceipts(r);
validateOwnershipBusiness(r);
validateDailyProfits(r);
}
function validateDailyProfits(r){
const fail=()=>{throw new Error('每日利润表未完整返回或与当前对账金额不一致,请重新读取。');},table=r.dailyProfits,money=Number.isSafeInteger,count=value=>money(value)&&value>=0,nullable=value=>value===null||money(value),members=teamDataKeys(r.ownershipReceipts);
const amounts=['sales','knownTotalCost','knownProfit'],counts=['recordCount','orderCount','afterSaleCount','draftCount','unknownCostCount','unknownProfitCount'];
const valid=row=>row&&amounts.every(key=>money(row[key]))&&counts.every(key=>count(row[key]))&&nullable(row.totalCost)&&nullable(row.profit)&&typeof row.incomplete==='boolean'&&row.recordCount===row.orderCount+row.afterSaleCount&&row.draftCount<=row.orderCount&&row.unknownCostCount<=row.recordCount&&row.unknownProfitCount<=row.recordCount&&row.totalCost===(row.unknownCostCount?null:row.knownTotalCost)&&row.profit===(row.unknownProfitCount?null:row.knownProfit)&&((row.unknownCostCount||row.unknownProfitCount)?row.incomplete:true)&&(row.profit===null||row.totalCost!==null&&row.sales-row.totalCost===row.profit);
if(!table||table.basis!=='orderDate'||table.from!==r.from||table.date!==r.date||!Array.isArray(table.rows)||!valid(table.summary))fail();
let previous='';for(const row of table.rows){
if(!valid(row)||!row.recordCount||!members.includes(row.member)||typeof row.name!=='string'||!row.name||!validOrderDate(row.date)||row.date<r.from||row.date>r.date)fail();
const key=row.date+':'+teamMemberKeys.indexOf(row.member);if(key<=previous)fail();previous=key;
}
if([...amounts,...counts].some(key=>table.rows.reduce((sum,row)=>sum+row[key],0)!==table.summary[key])||table.rows.some(row=>row.incomplete)!==table.summary.incomplete||table.summary.sales!==r.summary.sale||table.summary.knownTotalCost!==r.summary.totalCost||table.summary.knownProfit!==r.summary.profit||table.summary.recordCount!==r.orderRows.length||table.summary.unknownProfitCount!==(r.summary.unknownProfitCount||0)+(r.summary.draftCount||0)||table.summary.unknownCostCount!==(r.summary.unknownCostCount||0)+(r.summary.draftCount||0))fail();
}
function validateOwnershipReceipts(r){
const fail=()=>{throw new Error('所属订单净收入与账户明细未完整返回或金额不一致,请重新读取。');},keys=teamDataKeys(r.ownershipReceipts),selected=teamMode()?(state.user.role==='owner'?reportMember:currentMember()):'',expected=selected?[selected]:teamMode()?teamMemberKeys:teamDataKeys(r.recipientReceipts);
@@ -1577,7 +1599,7 @@ function validateOwnershipBusiness(r){
async function renderReport(){
if(!reportDateInitialized){reportDate=reportDate||state.today;reportDateInitialized=true;}
invalidateReport();const request=reportRequest,user=state.user.id||state.user.name;let range;
$('#main').innerHTML=heading('DAILY CHECK','每日对账','核对本人或所选成员的所属订单收入、实际支出与收款账户。',`<div class="report-controls">${memberFilterHTML('report-member-filter',reportMember)}<label>对账日期<input type="date" id="report-date" value="${e(reportDate)}" max="${e(state.today)}" aria-label="对账日期"></label><label class="check"><input type="checkbox" id="report-month" ${reportMonth?'checked':''}>汇总当月</label></div>`)+`<p class="small muted report-scope">普通订单按开单日期、售后按记录日期筛选。锁价收付按实际发生日期,销售和完整利润在交付日计入;原锁付款不会重复计入交付日支出。</p><div id="report-content" aria-live="polite"></div><div id="daily-funds-content" aria-live="polite"></div>`;
$('#main').innerHTML=heading('DAILY CHECK','每日对账','核对本人或所选成员的所属订单收入、实际支出与收款账户。',`<div class="report-controls">${memberFilterHTML('report-member-filter',reportMember)}<label>对账日期<input type="date" id="report-date" value="${e(reportDate)}" max="${e(state.today)}" aria-label="对账日期"></label><label class="check"><input type="checkbox" id="report-month" ${reportMonth?'checked':''}>汇总当月</label></div>`)+`<p class="small muted report-scope">普通订单按开单日期、售后按记录日期筛选。锁价收付按实际发生日期,销售和完整利润在交付日计入;原锁付款不会重复计入交付日支出。</p><div id="report-content" aria-live="polite"></div><div id="daily-funds-content" aria-live="polite"></div><div id="report-daily-profits-content" aria-live="polite"></div>`;
try{range=reportRange();}catch(err){reportQueryState(null,err.message);return;}
reportQueryState(range);
if(typeof prepareDailyFundsReport==='function')prepareDailyFundsReport({...range,month:reportMonth});
@@ -1606,6 +1628,7 @@ function renderReportContent(r,range){
body.setAttribute('aria-busy','false');
body.innerHTML=`${reportOwnershipReceiptsHTML(r,range)}<div class="order-people-strip report-people-strip">${peopleCountHTML(r.peopleCount)}</div><div class="cards report-cards">${card('所选'+(reportMonth?'月':'日')+'销售净额',e(reportSummaryAmount(s,'sale')),e(countHints))}${card('本期实收','¥'+yuan(receipts.receipt),'普通订单累计收款+本期锁价实收')}${card('本期实退','¥'+yuan(receipts.refund),'普通订单累计退款+本期锁价实退')}${card('本期净利润'+(profitMissing?'(已核算部分)':''),e(reportSummaryAmount(s,'profit')),profitMissing?profitMissing+' 单利润待补齐'+(r.pendingMaterialCount?',其中 '+r.pendingMaterialCount+' 单料费待补':''):'销售净额 − 订单耗用成本 − 实际费用(含售后)',true)}</div><div class="report-primary"><section class="panel report-accounts"><h2>按收款账户核对</h2><p class="small muted">${e(reportPeriod(range))}普通订单当前收付,加上同期锁价实际收付。</p><div class="table-wrap"><table aria-label="按收款账户核对"><thead><tr><th>账户</th><th class="number">实收</th><th class="number">实退</th><th class="number">净额</th></tr></thead><tbody>${reportActiveAccounts(r).map(a=>`<tr><td>${e(a.account)}</td><td class="number">¥${yuan(a.receipt)}</td><td class="number">¥${yuan(a.refund)}</td><td class="number">¥${yuan(a.net)}</td></tr>`).join('')||'<tr><td colspan="4" class="muted">所选范围没有收退款活动账户。</td></tr>'}</tbody><tfoot><tr><td>合计</td><td class="number">¥${yuan(receipts.receipt)}</td><td class="number">¥${yuan(receipts.refund)}</td><td class="number">¥${yuan(receipts.net)}</td></tr></tfoot></table></div><p class="small muted report-cost-note">请按这些订单的收退款记录与微信、支付宝、现金、信用卡核对;系统尚未接入支付平台账单。</p></section>${reportPayerCostsHTML(r)}</div>`;
body.insertAdjacentHTML('beforeend',priceLockActivityHTML(r.priceLockActivity)+materialPoolActivityHTML(r.materialPoolActivity)+reportOrderNetHTML(r,range)+reportGlobalHTML(r)+`<section class="panel"><div class="panel-title"><h2>需要查看 ${r.warnings.length} 项</h2><span class="small muted">截至现在所有订单,不受日期筛选</span></div>${r.warnings.length?`<ul>${r.warnings.map(w=>`<li>${w.id?`<button class="link-button" data-action="open-order" data-id="${e(w.id)}">${e(w.number)}</button> `:''}${e(w.message)}</li>`).join('')}</ul>`:'<p class="ok">系统内未发现待补成本、待退款和待复核项。实际到账仍需核对。</p>'}<div class="form-actions"><div class="small ${close?.stale?'danger-text':'muted'}">${e(closeStatus)}</div><div class="actions">${button('下载对账报告','download-report')}${state.user.role==='owner'&&!reportMonth?button('保存核对快照','close-day','primary'):''}</div></div></section>`+(teamMode()?teamHistoricalReportHTML(r):reportUnsettledHTML(r)+materialPoolGlobalSettlementHTML(r.materialPoolSettlement)));
$('#report-daily-profits-content').innerHTML=reportDailyProfitsHTML(r);
}
function requireCurrentReport(){
const range=reportRange(),r=currentReport;
@@ -1618,7 +1641,7 @@ function reportDownloadText(r){
const s=r.summary,receipts=r.receiptsByOrderDate,people=teamDataKeys(r.payerCosts).map(key=>r.payerCosts[key]),missing=people.reduce((sum,c)=>sum+c.missingCount,0),pending=people.reduce((sum,c)=>sum+c.pendingCount,0);
const costs=people.flatMap(c=>[`${c.name}支出成本:货品成本 ${reportCostAmount(c.goods,c.missingCount)};已付费用 ¥${yuan(c.paidFees)}${c.items.some(item=>item.kind==='afterSale')?'(其中售后 ¥'+yuan(reportAfterSaleAmount(c))+')':''};支出合计 ${reportCostAmount(c.total,c.missingCount+c.pendingCount)}`,reportPayerHints(c),`${c.name}逐项明细(货品成本为 0 的分项省略,已核实为 0 的费用保留):`,...reportCostItems(c).map(item=>`${item.date} / ${reportCostIdentity(item)} / ${item.name} / ${item.source}${item.calculation?' / '+reportCostFormula(item):''} / ${reportCostItemAmount(item)}${item.kind==='pending'?'(未计入实际成本与合计)':''}`),'']);
const orders=r.orderRows.map(row=>`${row.date} / ${row.kind==='afterSale'?'售后 · '+row.project+' / 客户 '+row.customer+' / '+afterSalePayerName(row)+'支付':row.paper_number||row.number} / ${label[row.status]||row.status} / 销售净额 ${reportRowAmount(row,'sale')} / 货品成本 ${reportRowAmount(row,'goods')} / 已付费用 ${reportRowAmount(row,'paidFees')} / 成本合计 ${reportRowAmount(row,'totalCost')} / 净利润 ${reportRowAmount(row,'profit')}${row.costHint?' / '+row.costHint:''}`);
return [`麦麦珠宝新账 · ${reportPeriod(r)} 对账报告`,'口径:普通订单按开单日期、售后按记录日期;锁价收付款按实际发生日期,销售与完整利润按交付日期。原锁料费不会重复计入交付日实际支出。',`销售订单:${s.orderCount} 单;售后 ${s.afterSaleCount||0} 笔;完成 ${s.completedCount} 单;退货 ${s.returnedCount} 单;取消 ${s.cancelledCount} 单;旧草稿 ${s.draftCount} 单(未计金额)`,...peopleCountReportLines(r.peopleCount),`销售净额:${reportSummaryAmount(s,'sale')}`,`累计实收:¥${yuan(receipts.receipt)}`,`累计实退:¥${yuan(receipts.refund)}`,`客户收款净额:¥${yuan(receipts.net)}`,`订单耗用货品成本:${reportCostAmount(r.goods,s.missingCosts)}`,`订单已付费用:¥${yuan(r.expense)}${s.afterSaleCount?'(其中售后 ¥'+yuan(people.reduce((sum,c)=>sum+reportAfterSaleAmount(c),0))+')':''}`,`各人实际货品支出:${reportCostAmount(r.outlayGoods??r.goods,missing)}`,`各人实际费用支出:¥${yuan(r.outlayExpense??r.expense)}`,`各人实际支出合计:${reportCostAmount(r.outlayTotal??r.goods+r.expense,missing+pending)}`,`本期净利润${s.unknownProfitCount?'(已核算部分)':''}:${reportSummaryAmount(s,'profit')}${s.unknownProfitCount?';'+s.unknownProfitCount+' 单利润待补齐':''}`,'',...reportOwnershipReceiptsText(r),...(typeof dailyFundsDownloadText==='function'?dailyFundsDownloadText(r):[]),...reportRecipientReceiptsText(r),'按收款账户核对(普通订单累计收付+同期锁价实际收付)',...reportActiveAccounts(r).map(a=>`${a.account}:实收 ¥${yuan(a.receipt)},实退 ¥${yuan(a.refund)},净额 ¥${yuan(a.net)}`),'',(teamMode()?'各人支出成本(未入账费用不计合计)':'双方支出成本(未入账费用不计合计)'),...costs,...priceLockActivityText(r.priceLockActivity),...(r.materialPoolActivity?.purchases?.length?['本期实际购料(已计入各人实际支出,不再加总)',...r.materialPoolActivity.purchases.map(item=>`${item.date} / ${grams(item.mg)}g / ¥${yuan(item.amount)} / ${materialPayerName(item.payer)} / ${item.note||''}`),'']:[]),'订单与售后净额明细(订单按开单日期、售后按售后日期)',...orders,'',`${r.date} 账面库存(按所选日及此前流水计算,月汇总仍显示所选日)`,...r.inventory.map(i=>`${i.pocket}:${grams(i.mg)}g`),'','截至现在的全局未结事项(不受日期筛选)',`客户待收款:¥${yuan(r.customerBalance)}`,`订单与剩余料款待结净额:${materialReportMoney(r.settlementDue)}`,...r.unsettled.map(o=>`${o.number}:货款待结 ${materialReportMoney(o.costDue)},利润待结 ${materialReportMoney(o.profitDue)},麦麦直收净额 ¥${yuan(o.ownerDirect)},总待结 ${materialReportMoney(o.total)}`),'','当前待处理(所有订单,不受日期筛选)',...r.warnings.map(w=>`${w.number||''} ${w.message}`),'',...(r.materialPoolSettlement?.pools?.length?['剩余料款与助理结算(正数助理交麦麦,负数麦麦转回助理)',...r.materialPoolSettlement.pools.map(item=>`${item.date}:助理剩余料款 ${materialReportMoney(item.assistantInventoryCredit)},实际已交净额 ¥${yuan(item.transferred)},待结 ${materialReportMoney(item.settlementDue)}`),'']:[]),'收款由经办人登记,不代表支付平台自动核验。各人实际付款与订单耗用成本分别核对;退货冲回耗用成本,锁价实际进货付款保留。净利润不含房租、工资、水电。'].join('\n');
return [`麦麦珠宝新账 · ${reportPeriod(r)} 对账报告`,'口径:普通订单按开单日期、售后按记录日期;锁价收付款按实际发生日期,销售与完整利润按交付日期。原锁料费不会重复计入交付日实际支出。',`销售订单:${s.orderCount} 单;售后 ${s.afterSaleCount||0} 笔;完成 ${s.completedCount} 单;退货 ${s.returnedCount} 单;取消 ${s.cancelledCount} 单;旧草稿 ${s.draftCount} 单(未计金额)`,...peopleCountReportLines(r.peopleCount),`销售净额:${reportSummaryAmount(s,'sale')}`,`累计实收:¥${yuan(receipts.receipt)}`,`累计实退:¥${yuan(receipts.refund)}`,`客户收款净额:¥${yuan(receipts.net)}`,`订单耗用货品成本:${reportCostAmount(r.goods,s.missingCosts)}`,`订单已付费用:¥${yuan(r.expense)}${s.afterSaleCount?'(其中售后 ¥'+yuan(people.reduce((sum,c)=>sum+reportAfterSaleAmount(c),0))+')':''}`,`各人实际货品支出:${reportCostAmount(r.outlayGoods??r.goods,missing)}`,`各人实际费用支出:¥${yuan(r.outlayExpense??r.expense)}`,`各人实际支出合计:${reportCostAmount(r.outlayTotal??r.goods+r.expense,missing+pending)}`,`本期净利润${s.unknownProfitCount?'(已核算部分)':''}:${reportSummaryAmount(s,'profit')}${s.unknownProfitCount?';'+s.unknownProfitCount+' 单利润待补齐':''}`,'',...reportDailyProfitsText(r),...reportOwnershipReceiptsText(r),...(typeof dailyFundsDownloadText==='function'?dailyFundsDownloadText(r):[]),...reportRecipientReceiptsText(r),'按收款账户核对(普通订单累计收付+同期锁价实际收付)',...reportActiveAccounts(r).map(a=>`${a.account}:实收 ¥${yuan(a.receipt)},实退 ¥${yuan(a.refund)},净额 ¥${yuan(a.net)}`),'',(teamMode()?'各人支出成本(未入账费用不计合计)':'双方支出成本(未入账费用不计合计)'),...costs,...priceLockActivityText(r.priceLockActivity),...(r.materialPoolActivity?.purchases?.length?['本期实际购料(已计入各人实际支出,不再加总)',...r.materialPoolActivity.purchases.map(item=>`${item.date} / ${grams(item.mg)}g / ¥${yuan(item.amount)} / ${materialPayerName(item.payer)} / ${item.note||''}`),'']:[]),'订单与售后净额明细(订单按开单日期、售后按售后日期)',...orders,'',`${r.date} 账面库存(按所选日及此前流水计算,月汇总仍显示所选日)`,...r.inventory.map(i=>`${i.pocket}:${grams(i.mg)}g`),'','截至现在的全局未结事项(不受日期筛选)',`客户待收款:¥${yuan(r.customerBalance)}`,`订单与剩余料款待结净额:${materialReportMoney(r.settlementDue)}`,...r.unsettled.map(o=>`${o.number}:货款待结 ${materialReportMoney(o.costDue)},利润待结 ${materialReportMoney(o.profitDue)},麦麦直收净额 ¥${yuan(o.ownerDirect)},总待结 ${materialReportMoney(o.total)}`),'','当前待处理(所有订单,不受日期筛选)',...r.warnings.map(w=>`${w.number||''} ${w.message}`),'',...(r.materialPoolSettlement?.pools?.length?['剩余料款与助理结算(正数助理交麦麦,负数麦麦转回助理)',...r.materialPoolSettlement.pools.map(item=>`${item.date}:助理剩余料款 ${materialReportMoney(item.assistantInventoryCredit)},实际已交净额 ¥${yuan(item.transferred)},待结 ${materialReportMoney(item.settlementDue)}`),'']:[]),'收款由经办人登记,不代表支付平台自动核验。各人实际付款与订单耗用成本分别核对;退货冲回耗用成本,锁价实际进货付款保留。净利润不含房租、工资、水电。'].join('\n');
}
function printSettingsDirty(form=$('#print-settings')){
if(!form)return false;