改善断连自动恢复并按上次有效记录计算人数增量

This commit is contained in:
summer committed 2026-10-29 00:27:36 +08:00
1 parent 3ef8a16eca
commit 914a2b7287
11 files changed
+334 -69

No files matched your search

+88 -23
View File
@@ -28,20 +28,80 @@ const button=(text,action,cls='',attrs='')=>`<button type="button" data-action="
const badge=o=>`<span class="order-status ${['draft','confirmed'].includes(o.status)?'danger-text':'muted'}">${e(label[o.status]||o.status)}</span>`;
const card=(title,value,hint='',emphasis=false)=>`<div class="stat ${emphasis?'emphasis':''}"><small>${title}</small><strong>${value}</strong><div class="hint">${hint}</div></div>`;
function toast(message,error=false){const t=$('#toast');t.textContent=message;t.className=error?'error-toast':'';t.hidden=false;clearTimeout(toast.timer);toast.timer=setTimeout(()=>t.hidden=true,error?9000:3500);}
async function api(url,data,operation){
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),25000);
try{const r=await fetch(url,{method:data?'POST':'GET',headers:data?{'Content-Type':'application/json','X-Requested-With':'maimai-ledger',...(operation?{'Idempotency-Key':operation}:{})}:{},...(data?{body:JSON.stringify(data)}:{}),signal:controller.signal});const result=await r.json();if(!r.ok){const err=new Error(result.error||'请求失败');err.confirmed=true;err.status=r.status;throw err;}return result;}finally{clearTimeout(timer);}
const MUTATION_RETRY=Symbol('mutationRetry');
const requestBackoffs=[400,1200];
const requestProgress=new Map();
const requestUser=()=>session?session.user?.id||'':state?.user?.id||'';
function accountChangedError(){return Object.assign(new Error('登录账号已切换,请刷新后继续;原操作已暂停。'),{status:409,code:'ACCOUNT_CHANGED'});}
function showRequestProgress(token,message=''){
if(message)requestProgress.set(token,message);else requestProgress.delete(token);
const text=[...requestProgress].filter(([key])=>key.user===requestUser()).sort(([a],[b])=>Number(a.write)-Number(b.write)).at(-1)?.[1]||'';
const target=$('#request-status');if(target){target.hidden=!text;target.textContent=text;}
for(const dialog of document.querySelectorAll('dialog[open]')){
let notice=dialog.querySelector('.request-progress');
if(text&&!notice){notice=document.createElement('p');notice.className='request-progress small muted';notice.setAttribute('role','status');dialog.append(notice);}
if(notice){notice.textContent=text;notice.hidden=!text;}
}
}
function retryableMutation(url){
// 只有服务端事务幂等入口可自动确认;密码、备份、同步及新未知接口不在这里。
return ['/api/orders','/api/orders/issue','/api/people-count','/api/after-sales','/api/recoveries','/api/material-purchases','/api/material-pools/rolling-enable','/api/price-locks','/api/order-templates','/api/reimbursements','/api/daily-funds/confirm','/api/team-funds/transfers','/api/team-funds/transfer','/api/stock','/api/inventory/review','/api/close','/api/printing'].includes(url)||[
/^\/api\/orders\/[^/]+\/(?:edit|ownership|change|cancellation|canceltoday|confirm|receipt|refund|expense|fees|cost|deliver|complete|cancel|return|settlement|review|correct|print)$/,
/^\/api\/(?:order-templates\/[^/]+\/(?:update|delete)|reimbursements\/[^/]+\/(?:update|approve|reject)|price-locks\/[^/]+\/deliver|material-purchases\/[^/]+\/(?:edit|delete|change)|material-pools\/\d{4}-\d{2}-\d{2}\/settlement|after-sales\/[^/]+\/update|after-sales\/changes\/[^/]+\/(?:approve|reject)|(?:order-changes|order-ownership-changes|order-cancellations|material-purchase-changes)\/[^/]+\/(?:approve|reject)|inventory\/movements\/[^/]+\/(?:update|delete)|inventory\/changes\/[^/]+\/(?:approve|reject))$/
].some(pattern=>pattern.test(url));
}
async function api(url,data,operation,retryContext){
const write=!!data,body=write?JSON.stringify(data):undefined;
const protectedRequest=url.startsWith('/api/')&&!['/api/session','/api/login','/api/setup','/api/demo-login'].includes(url),user=protectedRequest?(retryContext?.user||requestUser()):'';
const retry=!write||retryContext?.permission===MUTATION_RETRY&&retryableMutation(url)&&/^[a-zA-Z0-9_-]{16,100}$/.test(operation||'');
const token={user:user||requestUser(),write},active=()=>!user||requestUser()===user;
if(write&&retryContext)showRequestProgress(token,'正在保存,请稍候…');
try{
for(let attempt=0;;attempt++){
if(!active())throw accountChangedError();
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),25000);
try{
const r=await fetch(url,{method:write?'POST':'GET',headers:{...(write?{'Content-Type':'application/json','X-Requested-With':'maimai-ledger',...(operation?{'Idempotency-Key':operation}:{})}:{}),...(user?{'X-Ledger-User':user}:{})},...(write?{body}:{}),signal:controller.signal});
// 网关可能返回HTML,先按状态识别,不能让JSON解析失败掩盖502等。
if([408,502,503,504].includes(r.status))throw Object.assign(new Error('服务器暂时没有响应('+r.status+')'),{status:r.status,retryable:true});
let result;try{result=await r.json();}catch(error){if(r.ok){error.retryable=true;throw error;}result=null;}
if(!r.ok){const confirmed=!!result&&typeof result.error==='string';throw Object.assign(new Error(confirmed?result.error:'请求被拒绝('+r.status+'),服务器未返回可确认的业务结果。'),{confirmed,status:r.status,...(result?.code?{code:result.code}:{})});}
if(!active())throw Object.assign(accountChangedError(),{completed:true});
return result;
}catch(err){
if(!active()&&err.code!=='ACCOUNT_CHANGED')throw accountChangedError();
const transient=err.retryable||!err.status&&['TypeError','AbortError','TimeoutError'].includes(err.name);
if(!retry||!transient||attempt>=requestBackoffs.length)throw err;
showRequestProgress(token,'连接暂时中断,正在自动'+(write?'确认':'重连')+'('+(attempt+1)+'/2)…');
await new Promise(resolve=>setTimeout(resolve,requestBackoffs[attempt]));
}finally{clearTimeout(timer);}
}
}finally{showRequestProgress(token);}
}
const pendingKey=()=>`mm-pending-${session?.user?.id}`;
function pending(){try{return JSON.parse(localStorage.getItem(pendingKey())||'null');}catch{return null;}}
function showPending(){const p=pending();$('#pending').hidden=!p;if(p)$('#pending').innerHTML=`上次提交结果尚未确认,请先恢复原操作。重试会使用同一个操作号。 ${button('恢复原操作','retry','danger')}`;}
function showPending(){const p=pending(),target=$('#pending');if(!target)return;target.hidden=!p||busy;if(p&&!busy)target.innerHTML=`上次提交结果尚未确认,请先恢复原操作。重试会使用同一个操作号。 ${button('恢复原操作','retry','danger')}`;}
function clearPendingJob(storageKey,job){try{if(JSON.parse(localStorage.getItem(storageKey)||'null')?.key===job.key)localStorage.removeItem(storageKey);}catch{}}
async function mutate(url,data,existing){
if(busy)throw new Error('正在保存,请稍候');if(pending()&&!existing)throw new Error('请先点击顶部“恢复原操作”,确认上次提交结果');
const job=existing||{url,data,key:crypto.randomUUID()},storageKey=pendingKey();busy=true;localStorage.setItem(storageKey,JSON.stringify(job));
document.querySelectorAll('button').forEach(b=>b.disabled=true);
try{const r=await api(job.url,job.data,job.key);localStorage.removeItem(storageKey);return r;}
catch(err){if(err.confirmed&&[400,403,404,409,413].includes(err.status))localStorage.removeItem(storageKey);else if(err.status===401)err.message='登录已过期,请刷新并登录,再恢复原操作。';else err.message='连接中断,提交结果待确认。请点“恢复原操作”,不要重新开单。';throw err;}
finally{busy=false;document.querySelectorAll('button').forEach(b=>b.disabled=false);showPending();applyAfterSaleRestrictions();if(typeof applyOrderCancellationRestrictions==='function')applyOrderCancellationRestrictions();if(typeof applyOrderChangeRestrictions==='function')applyOrderChangeRestrictions();if(typeof applyOrderOwnershipRestrictions==='function')applyOrderOwnershipRestrictions();if(typeof applyOrderEditRestrictions==='function')applyOrderEditRestrictions();if(typeof applyDailyFundsRestrictions==='function')applyDailyFundsRestrictions();if(typeof applyInventoryChangeRestrictions==='function')applyInventoryChangeRestrictions();if(typeof applyRecoveryRestrictions==='function')applyRecoveryRestrictions();if(typeof applyMaterialRollingRestrictions==='function')applyMaterialRollingRestrictions();updateOrderDetailNavigation();}
const user=requestUser();if(!user)throw new Error('请先登录后再保存');
// 首次发送前复制完整请求,表单继续变动也不能改变自动重试的内容。
const job=JSON.parse(JSON.stringify(existing||{url,data,key:crypto.randomUUID(),userId:user})),storageKey=pendingKey();
if(existing&&(job.userId&&job.userId!==user||JSON.stringify(pending())!==JSON.stringify(existing)))throw new Error('待恢复操作与当前账号不匹配,请刷新后核对。');
busy=true;
const buttons=[...document.querySelectorAll('button')].map(button=>[button,button.disabled]);
try{
localStorage.setItem(storageKey,JSON.stringify(job));showPending();buttons.forEach(([button])=>button.disabled=true);
const r=await api(job.url,job.data,job.key,{permission:MUTATION_RETRY,user});clearPendingJob(storageKey,job);return r;
}catch(err){
if(err.completed||err.code!=='ACCOUNT_CHANGED'&&err.confirmed&&[400,403,404,409,413].includes(err.status))clearPendingJob(storageKey,job);
if(err.code!=='ACCOUNT_CHANGED'){
if(err.status===401)err.message='登录已过期,请刷新并登录,再恢复原操作。';
else if(!err.confirmed&&(!err.status||err.retryable))err.message='连接中断,提交结果待确认。请点“恢复原操作”,不要重新开单。';
else if(!err.confirmed)err.message+=' 提交结果仍待确认,请保留原操作。';
}
throw err;
}finally{busy=false;buttons.forEach(([button,disabled])=>button.disabled=disabled);showPending();applyAfterSaleRestrictions();if(typeof applyOrderCancellationRestrictions==='function')applyOrderCancellationRestrictions();if(typeof applyOrderChangeRestrictions==='function')applyOrderChangeRestrictions();if(typeof applyOrderOwnershipRestrictions==='function')applyOrderOwnershipRestrictions();if(typeof applyOrderEditRestrictions==='function')applyOrderEditRestrictions();if(typeof applyDailyFundsRestrictions==='function')applyDailyFundsRestrictions();if(typeof applyInventoryChangeRestrictions==='function')applyInventoryChangeRestrictions();if(typeof applyRecoveryRestrictions==='function')applyRecoveryRestrictions();if(typeof applyMaterialRollingRestrictions==='function')applyMaterialRollingRestrictions();updateOrderDetailNavigation();}
}
async function init(){
invalidateAfterSaleViews();
@@ -587,25 +647,26 @@ function peopleCountText(count,part=null){
const value=part?count?.[part]:count;
if(!value||!Object.hasOwn(value,'endTotal')||!Object.hasOwn(value,'netChange'))return '尚未取得总人数';
const period=count.from!==count.date,total=value.endTotal===null?(period?'结束日未记录':'当日未记录'):value.endTotal+' 人(已记录)';
return total+' · '+(period?'本期净增 '+(value.netChange===null?'未知('+peopleCountUnknownReason(value.netChangeReason,true)+')':peopleCountSignedText(value.netChange)):value.netChange===null?'较昨日变化未知('+peopleCountUnknownReason(value.netChangeReason)+')':'较昨日'+peopleCountDeltaText(value.netChange));
const baseline=value.baselineDate,comparison='较上次记录'+(baseline?'('+baseline+')':'');
return total+' · '+(period?'本期净增 '+(value.netChange===null?'未知('+peopleCountUnknownReason(value.netChangeReason,true)+')':peopleCountSignedText(value.netChange))+(baseline?'(基准 '+baseline+')':''):value.netChange===null?(value.endTotal!==null&&value.netChangeReason==='missing-previous'?'首次记录(暂无上次记录)':comparison+'变化未知('+peopleCountUnknownReason(value.netChangeReason)+')'):comparison+peopleCountDeltaText(value.netChange));
}
function peopleCountDisplayName(name,period=false){return name.replace('人数',period?'结束日总人数':'当日总人数');}
function peopleCountNumber(value){return Number.isSafeInteger(value)&&value>=0&&value<=1000000;}
function peopleCountPreviousDate(date){return new Date(Date.parse(date+'T00:00:00Z')-86400000).toISOString().slice(0,10);}
function peopleCountChangeReason(current,previous){return current===null?(previous===null?'missing-both':'missing-current'):previous===null?'missing-previous':null;}
function peopleCountUnknownReason(reason,period=false){return ({'missing-current':period?'结束日未记录':'当日未记录','missing-previous':period?'期初前一天未记录':'昨日未记录','missing-both':period?'结束日和期初前一天均未记录':'当日和昨日均未记录'})[reason]||'缺少人数记录';}
function peopleCountUnknownReason(reason,period=false){return ({'missing-current':period?'结束日未记录':'当日未记录','missing-previous':period?'开始日前暂无记录':'暂无上次记录','missing-both':period?'结束日未记录,开始日前暂无记录':'当日未记录,暂无上次记录'})[reason]||'缺少人数记录';}
function peopleCountDeltaText(value){return value>0?'新增 '+value+' 人':value<0?'减少 '+Math.abs(value)+' 人':'无变化(0 人)';}
function peopleCountSignedText(value){return (value>0?'+':'')+value+' 人';}
function peopleCountHTML(count){
const period=count?.from!==count?.date;
return peopleParts().map(([part,name])=>`<div class="people-count-item"><strong>${peopleCountDisplayName(name,period)}</strong><span>${e(peopleCountText(count,part))}</span></div>`).join('')+`<small>${period?'本期净增='+e(count?.date||'结束日')+'总人数-'+e(count?.baselineDate||'开始日前一天')+'总人数,缺任一端则未知。':'较昨日变化按自然日前一天计算;缺记录时不按0计算。'}不随订单搜索与状态筛选变化。</small>`;
return peopleParts().map(([part,name])=>`<div class="people-count-item"><strong>${peopleCountDisplayName(name,period)}</strong><span>${e(peopleCountText(count,part))}</span></div>`).join('')+`<small>${period?'本期净增=结束日总人数-各自开始日前最近记录总人数;缺任一端则未知,每日总人数不累加。':'各自与上次有记录日期比较,未记录日自动跳过;0为有效记录。'}不随订单搜索与状态筛选变化。</small>`;
}
function peopleCountReportLines(count){const period=count?.from!==count?.date;return peopleParts().map(([part,name])=>`${peopleCountDisplayName(name,period)}:${peopleCountText(count,part)}${period?'(期末 '+(count?.date||'未知')+';期初基准 '+(count?.baselineDate||'未知')+')':''}`);}
function validPeopleCountDaily(entry,date,names){return entry?.date===date&&entry.previousDate===peopleCountPreviousDate(date)&&names.every(name=>{const current=entry[name],previous=entry.previous?.[name],prefix=name.replace(/Count$/,'');return (current===null||peopleCountNumber(current))&&(previous===null||peopleCountNumber(previous))&&entry[prefix+'Change']===(current===null||previous===null?null:current-previous)&&entry[prefix+'ChangeReason']===peopleCountChangeReason(current,previous);});}
function peopleCountReportLines(count){const period=count?.from!==count?.date;return peopleParts().map(([part,name])=>`${peopleCountDisplayName(name,period)}:${peopleCountText(count,part)}${period?'(期末 '+(count?.date||'未知')+';开始日前最近记录 '+(count?.[part]?.baselineDate||'暂无')+')':''}`);}
function validPeopleCountDaily(entry,date,names){return entry?.mode==='daily-total'&&entry.date===date&&entry.previousDate===peopleCountPreviousDate(date)&&names.every(name=>{const current=entry[name],previous=entry.previous?.[name],prefix=name.replace(/Count$/,''),previousDate=entry.previousDates?.[prefix];return (current===null||peopleCountNumber(current))&&(previous===null||peopleCountNumber(previous))&&(previous===null?previousDate===null:validOrderDate(previousDate)&&previousDate>='2000-01-01'&&previousDate<date)&&entry[prefix+'Change']===(current===null||previous===null?null:current-previous)&&entry[prefix+'ChangeReason']===peopleCountChangeReason(current,previous);});}
function syncPeopleCountPreview(){
const form=$('#people-count-form'),target=$('#people-count-preview');if(!form||!target)return;
if(!peopleEntry||peopleEntry.date!==form.elements.date.value||peopleEntryUser!==(state.user.id||state.user.name)){target.innerHTML='<p class="small muted">正在读取昨日总人数…</p>';return;}
target.innerHTML=peopleParts().map(([part,name])=>{const field=part+'Count',previous=peopleEntry.previous[field];let current;try{current=peopleCountInput(form.elements[field].value,peopleCountDisplayName(name),true);}catch{return `<div class="people-count-preview-item"><strong>${e(name.replace('人数',''))}</strong><span class="small muted">请填写有效的当日总人数后查看变化。</span></div>`;}const change=current===null||previous===null?null:current-previous;return `<div class="people-count-preview-item"><strong>${e(name.replace('人数',''))}</strong><span class="small muted">昨日总人数:${previous===null?'未记录':previous+' 人'}</span><span>${change===null?'变化未知:'+peopleCountUnknownReason(peopleCountChangeReason(current,previous)):`${previous} → ${current},${peopleCountDeltaText(change)}`}</span></div>`;}).join('');
if(!peopleEntry||peopleEntry.date!==form.elements.date.value||peopleEntryUser!==(state.user.id||state.user.name)){target.innerHTML='<p class="small muted">正在读取上次记录…</p>';return;}
target.innerHTML=peopleParts().map(([part,name])=>{const field=part+'Count',previous=peopleEntry.previous[field],previousDate=peopleEntry.previousDates[part];let current;try{current=peopleCountInput(form.elements[field].value,peopleCountDisplayName(name),true);}catch{return `<div class="people-count-preview-item"><strong>${e(name.replace('人数',''))}</strong><span class="small muted">请填写有效的当日总人数后查看变化。</span></div>`;}const change=current===null||previous===null?null:current-previous;return `<div class="people-count-preview-item"><strong>${e(name.replace('人数',''))}</strong><span class="small muted">${previousDate?'上次记录('+e(previousDate)+')总人数:'+previous+' 人':'暂无上次记录'}</span><span>${change===null?(current!==null?'首次记录(暂无上次记录)':'变化未知:'+peopleCountUnknownReason(peopleCountChangeReason(current,previous))):`较上次记录 ${previous} → ${current},${peopleCountDeltaText(change)}`}</span></div>`;}).join('');
}
function peopleCountInput(value,name,optional=false){
if(optional&&(value===null||typeof value==='string'&&!value.trim()))return null;
@@ -617,7 +678,7 @@ function invalidatePeopleEntry(){++peopleRequest;peopleEntry=null;peopleEntryUse
async function showPeopleCountForm(date=state.today,message=''){
invalidatePeopleEntry();let dialog=$('#people-count-dialog');
if(!dialog){dialog=document.createElement('dialog');dialog.id='people-count-dialog';dialog.setAttribute('aria-labelledby','people-count-title');dialog.addEventListener('cancel',invalidatePeopleEntry);document.body.append(dialog);}
dialog.innerHTML=`<button class="dialog-close" data-action="close-people-count" aria-label="关闭人数记录">×</button><h2 id="people-count-title">记录当日总人数</h2><form id="people-count-form"><div class="grid two">${field('日期','date',date,'date',`id="people-count-date" required max="${e(state.today)}"`)}${peopleParts().map(([part,label])=>field(peopleCountDisplayName(label),part+'Count','','number','min="0" max="1000000" step="1" placeholder="未记录" disabled')).join('')}</div><div id="people-count-preview" class="people-count-preview" aria-live="polite"></div><p class="small muted">填当天总人数,例:昨天100、今天108,自动显示新增8人。同一天再次保存会替换当天总数。</p><p id="people-count-status" class="small muted" aria-live="polite">正在读取…</p><div id="people-count-error" aria-live="polite"></div><div class="form-actions"><span class="small muted">各自独立记录。留空为未记录,填0为已记录0人。</span><div class="actions">${button('取消','close-people-count','quiet')}<button class="primary" type="submit" disabled>保存人数</button></div></div></form>`;
dialog.innerHTML=`<button class="dialog-close" data-action="close-people-count" aria-label="关闭人数记录">×</button><h2 id="people-count-title">记录当日总人数</h2><form id="people-count-form"><div class="grid two">${field('日期','date',date,'date',`id="people-count-date" required max="${e(state.today)}"`)}${peopleParts().map(([part,label])=>field(peopleCountDisplayName(label),part+'Count','','number','min="0" max="1000000" step="1" placeholder="未记录" disabled')).join('')}</div><div id="people-count-preview" class="people-count-preview" aria-live="polite"></div><p class="small muted">填当天总人数,例:上次记录100、今天108,自动显示新增8人。没营业或漏录的日期自动跳过。同一天再次保存会替换当天总数。</p><p id="people-count-status" class="small muted" aria-live="polite">正在读取…</p><div id="people-count-error" aria-live="polite"></div><div class="form-actions"><span class="small muted">各自独立记录。留空为未记录,填0为已记录0人。</span><div class="actions">${button('取消','close-people-count','quiet')}<button class="primary" type="submit" disabled>保存人数</button></div></div></form>`;
if(!dialog.open)dialog.showModal();await loadPeopleCount(message);
}
async function loadPeopleCount(message=''){
@@ -634,7 +695,7 @@ async function loadPeopleCount(message=''){
peopleEntry=entry;peopleEntryUser=user;
for(const name of names){form.elements[name].value=entry[name]===null?'':entry[name];form.elements[name].disabled=false;}
save.disabled=false;syncPeopleCountPreview();
status.textContent=message||'填写当日总人数后保存;较昨日变化会自动计算。';
status.textContent=message||'填写当日总人数后保存;较上次记录变化会自动计算。';
}catch(err){if(request!==peopleRequest||!dialog.open||form!==$('#people-count-form'))return;status.textContent='尚未取得人数记录';$('#people-count-error').innerHTML=`<div class="error">${e(err.name==='AbortError'?'读取超时,请重新读取。':err.message)} ${button('重新读取','people-count-retry')}</div>`;}
}
async function showSavedPeopleCount(date){
@@ -644,20 +705,24 @@ function closePeopleCountHistory(){++peopleHistoryRequest;$('#people-count-histo
async function openPeopleCountHistory(){
let dialog=$('#people-count-history-dialog');peopleHistoryToday=state.today;
if(!dialog){dialog=document.createElement('dialog');dialog.id='people-count-history-dialog';dialog.setAttribute('aria-labelledby','people-count-history-title');dialog.addEventListener('cancel',()=>{++peopleHistoryRequest;});dialog.addEventListener('close',()=>{++peopleHistoryRequest;});document.body.append(dialog);}
dialog.innerHTML=`<button class="dialog-close" data-action="close-people-history" aria-label="关闭每日人数">×</button><h2 id="people-count-history-title">每日人数</h2><p class="small muted">按日期查看当日总人数和较昨日变化;昨天未记录时变化未知,不按0计算。每次最多查看366天。</p><form id="people-count-history-form" class="people-history-filters">${field('开始日期','from',state.today.slice(0,7)+'-01','date',`required min="2000-01-01" max="${e(state.today)}"`)}${field('结束日期','date',state.today,'date',`required min="2000-01-01" max="${e(state.today)}"`)}<button type="submit" class="primary">查询</button><div class="actions">${button('本月','people-history-month','', 'data-period="current"')}${button('上月','people-history-month','', 'data-period="previous"')}</div></form><div id="people-count-history-content" aria-live="polite"></div>`;
dialog.innerHTML=`<button class="dialog-close" data-action="close-people-history" aria-label="关闭每日人数">×</button><h2 id="people-count-history-title">每日人数</h2><p class="small muted">按日期查看当日总人数和较上次记录变化;每位助理分别跳过未记录日,0为有效记录。每次最多查看366天。</p><form id="people-count-history-form" class="people-history-filters">${field('开始日期','from',state.today.slice(0,7)+'-01','date',`required min="2000-01-01" max="${e(state.today)}"`)}${field('结束日期','date',state.today,'date',`required min="2000-01-01" max="${e(state.today)}"`)}<button type="submit" class="primary">查询</button><div class="actions">${button('本月','people-history-month','', 'data-period="current"')}${button('上月','people-history-month','', 'data-period="previous"')}</div></form><div id="people-count-history-content" aria-live="polite"></div>`;
if(!dialog.open)dialog.showModal();await loadPeopleCountHistory(true);
}
function peopleCountHistoryHTML(result){
const parts=peopleParts(),rows=result.rows.filter(row=>parts.some(([part])=>row[part+'Count']!==null&&row[part+'Count']!==undefined));
const number=value=>value==null?'<span class="muted">未记录</span>':value.toLocaleString('zh-CN')+' 人';
const change=(value,reason)=>value===null?`<span class="muted">未知</span><div class="small muted">${e(peopleCountUnknownReason(reason))}</div>`:e(peopleCountDeltaText(value));
return `<p class="small muted">${e(result.from)} 至 ${e(result.date)} · 已记录 ${rows.length} 天。期初基准:${e(result.baselineDate)}。</p><div class="table-wrap"><table class="people-history-table" aria-label="助理每日总人数与较昨日变化"><thead><tr><th rowspan="2">日期</th>${parts.map(([,label])=>`<th colspan="2" class="number">${e(label.replace('人数',''))}</th>`).join('')}</tr><tr>${parts.map(()=>'<th class="number">当日总人数</th><th class="number">较昨日变化</th>').join('')}</tr></thead><tbody>${rows.length?rows.map(row=>`<tr><td>${e(row.date)}</td>${parts.map(([part])=>`<td class="number">${number(row[part+'Count'])}</td><td class="number">${change(row[part+'Change'],row[part+'ChangeReason'])}</td>`).join('')}</tr>`).join(''):`<tr><td colspan="${1+parts.length*2}" class="muted">所选日期暂无人数记录</td></tr>`}</tbody><tfoot><tr><th>期末/本期变化</th>${parts.map(([key])=>{const value=result.summary[key];return `<td colspan="2" class="number"><div>结束日总人数 <strong>${number(value.endTotal)}</strong></div><div class="small">本期净增 ${value.netChange===null?'未知':e(peopleCountSignedText(value.netChange))}</div>${value.netChange===null?`<div class="small muted">${e(peopleCountUnknownReason(value.netChangeReason,true))}</div>`:''}</td>`;}).join('')}</tr></tfoot></table></div><p class="small muted">本期净增=${e(result.date)}总人数-${e(result.baselineDate)}总人数;每日总人数不累加。</p>`;
const change=(row,part)=>{const value=row[part+'Change'],reason=row[part+'ChangeReason'],previousDate=row.previousDates?.[part];return (value===null?`<span class="muted">${row[part+'Count']!==null&&reason==='missing-previous'?'首次记录':'未知'}</span><div class="small muted">${e(peopleCountUnknownReason(reason))}</div>`:e(peopleCountDeltaText(value)))+(previousDate?`<div class="small muted">上次记录:${e(previousDate)}</div>`:'');};
return `<p class="small muted">${e(result.from)} 至 ${e(result.date)} · 已记录 ${rows.length} 天。</p><div class="table-wrap"><table class="people-history-table" aria-label="助理每日总人数与较上次记录变化"><thead><tr><th rowspan="2">日期</th>${parts.map(([,label])=>`<th colspan="2" class="number">${e(label.replace('人数',''))}</th>`).join('')}</tr><tr>${parts.map(()=>'<th class="number">当日总人数</th><th class="number">较上次记录变化</th>').join('')}</tr></thead><tbody>${rows.length?rows.map(row=>`<tr><td>${e(row.date)}</td>${parts.map(([part])=>`<td class="number">${number(row[part+'Count'])}</td><td class="number">${change(row,part)}</td>`).join('')}</tr>`).join(''):`<tr><td colspan="${1+parts.length*2}" class="muted">所选日期暂无人数记录</td></tr>`}</tbody><tfoot><tr><th>期末/本期变化</th>${parts.map(([key])=>{const value=result.summary[key];return `<td colspan="2" class="number"><div>结束日总人数 <strong>${number(value.endTotal)}</strong></div><div class="small">本期净增 ${value.netChange===null?'未知':e(peopleCountSignedText(value.netChange))}</div>${value.baselineDate?`<div class="small muted">期初基准:${e(value.baselineDate)}</div>`:''}${value.netChange===null?`<div class="small muted">${e(peopleCountUnknownReason(value.netChangeReason,true))}</div>`:''}</td>`;}).join('')}</tr></tfoot></table></div><p class="small muted">本期净增=${e(result.date)}总人数-各自开始日前最近记录总人数;结束日未记录则未知,每日总人数不累加。</p>`;
}
function validatePeopleCountHistory(result,range){
if(!result||result.mode!=='daily-total'||!validOrderDate(result.today)||!validOrderDate(result.from)||!validOrderDate(result.date)||result.date>result.today||result.from>result.date||result.baselineDate!==peopleCountPreviousDate(result.from)||range&&(result.from!==range.from||result.date!==range.date)||!Array.isArray(result.rows))throw new Error('每日人数资料未完整返回,请重新查询。');
const first=Date.parse(result.from+'T00:00:00Z'),days=(Date.parse(result.date+'T00:00:00Z')-first)/86400000+1;
const names=peopleParts().map(([part])=>part+'Count');
if(days>366||result.rows.length!==days||!result.rows.every((row,i)=>validPeopleCountDaily(row,new Date(first+i*86400000).toISOString().slice(0,10),names)&&names.every(name=>!i||row.previous[name]===result.rows[i-1][name]))||!peopleParts().every(([key])=>{const value=result.summary?.[key],end=result.rows.at(-1)[key+'Count'],baseline=result.rows[0].previous[key+'Count'];return value?.endTotal===end&&value?.baselineTotal===baseline&&value?.netChange===(end===null||baseline===null?null:end-baseline)&&value?.netChangeReason===peopleCountChangeReason(end,baseline)&&value.recordedDays===result.rows.filter(row=>row[key+'Count']!==null).length;}))throw new Error('每日总人数或变化资料不完整,请重新查询。');
const parts=peopleParts(),names=parts.map(([part])=>part+'Count'),previous={};
if(days>366||result.rows.length!==days||!result.rows.every((row,i)=>{
if(!validPeopleCountDaily(row,new Date(first+i*86400000).toISOString().slice(0,10),names))return false;
for(const [key] of parts){const name=key+'Count';if(i&&(row.previous[name]!==previous[key].total||row.previousDates[key]!==previous[key].date))return false;previous[key]=row[name]===null?{total:row.previous[name],date:row.previousDates[key]}:{total:row[name],date:row.date};}
return true;
})||!parts.every(([key])=>{const value=result.summary?.[key],end=result.rows.at(-1)[key+'Count'],baseline=result.rows[0].previous[key+'Count'],baselineDate=result.rows[0].previousDates[key];return value?.total===end&&value?.endTotal===end&&value?.baselineTotal===baseline&&value?.baselineDate===baselineDate&&value?.netChange===(end===null||baseline===null?null:end-baseline)&&value?.netChangeReason===peopleCountChangeReason(end,baseline)&&value.recordedDays===result.rows.filter(row=>row[key+'Count']!==null).length;}))throw new Error('每日总人数或变化资料不完整,请重新查询。');
return result;
}
async function loadPeopleCountHistory(defaults=false){