Files
weiguang-jewelry-ledger/新账系统/public/daily-funds-ui.js
T

265 lines
38 KiB
JavaScript
Raw Normal View History

'use strict';
// 转账核对与报销独立记录,不写订单成本、利润、库存或实际转账流水。
let dailyFundsRequest=0,dailyFundsEntry=null,dailyFundsLoading=false;
let dailyFundsSaving=false;
let dailyReimbursementsRequest=0,dailyReimbursementsList=null,dailyReimbursementsOffset=0;
const dailyOutlayDrafts=new Map(),reimbursementDrafts=new Map(),reimbursementEditors=new Map(),reimbursementReviews=new Map();
const dailyFundsPendingOrigins=new Map();
const reimbursementStatusNames={pending:'待麦麦复核',approved:'已批准',rejected:'已驳回'};
function dailyFundsUser(){return state?.user?.id||state?.user?.name||'';}
function dailyFundsOwner(){return state?.user?.role==='owner';}
function dailyFundsViewKey(range){return dailyFundsUser()+'|'+range.from+'|'+range.date+'|'+!!range.month;}
function dailyFundsRange(){return {...reportRange(),month:reportMonth};}
function dailyFundsMatches(entry=dailyFundsEntry){
if(!entry||tab!=='report'||entry.user!==dailyFundsUser()||!$('#daily-funds-content'))return false;
if(session?.user?.id&&session.user.id!==state?.user?.id)return false;
try{return entry.key===dailyFundsViewKey(dailyFundsRange());}catch{return false;}
}
function dailyFundsMoney(value){return value==null?'待确认':'¥'+yuan(value);}
function validateReimbursement(row){
if(!row||typeof row.id!=='string'||!row.id||!validOrderDate(row.date)||!Object.hasOwn(reimbursementStatusNames,row.status)||!Number.isSafeInteger(row.revision)||row.revision<1||
typeof row.canEdit!=='boolean'||typeof row.canApprove!=='boolean'||!Array.isArray(row.items)||!row.items.length||row.items.length>60||
!row.items.every(item=>typeof item.name==='string'&&item.name&&Number.isSafeInteger(item.amount)&&item.amount>0)||
!Number.isSafeInteger(row.total)||row.items.reduce((sum,item)=>sum+item.amount,0)!==row.total)throw new Error('报销单未完整返回,请重新读取。');
return row;
}
function validateDailyFunds(data,range){
const money=value=>Number.isSafeInteger(value),nullable=value=>value===null||money(value);
if(!data||data.date!==range.date||data.from!==range.from||typeof data.readOnly!=='boolean'||typeof data.ready!=='boolean'||
!['receipt','refund','net'].every(key=>money(data.ownerReceipts?.[key]))||data.ownerReceipts.net!==data.ownerReceipts.receipt-data.ownerReceipts.refund||
!money(data.approvedReimbursements)||!nullable(data.actualOutlay)||!nullable(data.transferAmount)||data.transfersNotDeducted!==true||
!Array.isArray(data.reimbursements)||!Array.isArray(data.days)||!Array.isArray(data.missingDates)||!Array.isArray(data.staleDates)||
!Number.isSafeInteger(data.pendingCount)||data.pendingCount<0||typeof data.sources?.revision!=='string'||!money(data.sources.total)||!Array.isArray(data.sources.items)||
!data.sources.items.every(item=>item&&typeof item.id==='string'&&validOrderDate(item.date)&&money(item.amount)&&item.payer==='owner'&&typeof item.name==='string')||
data.sources.items.reduce((sum,item)=>sum+item.amount,0)!==data.sources.total)throw new Error('转账核对资料未完整返回,请重新读取。');
data.reimbursements.forEach(validateReimbursement);
if(data.confirmation&&(!money(data.confirmation.amount)||data.confirmation.amount<0||!Number.isSafeInteger(data.confirmation.revision)||typeof data.confirmation.sourceRevision!=='string'||typeof data.confirmation.stale!=='boolean'))throw new Error('实际支出确认资料未完整返回,请重新读取。');
if(data.ready&&(data.actualOutlay==null||data.transferAmount!==data.ownerReceipts.net-data.actualOutlay+data.approvedReimbursements)||!data.ready&&data.transferAmount!==null)throw new Error('转账合计与分项不一致,请重新读取。');
if(!range.month&&range.from===range.date&&data.ready&&(!data.confirmation||data.confirmation.stale))throw new Error('当天支出尚未有效确认,请重新读取。');
return data;
}
function preserveDailyFundsDrafts(){
const outlay=$('#daily-outlay-form');
if(outlay){const draft=dailyOutlayDrafts.get(outlay.dataset.viewKey);if(draft){draft.amount=outlay.querySelector('[name="amount"]').value;draft.note=outlay.querySelector('[name="note"]').value;draft.verified=outlay.querySelector('[name="verified"]').checked;}}
const form=$('#reimbursement-form');
if(form){const draft=reimbursementDrafts.get(form.dataset.draftKey);if(draft){draft.date=form.querySelector('[name="date"]').value;draft.note=form.querySelector('[name="note"]').value;draft.items=[...form.querySelectorAll('.reimbursement-item-row')].map(row=>({name:row.querySelector('[name="itemName"]').value,amount:row.querySelector('[name="itemAmount"]').value}));}}
const review=$('#reimbursement-review-form');
if(review){const draft=reimbursementReviews.get(review.dataset.viewKey);if(draft){draft.note=review.querySelector('[name="note"]').value;draft.verified=!!review.querySelector('[name="verified"]')?.checked;}}
}
function invalidateDailyFunds(){preserveDailyFundsDrafts();++dailyFundsRequest;dailyFundsEntry=null;dailyFundsLoading=false;}
function dailyFundsStatusHTML(message,error=false){return `<div class="${error?'error':'small muted'} daily-funds-status" role="status">${e(message)}${error?' '+button('重新读取','daily-funds-retry'):''}</div>`;}
function prepareDailyFundsReport(range){
preserveDailyFundsDrafts();++dailyFundsRequest;dailyFundsLoading=true;
dailyFundsEntry={user:dailyFundsUser(),key:dailyFundsViewKey(range),range:{...range},data:null,error:'',notice:''};renderDailyFunds();
}
function acceptDailyFundsReport(report,range){
if(!dailyFundsMatches())return;
const data=validateDailyFunds(report.dailyFunds,range),key=dailyFundsEntry.key;
dailyFundsEntry.data=data;dailyFundsLoading=false;
let draft=dailyOutlayDrafts.get(key);const confirmationRevision=data.confirmation?.revision||0;
if(!draft){draft={amount:((data.confirmation?.amount??Math.max(0,data.sources.total))/100).toFixed(2),note:data.confirmation?.note||'',verified:false,editing:!data.ready,sourceRevision:data.sources.revision,confirmationRevision};dailyOutlayDrafts.set(key,draft);}
draft.verified=false;
if(draft.confirmationRevision!==confirmationRevision){draft.confirmationRevision=confirmationRevision;draft.editing=true;dailyFundsEntry.notice='当天支出确认已被更新,填写内容已保留;请重新核对完整支出后勾选确认。';}
const reviewDraft=reimbursementReviews.get(key);if(reviewDraft)reviewDraft.verified=false;
if(draft.sourceRevision!==data.sources.revision){draft.sourceRevision=data.sources.revision;draft.editing=true;dailyFundsEntry.notice='已记录付款有变动,请重新核对当天完整支出。';}
if(data.confirmation?.stale)draft.editing=true;
renderDailyFunds();
}
function dailyFundsReportError(range,error){
if(!dailyFundsMatches())return;dailyFundsLoading=false;dailyFundsEntry.data=null;dailyFundsEntry.error=error.name==='AbortError'?'读取超时,填写内容已保留。':error.message;renderDailyFunds();
}
async function loadDailyFunds(range=dailyFundsRange(),notice=''){
const key=dailyFundsViewKey(range);await renderReport();
if(notice&&dailyFundsMatches()&&dailyFundsEntry.key===key&&dailyFundsEntry.data){dailyFundsEntry.notice=notice;renderDailyFunds();}
}
function dailyOutlayFormHTML(entry){
const draft=dailyOutlayDrafts.get(entry.key);if(!dailyFundsOwner()||entry.range.month||!draft||!draft.editing)return '';
return `<form id="daily-outlay-form" data-view-key="${e(entry.key)}" class="daily-outlay-form"><div class="daily-outlay-inputs">${field('麦麦当天完整实际对外支出(元)','amount',draft.amount,'number','min="0" step="0.01" required inputmode="decimal"')}${field('确认备注(选填)','note',draft.note,'text','maxlength="300"')}</div><p class="small muted">含未售现货采购及当天实际对外付款。不含客户退款(已从净收款扣除)、双方互转或报销转账。之前已经支付的货品,后续卖出不算一笔新支出。</p><label class="check"><input type="checkbox" name="verified" ${draft.verified?'checked':''} required>已核对完整支出;没有发生的,明确按 0 元确认。</label><div id="daily-outlay-error" aria-live="polite"></div><div class="actions"><button type="submit" class="primary">确认当天支出</button>${entry.data?.ready?button('收起','daily-outlay-close','quiet'):''}</div></form>`;
}
function dailyFundsSourcesHTML(data){
return `<details class="daily-funds-sources"><summary>已记录付款参考 ¥${yuan(data.sources.total)} <span class="small muted">${data.sources.items.length} 笔,可能不完整</span></summary><p class="small muted">只列麦麦按真实付款日期记录的费用、日购料和锁价采购等;不把普通订单耗用成本当作当天付款。完整总额以麦麦核实为准。</p><div class="table-wrap"><table aria-label="麦麦已记录实际付款参考"><thead><tr><th>付款日期</th><th>项目/说明</th><th class="number">金额</th></tr></thead><tbody>${data.sources.items.map(item=>`<tr><td>${e(item.date)}</td><td>${e(item.name)}${item.note?`<div class="small muted">${e(item.note)}</div>`:''}</td><td class="number">¥${yuan(item.amount)}</td></tr>`).join('')||'<tr><td colspan="3" class="muted">暂无已记录付款;这不代表当天完整支出一定为 0。</td></tr>'}</tbody></table></div></details>`;
}
function dailyTransferResultHTML(data,month=false){
const ready=data.ready&&!dailyFundsLoading;
const direction=data.transferAmount>0?'麦麦转助理':data.transferAmount<0?'助理转麦麦':'无需转款';
return `<div class="daily-transfer-parts"><div><span>麦麦净收款</span><strong>¥${yuan(data.ownerReceipts.net)}</strong><small>实收 ¥${yuan(data.ownerReceipts.receipt)} − 实退 ¥${yuan(data.ownerReceipts.refund)}</small></div><div><span>确认的完整对外支出</span><strong>${dailyFundsMoney(ready?data.actualOutlay:null)}</strong><small>${ready?'麦麦已核实':data.confirmation?.stale?'来源变动,需重新确认':'由麦麦核对后确认'}</small></div><div><span>已批准报销</span><strong>¥${yuan(data.approvedReimbursements)}</strong><small>按报销日期归集</small></div></div>${ready?`<div class="daily-transfer-result" aria-label="${month?'本期':'本日'}应转合计"><span>${month?'本期':'本日'}应转合计 · ${direction}</span><strong>¥${yuan(Math.abs(data.transferAmount))}</strong><p>麦麦净收款 ¥${yuan(data.ownerReceipts.net)} − 确认对外支出 ¥${yuan(data.actualOutlay)} + 已批准报销 ¥${yuan(data.approvedReimbursements)} = <b>¥${yuan(data.transferAmount)}</b></p><small>此为${month?'所选范围':'所选日'}应转合计,未扣已转;不要与下方旧按单/剩料待结重复相加。</small></div>`:`<p class="note daily-transfer-unready">${dailyFundsLoading?'正在重新读取,暂不显示应转合计。':month?'还有日期未完成支出确认,暂不显示完整应转合计。':'当天完整支出尚未确认,暂不显示应转合计。'}</p>`}`;
}
function dailyFundsMonthHTML(data){
return `<p class="small muted">月汇总只读。按每张报销单的报销日期归集,跨日批准仍回到原日期。</p>${data.missingDates.length?`<p class="small danger-text">待确认日期:${data.missingDates.map(e).join('、')}</p>`:''}${data.staleDates.length?`<p class="small danger-text">来源变动待重新确认:${data.staleDates.map(e).join('、')}</p>`:''}<div class="table-wrap"><table class="daily-funds-month-table" aria-label="每日转账核对汇总"><thead><tr><th>日期</th><th class="number">麦麦净收款</th><th class="number">确认支出</th><th class="number">批准报销</th><th class="number">应转合计</th><th>状态</th></tr></thead><tbody>${data.days.map(day=>`<tr><td>${button(e(day.date),'daily-funds-open-date','link-button',`data-date="${e(day.date)}"`)}</td><td class="number">¥${yuan(day.ownerReceipts.net)}</td><td class="number">${dailyFundsMoney(day.actualOutlay)}</td><td class="number">¥${yuan(day.approvedReimbursements)}</td><td class="number">${day.ready?dailyFundsMoney(day.transferAmount):'待确认'}</td><td>${day.ready?'已确认':day.confirmation?.stale?'需重新确认':'待确认'}</td></tr>`).join('')||'<tr><td colspan="6" class="muted">所选范围暂无需核对的记录。可切换单日确认。</td></tr>'}</tbody></table></div>`;
}
function reimbursementItemsHTML(row){return `<ul class="reimbursement-items-read">${row.items.map(item=>`<li><span>${e(item.name)}</span><b>¥${yuan(item.amount)}</b></li>`).join('')}</ul>`;}
function reimbursementRowsHTML(data,readOnly){
return `<div class="reimbursement-records">${data.reimbursements.map(row=>`<article class="reimbursement-record" data-id="${e(row.id)}"><div class="reimbursement-record-heading"><strong>${e(row.date)} · ¥${yuan(row.total)}</strong><span class="badge${row.status==='rejected'?' danger':row.status==='pending'?' warn':''}">${e(reimbursementStatusNames[row.status])}</span></div><p class="small muted">${e(row.requester_name||'提交人未提供')}提交${row.reviewer_name?' · '+e(row.reviewer_name)+'复核':''}</p>${reimbursementItemsHTML(row)}${row.note?`<p class="small reimbursement-note">备注:${e(row.note)}</p>`:''}${row.review_note?`<p class="small ${row.status==='rejected'?'danger-text':'muted'} reimbursement-note">${row.status==='rejected'?'驳回原因':'复核备注'}:${e(row.review_note)}</p>`:''}${!readOnly?`<div class="actions">${row.canEdit&&row.status!=='approved'?button(row.status==='rejected'?'修改后重新提交':'修改报销单','reimbursement-edit','',`data-id="${e(row.id)}"`):''}${dailyFundsOwner()&&row.canApprove&&row.status==='pending'?button('复核通过','reimbursement-approve','primary',`data-id="${e(row.id)}"`)+button('驳回','reimbursement-reject','',`data-id="${e(row.id)}"`):''}</div>`:''}</article>`).join('')||'<p class="small muted">所选日期暂无报销单。</p>'}</div>`;
}
function reimbursementDraftTotal(items){
let total=0,complete=true;const amounts=[];
for(const item of items){try{const amount=LedgerCalc.cents(item.amount);if(!amount)complete=false;total+=amount;amounts.push('¥'+yuan(amount));}catch{complete=false;}}
return {total,complete,formula:amounts.join(' + ')};
}
function reimbursementEditorHTML(entry){
const draftKey=reimbursementEditors.get(entry.key),draft=reimbursementDrafts.get(draftKey);if(!draft||entry.range.month)return '';
const summary=reimbursementDraftTotal(draft.items);
return `<form id="reimbursement-form" class="reimbursement-form" data-view-key="${e(entry.key)}" data-draft-key="${e(draftKey)}"><div class="panel-title"><h3>${draft.id?'修改报销单':'新增报销单'}</h3>${button('收起','reimbursement-close','quiet')}</div>${field('报销日期','date',draft.date,'date',`required max="${e(state.today)}"`)}<div class="reimbursement-item-labels"><span>报销项目</span><span>金额(元)</span><span></span></div><div id="reimbursement-items">${draft.items.map((item,index)=>`<div class="reimbursement-item-row" data-index="${index}"><label><span class="sr-only">项目 ${index+1}</span><input name="itemName" value="${e(item.name)}" required maxlength="100" placeholder="例如:进货工费、快递" aria-label="报销项目 ${index+1}"></label><label><span class="sr-only">金额 ${index+1}</span><input name="itemAmount" value="${e(item.amount)}" type="number" min="0.01" step="0.01" inputmode="decimal" required aria-label="报销金额 ${index+1}"></label>${button('移除','reimbursement-remove-item','quiet',`data-index="${index}" ${draft.items.length<=1?'disabled':''}`)}</div>`).join('')}</div>${button('+ 添加项目','reimbursement-add-item')}<p class="reimbursement-edit-total" id="reimbursement-edit-total">${summary.complete?summary.formula+' = ':'已填合计 '}<strong>¥${yuan(summary.total)}</strong></p>${field('备注(选填)','note',draft.note,'text','maxlength="300"')}<p class="small muted">报销单通过麦麦复核后,才计入报销日期的应转合计;这次提交不扣当天利润。</p><div id="reimbursement-error" aria-live="polite"></div><div class="actions"><button class="primary" type="submit">${draft.id?'保存并重新提交复核':'提交麦麦复核'}</button></div></form>`;
}
function reimbursementReviewHTML(entry){
const draft=reimbursementReviews.get(entry.key),row=entry.data?.reimbursements.find(item=>item.id===draft?.id);if(!draft||!row||entry.range.month)return '';
return `<form id="reimbursement-review-form" class="reimbursement-review-form" data-view-key="${e(entry.key)}"><div class="panel-title"><h3>${draft.kind==='approve'?'复核报销单':'驳回报销单'}</h3>${button('收起','reimbursement-review-close','quiet')}</div><p>${e(row.date)} · ${e(row.requester_name)}提交 · 合计 <strong>¥${yuan(row.total)}</strong></p>${reimbursementItemsHTML(row)}<label>${draft.kind==='reject'?'驳回原因':'复核备注(选填)'}<textarea name="note" maxlength="300" rows="2" ${draft.kind==='reject'?'required':''}>${e(draft.note)}</textarea></label>${draft.kind==='approve'?`<label class="check"><input type="checkbox" name="verified" ${draft.verified?'checked':''} required>已核对项目和金额,同意将 ¥${yuan(row.total)} 计入 ${e(row.date)} 的应转合计。</label>`:''}<div id="reimbursement-review-error" aria-live="polite"></div><div class="actions"><button class="primary" type="submit">${draft.kind==='approve'?'同意报销':'确认驳回'}</button></div></form>`;
}
function renderDailyFunds(){
const element=$('#daily-funds-content'),entry=dailyFundsEntry;if(!element||!entry||!dailyFundsMatches(entry))return;
const data=entry.data,month=entry.range.month||data?.readOnly,period=entry.range.month?entry.range.from+' 至 '+entry.range.date:entry.range.date;
element.setAttribute('aria-busy',String(dailyFundsLoading));
element.innerHTML=`${entry.error?dailyFundsStatusHTML(entry.error,true):dailyFundsLoading?dailyFundsStatusHTML('正在读取转账与报销资料…'):entry.notice?dailyFundsStatusHTML(entry.notice):''}<section class="panel daily-transfer" aria-label="每天转账核对"><div class="panel-title"><h2>每天转账核对</h2><span class="small muted">${e(period)}${month?' · 只读汇总':''}</span></div><p class="small muted">普通收退款按开单日期归集,锁价收退款按实际发生日期归集。报销与支出确认只用于转账核对。</p>${data?dailyTransferResultHTML(data,month):'<p class="small muted">资料未读取完成,暂不计算应转合计。</p>'}${data?(month?dailyFundsMonthHTML(data):dailyFundsSourcesHTML(data)):''}${data&&!month&&data.confirmation&&!data.confirmation.stale?`<div class="daily-confirmed-note small muted">${e(data.confirmation.actor||'麦麦')}已确认 ¥${yuan(data.confirmation.amount)}${dailyFundsOwner()?button('修改支出确认','daily-outlay-edit','quiet'):''}</div>`:''}${!month?dailyOutlayFormHTML(entry):''}${!month&&!dailyFundsOwner()?'<p class="small muted">当天完整对外支出由麦麦确认。</p>':''}</section><section class="panel daily-reimbursements" aria-label="每日报销单"><div class="panel-title"><h2>每日报销单</h2><div class="actions">${data?button('待复核('+data.pendingCount+')','reimbursement-open-list'):''}${data&&!month&&['owner','assistant'].includes(state.user.role)?button('新增报销单','reimbursement-new','primary'):''}</div></div><p class="small muted">按报销日期归集。待复核或被驳回的单据可修改后再提交;已批准单据只读,不能直接修改。</p>${!month?reimbursementEditorHTML(entry)+reimbursementReviewHTML(entry):''}${data?reimbursementRowsHTML(data,month):'<p class="small muted">报销资料尚未读到,已填写内容保留。</p>'}</section>`;
applyDailyFundsRestrictions();
}
function requireDailyFunds({owner=false,write=true}={}){
if(!dailyFundsMatches()||dailyFundsLoading||!dailyFundsEntry?.data||dailyFundsEntry.error)throw new Error('请先重新读取当前日期的转账与报销资料。');
if(owner&&!dailyFundsOwner())throw new Error('这项确认或复核只能由麦麦账号操作。');
if(write&&(dailyFundsEntry.range.month||dailyFundsEntry.data.readOnly))throw new Error('月汇总只读,请打开单日后操作。');
if(write&&(busy||pending()))throw new Error(pending()?'请先恢复原操作,确认上次提交结果。':'正在保存,请稍候。');
return dailyFundsEntry;
}
function applyDailyFundsRestrictions(){
const entry=dailyFundsEntry,blocked=busy||dailyFundsSaving||!!pending()||dailyFundsLoading||!dailyFundsMatches()||!entry?.data||!!entry.error;
for(const form of [$('#daily-outlay-form'),$('#reimbursement-form'),$('#reimbursement-review-form')])if(form)form.querySelectorAll('input,textarea,button').forEach(control=>{
const action=control.dataset.action,close=['daily-outlay-close','reimbursement-close','reimbursement-review-close'].includes(action);
control.disabled=close?busy:blocked||(form.id!=='reimbursement-form'&&!dailyFundsOwner())||(action==='reimbursement-remove-item'&&form.querySelectorAll('.reimbursement-item-row').length<=1);
});
$('#daily-funds-content')?.querySelectorAll('[data-action="reimbursement-new"],[data-action="reimbursement-edit"],[data-action="reimbursement-approve"],[data-action="reimbursement-reject"],[data-action="daily-outlay-edit"]').forEach(control=>control.disabled=blocked);
}
function dailyFundsOperation(url){return url==='/api/daily-funds/confirm'?{kind:'confirm'}:url==='/api/reimbursements'?{kind:'create'}:(()=>{const match=url.match(/^\/api\/reimbursements\/([^/]+)\/(update|approve|reject)$/);return match?{kind:match[2],id:decodeURIComponent(match[1])}:null;})();}
function reimbursementDraftSnapshot(draft){return JSON.stringify({identity:draft.identity,id:draft.id||'',revision:draft.revision??0,date:draft.date,items:draft.items,note:draft.note});}
function dailyFundsRecoveryOrigin(job){return dailyFundsPendingOrigins.get(job.key)||null;}
async function dailyFundsError(err,operation=null){
preserveDailyFundsDrafts();const entry=dailyFundsEntry,key=entry?.key;
err.message=String(err.message).replace('不要重新开单','不要重复提交确认或报销');
const checkbox=$('#daily-outlay-form [name="verified"]');if(checkbox)checkbox.checked=false;
const review=$('#reimbursement-review-form [name="verified"]');if(review)review.checked=false;
if(key){const outlay=dailyOutlayDrafts.get(key);if(outlay)outlay.verified=false;const draft=reimbursementReviews.get(key);if(draft)draft.verified=false;}
if(err.status===409&&entry&&dailyFundsMatches(entry)){
await loadDailyFunds(entry.range,'资料已有变动,填写内容已保留。请核对最新资料后重新提交。');
const updated=dailyFundsEntry?.data,editorKey=reimbursementEditors.get(key),editor=reimbursementDrafts.get(editorKey);
if(editor?.id){const current=updated?.reimbursements.find(item=>item.id===editor.id);if(current?.canEdit&&current.status!=='approved')editor.revision=current.revision;}
const draft=reimbursementReviews.get(key);if(draft){const current=updated?.reimbursements.find(item=>item.id===draft.id);if(current?.status==='pending'&&current.canApprove)draft.revision=current.revision;else reimbursementReviews.delete(key);}
renderDailyFunds();
}
const target=operation?.kind==='confirm'?$('#daily-outlay-error'):['approve','reject'].includes(operation?.kind)?$('#reimbursement-review-error'):$('#reimbursement-error');
if(target)target.innerHTML=`<div class="error">${e(err.message)}${pending()?' '+button('恢复原操作','retry','danger'):err.status===409?' 请重新核对后再提交。':' '+button('重新读取资料','daily-funds-retry')}</div>`;
else if(dailyFundsMatches()){dailyFundsEntry.notice=err.message;renderDailyFunds();}
applyDailyFundsRestrictions();toast(err.message,true);
}
async function submitDailyFundsForm(form){
let operation=form.id==='daily-outlay-form'?{kind:'confirm'}:form.id==='reimbursement-review-form'?{kind:reimbursementReviews.get(form.dataset.viewKey)?.kind}:null;
let origin;
try{
preserveDailyFundsDrafts();const entry=requireDailyFunds({owner:form.id!=='reimbursement-form'});if(form.dataset.viewKey!==entry.key)throw new Error('日期或账号已变化,请重新读取。');
let url,input;
if(form.id==='daily-outlay-form'){
const draft=dailyOutlayDrafts.get(entry.key),amount=String(draft.amount).trim();LedgerCalc.cents(amount,'完整对外支出');if(!draft.verified)throw new Error('请核对当天完整支出并勾选确认,0 元也需要确认。');
input={date:entry.range.date,amount,revision:draft.confirmationRevision,sourceRevision:draft.sourceRevision,note:draft.note.trim(),verified:true};url='/api/daily-funds/confirm';
}else if(form.id==='reimbursement-form'){
const draft=reimbursementDrafts.get(form.dataset.draftKey);if(!draft||reimbursementEditors.get(entry.key)!==form.dataset.draftKey)throw new Error('请重新打开报销单。');
if(!validOrderDate(draft.date)||draft.date>state.today)throw new Error('报销日期请选择今天或之前的有效日期。');
if(!draft.items.length||draft.items.length>60)throw new Error('每张报销单需要 1~60 个项目。');
const items=draft.items.map(item=>{const name=item.name.trim(),amount=String(item.amount).trim();if(!name||name.length>100)throw new Error('每项报销名称请填写 1~100 字。');if(LedgerCalc.cents(amount,'报销金额')<=0)throw new Error('每项报销金额必须大于 0。');return {name,amount};});
if(draft.note.length>300)throw new Error('备注最多 300 字。');
if(draft.id){const row=entry.data.reimbursements.find(item=>item.id===draft.id);if(!row?.canEdit||row.status==='approved'||row.revision!==draft.revision)throw new Error('报销单已变化或已批准,请重新读取后核对。');}
else if(!['owner','assistant'].includes(state.user.role))throw new Error('请使用麦麦或助理账号提交报销单。');
input={date:draft.date,items,note:draft.note.trim(),...(draft.id?{revision:draft.revision}:{})};url=draft.id?'/api/reimbursements/'+encodeURIComponent(draft.id)+'/update':'/api/reimbursements';
}else if(form.id==='reimbursement-review-form'){
const draft=reimbursementReviews.get(entry.key),row=entry.data.reimbursements.find(item=>item.id===draft?.id);if(!draft||!row?.canApprove||row.status!=='pending'||row.revision!==draft.revision)throw new Error('报销单已变化,请重新读取后复核。');
const note=draft.note.trim();if(note.length>300||draft.kind==='reject'&&!note)throw new Error(draft.kind==='reject'?'请填写 1~300 字的驳回原因。':'复核备注最多 300 字。');
if(draft.kind==='approve'&&!draft.verified)throw new Error('请核对报销项目和金额,并勾选复核确认。');
input={revision:draft.revision,note,...(draft.kind==='approve'?{verified:true}:{})};url='/api/reimbursements/'+encodeURIComponent(row.id)+'/'+draft.kind;
}else return;
operation=dailyFundsOperation(url);const draftKey=reimbursementEditors.get(entry.key),draft=reimbursementDrafts.get(draftKey);
origin={key:entry.key,user:entry.user,...(form.id==='reimbursement-form'&&draft?{draftKey,draftSnapshot:reimbursementDraftSnapshot(draft)}:{})};
dailyFundsSaving=true;applyDailyFundsRestrictions();const result=await mutate(url,input);return await finishDailyFundsSave(url,input,result,origin);
}catch(err){const job=pending();if(job&&origin)dailyFundsPendingOrigins.set(job.key,origin);return await dailyFundsError(err,operation);}
finally{dailyFundsSaving=false;applyDailyFundsRestrictions();}
}
async function finishDailyFundsSave(url,input,result,origin=null){
const operation=dailyFundsOperation(url);if(!operation)return;
const date=result.reimbursement?.date||result.date||input.date,entry=dailyFundsEntry;
const message=operation.kind==='confirm'?'当天完整支出已确认':operation.kind==='approve'?'报销已批准,已计入报销日期的应转合计':operation.kind==='reject'?'报销已驳回,原原因保留':'报销单已提交,等待麦麦复核';
const viewKey=origin?.user===dailyFundsUser()?origin.key:null;
if(viewKey){
if(operation.kind==='confirm'){const draft=dailyOutlayDrafts.get(viewKey);if(draft&&viewKey===dailyFundsUser()+'|'+input.date+'|'+input.date+'|false'){draft.verified=false;draft.editing=false;draft.confirmationRevision=result.confirmation.revision;draft.sourceRevision=result.confirmation.sourceRevision;}}
if(['create','update'].includes(operation.kind)){const draft=reimbursementDrafts.get(origin.draftKey);if(draft&&reimbursementDraftSnapshot(draft)===origin.draftSnapshot){reimbursementDrafts.delete(origin.draftKey);if(reimbursementEditors.get(viewKey)===origin.draftKey)reimbursementEditors.delete(viewKey);}}
const review=reimbursementReviews.get(viewKey);if(review?.id===operation.id)reimbursementReviews.delete(viewKey);
}
if(tab==='report'&&(!origin||origin.user===dailyFundsUser()))await renderReport();
if($('#daily-reimbursements-dialog')?.open)await loadDailyReimbursements();
if(origin)for(const [key,value] of dailyFundsPendingOrigins)if(value===origin)dailyFundsPendingOrigins.delete(key);
toast(message+(date&&date!==reportDate?'('+date+')':''));
}
function dailyFundsDownloadText(report){
const range={date:report.date,from:report.from,month:reportMonth},data=report.dailyFunds;
if(!data||data.rangeUnsupported)return ['每天转账核对','尚未取得完整转账资料,不输出应转金额。',''];
try{validateDailyFunds(data,range);}catch{return ['每天转账核对','资料未完整返回,不输出应转金额。',''];}
const result=['每天转账核对(应转合计,未扣已转)',`麦麦实收 ¥${yuan(data.ownerReceipts.receipt)} − 实退 ¥${yuan(data.ownerReceipts.refund)} = 净收款 ¥${yuan(data.ownerReceipts.net)}`];
if(data.ready)result.push(`麦麦净收款 ¥${yuan(data.ownerReceipts.net)} − 确认完整对外支出 ¥${yuan(data.actualOutlay)} + 已批准报销 ¥${yuan(data.approvedReimbursements)} = 应转合计 ¥${yuan(data.transferAmount)}`,data.transferAmount>0?'方向:麦麦转助理':data.transferAmount<0?'方向:助理转麦麦':'方向:无需转款');
else result.push('当天完整支出尚未全部确认,暂不输出完整应转合计。',...(data.missingDates.length?['待确认日期:'+data.missingDates.join('、')]:[]),...(data.staleDates.length?['来源变动待重新确认:'+data.staleDates.join('、')]:[]));
result.push('不要与旧按单/剩料待结重复相加;报销与确认不扣订单利润。','已批准报销项目(按报销日期归集)');
const approved=data.reimbursements.filter(row=>row.status==='approved');
result.push(...(approved.length?approved.flatMap(row=>[`${row.date} / ${row.requester_name} / 合计 ¥${yuan(row.total)} / ${row.reviewer_name||'麦麦'}复核`,...row.items.map(item=>`${item.name}:¥${yuan(item.amount)}`)]):['本期暂无已批准报销。']),'');return result;
}
async function dailyFundsAction(action,buttonNode){
try{
preserveDailyFundsDrafts();
if(action==='daily-funds-retry')return await loadDailyFunds();
if(action==='reimbursement-open-list')return await openDailyReimbursements();
if(action==='reimbursement-close-list'){++dailyReimbursementsRequest;$('#daily-reimbursements-dialog')?.close();return;}
if(action==='reimbursement-list-retry')return await loadDailyReimbursements();
if(action==='reimbursement-list-page'){dailyReimbursementsOffset=Number(buttonNode.dataset.offset)||0;return await loadDailyReimbursements();}
if(action==='daily-funds-open-date'||action==='reimbursement-open-date'){
const date=buttonNode.dataset.date;if(!validOrderDate(date))throw new Error('请选择有效日期。');
$('#daily-reimbursements-dialog')?.close();reportDate=date;reportMonth=false;await renderReport();
if(action==='reimbursement-open-date'&&dailyFundsOwner()&&buttonNode.dataset.id&&dailyFundsEntry?.data?.reimbursements.some(row=>row.id===buttonNode.dataset.id&&row.canApprove))return await dailyFundsAction('reimbursement-approve',buttonNode);
$('#daily-funds-content')?.scrollIntoView({block:'start',behavior:'smooth'});return;
}
const entry=requireDailyFunds({owner:action.startsWith('daily-outlay')||['reimbursement-approve','reimbursement-reject'].includes(action)});
if(action==='daily-outlay-edit'){dailyOutlayDrafts.get(entry.key).editing=true;dailyOutlayDrafts.get(entry.key).verified=false;}
if(action==='daily-outlay-close')dailyOutlayDrafts.get(entry.key).editing=false;
if(action==='reimbursement-new'){
if(!['owner','assistant'].includes(state.user.role))throw new Error('请使用麦麦或助理账号提交报销单。');const key=dailyFundsUser()+'|new';
if(!reimbursementDrafts.has(key))reimbursementDrafts.set(key,{identity:crypto.randomUUID(),id:'',date:state.today,items:[{name:'',amount:''}],note:''});reimbursementEditors.set(entry.key,key);
}
if(action==='reimbursement-edit'){
const row=entry.data.reimbursements.find(item=>item.id===buttonNode.dataset.id);if(!row?.canEdit||row.status==='approved')throw new Error('这张报销单当前不可修改。');
const key=dailyFundsUser()+'|'+row.id;if(!reimbursementDrafts.has(key))reimbursementDrafts.set(key,{identity:crypto.randomUUID(),id:row.id,revision:row.revision,date:row.date,items:row.items.map(item=>({name:item.name,amount:(item.amount/100).toFixed(2)})),note:row.note||''});reimbursementEditors.set(entry.key,key);
}
if(action==='reimbursement-close')reimbursementEditors.delete(entry.key);
if(action==='reimbursement-add-item'||action==='reimbursement-remove-item'){
const draft=reimbursementDrafts.get(reimbursementEditors.get(entry.key));if(!draft)return;
if(action==='reimbursement-add-item'){if(draft.items.length>=60)throw new Error('每张报销单最多 60 个项目。');draft.items.push({name:'',amount:''});}
else if(draft.items.length>1)draft.items.splice(Number(buttonNode.dataset.index),1);
}
if(action==='reimbursement-approve'||action==='reimbursement-reject'){
const row=entry.data.reimbursements.find(item=>item.id===buttonNode.dataset.id);if(!row?.canApprove||row.status!=='pending')throw new Error('这张报销单当前不可复核。');
reimbursementReviews.set(entry.key,{id:row.id,revision:row.revision,kind:action==='reimbursement-approve'?'approve':'reject',note:'',verified:false});
}
if(action==='reimbursement-review-close')reimbursementReviews.delete(entry.key);
renderDailyFunds();if(action==='reimbursement-new'||action==='reimbursement-edit')$('#reimbursement-form')?.scrollIntoView({block:'nearest',behavior:'smooth'});if(action==='reimbursement-approve'||action==='reimbursement-reject')$('#reimbursement-review-form')?.scrollIntoView({block:'nearest',behavior:'smooth'});
}catch(err){return await dailyFundsError(err);}
}
function dailyFundsInput(target){
if(!target.closest('#daily-outlay-form,#reimbursement-form,#reimbursement-review-form'))return;
if(target.closest('#daily-outlay-form')&&target.name!=='verified'){const verified=$('#daily-outlay-form [name="verified"]');if(verified)verified.checked=false;}
preserveDailyFundsDrafts();
if(target.closest('#reimbursement-form')){const draft=reimbursementDrafts.get($('#reimbursement-form').dataset.draftKey),total=reimbursementDraftTotal(draft.items),node=$('#reimbursement-edit-total');if(node)node.innerHTML=(total.complete?total.formula+' = ':'已填合计 ')+`<strong>¥${yuan(total.total)}</strong>`;}
}
function validateDailyReimbursements(data){
if(!data||!Array.isArray(data.requests)||!Number.isSafeInteger(data.total)||!Number.isSafeInteger(data.offset)||!Number.isSafeInteger(data.limit)||typeof data.hasMore!=='boolean'||!['pending','approved','rejected'].every(key=>Number.isSafeInteger(data.counts?.[key])))throw new Error('全日期报销列表未完整返回,请重新读取。');data.requests.forEach(validateReimbursement);return data;
}
async function openDailyReimbursements(){dailyReimbursementsOffset=0;const dialog=$('#daily-reimbursements-dialog');if(!dialog)throw new Error('请刷新页面后再查看报销列表。');if(!dialog.open)dialog.showModal();return await loadDailyReimbursements();}
async function loadDailyReimbursements(){
const dialog=$('#daily-reimbursements-dialog'),body=$('#daily-reimbursements-list');if(!dialog?.open||!body)return;
const request=++dailyReimbursementsRequest,user=dailyFundsUser();body.innerHTML='<p class="small muted" role="status">正在读取所有日期的待复核报销单…</p>';
try{
const data=await api('/api/reimbursements?'+new URLSearchParams({status:'pending',limit:'50',offset:String(dailyReimbursementsOffset)}));
if(request!==dailyReimbursementsRequest||!dialog.open||user!==dailyFundsUser())return;validateDailyReimbursements(data);dailyReimbursementsList=data;
body.innerHTML=`<h2>所有日期待复核报销单(${data.counts.pending})</h2><p class="small muted">点击原报销日期查看并复核;批准后回到该日期的应转合计。</p><div class="table-wrap"><table class="daily-reimbursements-global-table" aria-label="所有日期待复核报销单"><thead><tr><th>报销日期</th><th>提交人/项目</th><th class="number">合计</th><th></th></tr></thead><tbody>${data.requests.map(row=>`<tr><td>${e(row.date)}</td><td>${e(row.requester_name)}<div class="small muted">${row.items.map(item=>e(item.name)).join('、')}</div></td><td class="number">¥${yuan(row.total)}</td><td>${button(dailyFundsOwner()&&row.canApprove?'查看并复核':'查看原日期','reimbursement-open-date','',`data-date="${e(row.date)}" data-id="${e(row.id)}"`)}</td></tr>`).join('')||'<tr><td colspan="4" class="muted">目前没有待复核的报销单。</td></tr>'}</tbody></table></div><div class="form-actions"><span class="small muted">共 ${data.total} 张 · 当前 ${data.offset+1}~${Math.min(data.offset+data.requests.length,data.total)}</span><div class="actions">${button('上一页','reimbursement-list-page','',`data-offset="${Math.max(0,data.offset-data.limit)}" ${data.offset===0?'disabled':''}`)}${button('下一页','reimbursement-list-page','',`data-offset="${data.offset+data.limit}" ${!data.hasMore?'disabled':''}`)}</div></div>`;
}catch(err){if(request===dailyReimbursementsRequest&&dialog.open&&user===dailyFundsUser())body.innerHTML=`<div class="error">${e(err.message)} ${button('重新读取','reimbursement-list-retry')}</div>`;}
}