From 914a2b72875e6aa754f8698eb080fc0d7963ab2d Mon Sep 17 00:00:00 2001 From: summer Date: Thu, 29 Oct 2026 00:27:36 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E5=96=84=E6=96=AD=E8=BF=9E=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E6=81=A2=E5=A4=8D=E5=B9=B6=E6=8C=89=E4=B8=8A=E6=AC=A1?= =?UTF-8?q?=E6=9C=89=E6=95=88=E8=AE=B0=E5=BD=95=E8=AE=A1=E7=AE=97=E4=BA=BA?= =?UTF-8?q?=E6=95=B0=E5=A2=9E=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 新账系统/ledger.js | 35 +++++--- 新账系统/public/app.js | 111 ++++++++++++++++++++------ 新账系统/public/index.html | 1 + 新账系统/server.js | 13 ++- 新账系统/test/people-count-ui.test.js | 55 +++++++++---- 新账系统/test/people-count.test.js | 78 +++++++++++++++--- 新账系统/test/request-retry.test.js | 76 ++++++++++++++++++ 新账系统/test/team-ui.test.js | 2 +- 新账系统/三人使用说明.md | 4 +- 新账系统/使用说明.md | 10 ++- 新账系统/维护与部署.md | 18 ++++- 11 files changed, 334 insertions(+), 69 deletions(-) create mode 100644 新账系统/test/request-retry.test.js diff --git a/新账系统/ledger.js b/新账系统/ledger.js index b7a1d5a..0f97eb0 100644 --- a/新账系统/ledger.js +++ b/新账系统/ledger.js @@ -57,16 +57,27 @@ const PEOPLE_PARTS=[['assistant1','assistant1_count'],['assistant2','assistant2_ const previousPeopleDate=date=>new Date(Date.parse(date+'T00:00:00Z')-86400000).toISOString().slice(0,10); function peopleParts(ledger,actor=ledger.actor){return ledger.teamMode&&actor?.role==='assistant'?PEOPLE_PARTS.filter(([key])=>key===(ledger.memberFor(actor)==='assistant'?'assistant1':'assistant2')):PEOPLE_PARTS;} function peopleDifference(current,previous){return {change:current===null||previous===null?null:current-previous,reason:current===null?(previous===null?'missing-both':'missing-current'):previous===null?'missing-previous':null};} +function peopleSaved(ledger,from,date,parts){ + // 一次读取范围及每位可见成员的最近有效基准,跨空日、跨月不逐日查询。 + const columns=parts.map(([,column])=>column),baselines=columns.map(column=>`date=(SELECT MAX(date) FROM daily_people_counts WHERE date=? AND date<=?) OR ${baselines.join(' OR ')} ORDER BY date`,from,date,...columns.map(()=>from)).map(row=>[row.date,row])); +} +function peopleBaselines(saved,from,parts){ + const previous=new Map(); + for(const record of saved.values())if(record.daterow.date>=from&&row.date<=date&&row[column]!==null).length}; + const endTotal=end?.[column]??null,baseline=previous.get(key),baselineTotal=baseline?.total??null,difference=peopleDifference(endTotal,baselineTotal); + result[key]={total:endTotal,endTotal,baselineTotal,baselineDate:baseline?.date??null,netChange:difference.change,netChangeReason:difference.reason,recordedDays:[...saved.values()].filter(row=>row.date>=from&&row.date<=date&&row[column]!==null).length}; } return result; } @@ -790,24 +801,24 @@ class Ledger { return {after_sale_id:id,kind:'afterSale'}; } peopleCount(date,actor=this.actor){ - day(date);const previousDate=previousPeopleDate(date),saved=new Map(this.rows('SELECT date,count,assistant1_count,assistant2_count,revision FROM daily_people_counts WHERE date IN (?,?)',date,previousDate).map(row=>[row.date,row])),record=saved.get(date); - const result={...peopleDay(date,record,saved.get(previousDate),peopleParts(this,actor)),revision:record?.revision??0}; + day(date);const parts=peopleParts(this,actor),saved=peopleSaved(this,date,date,parts),record=saved.get(date); + const result={...peopleDay(date,record,peopleBaselines(saved,date,parts),parts),revision:record?.revision??0}; if(!this.teamMode)result.count=record?.count??null;return result; } peopleCountSummary(date,from=date){ day(date);day(from);if(from>date)fail('开始日期不能晚于结束日期'); - const baselineDate=previousPeopleDate(from),saved=new Map(this.rows('SELECT date,count,assistant1_count,assistant2_count FROM daily_people_counts WHERE date>=? AND date<=? ORDER BY date',baselineDate,date).map(row=>[row.date,row])); - const result={from,date,baselineDate,mode:'daily-total',...peoplePeriod(date,from,saved,peopleParts(this))}; + const parts=peopleParts(this),baselineDate=previousPeopleDate(from),saved=peopleSaved(this,from,date,parts); + const result={from,date,baselineDate,mode:'daily-total',...peoplePeriod(date,from,saved,parts)}; if(!this.teamMode){result.total=saved.get(date)?.count??null;result.recordedDays=[...saved.values()].filter(row=>row.date>=from).length;}return result; } peopleCountHistory(query={}){ const current=today(),from=day(query.from??current.slice(0,7)+'-01'),date=day(query.date??current); const first=Date.parse(from+'T00:00:00Z'),last=Date.parse(date+'T00:00:00Z'),days=(last-first)/86400000+1; if(from>date)fail('开始日期不能晚于结束日期');if(days>366)fail('每次最多查看366天,请缩小日期范围'); - const baselineDate=previousPeopleDate(from),saved=new Map(this.rows('SELECT date,assistant1_count,assistant2_count FROM daily_people_counts WHERE date>=? AND date<=? ORDER BY date',baselineDate,date).map(row=>[row.date,row])); - const rows=[],parts=peopleParts(this); + const parts=peopleParts(this),baselineDate=previousPeopleDate(from),saved=peopleSaved(this,from,date,parts),previous=peopleBaselines(saved,from,parts),rows=[]; for(let i=0;i`

记录当日总人数

${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('')}

填当天总人数,例:昨天100、今天108,自动显示新增8人。同一天再次保存会替换当天总数。

正在读取…

各自独立记录。留空为未记录,填0为已记录0人。
${button('取消','close-people-count','quiet')}
`; + dialog.innerHTML=`

记录当日总人数

${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('')}

填当天总人数,例:上次记录100、今天108,自动显示新增8人。没营业或漏录的日期自动跳过。同一天再次保存会替换当天总数。

正在读取…

各自独立记录。留空为未记录,填0为已记录0人。
${button('取消','close-people-count','quiet')}
`; 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=`
${e(err.name==='AbortError'?'读取超时,请重新读取。':err.message)} ${button('重新读取','people-count-retry')}
`;} } 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=`

每日人数

按日期查看当日总人数和较昨日变化;昨天未记录时变化未知,不按0计算。每次最多查看366天。

${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('本月','people-history-month','', 'data-period="current"')}${button('上月','people-history-month','', 'data-period="previous"')}
`; + dialog.innerHTML=`

每日人数

按日期查看当日总人数和较上次记录变化;每位助理分别跳过未记录日,0为有效记录。每次最多查看366天。

${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('本月','people-history-month','', 'data-period="current"')}${button('上月','people-history-month','', 'data-period="previous"')}
`; 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?'未记录':value.toLocaleString('zh-CN')+' 人'; - const change=(value,reason)=>value===null?`未知
${e(peopleCountUnknownReason(reason))}
`:e(peopleCountDeltaText(value)); - return `

${e(result.from)} 至 ${e(result.date)} · 已记录 ${rows.length} 天。期初基准:${e(result.baselineDate)}。

${parts.map(([,label])=>``).join('')}${parts.map(()=>'').join('')}${rows.length?rows.map(row=>`${parts.map(([part])=>``).join('')}`).join(''):``}${parts.map(([key])=>{const value=result.summary[key];return ``;}).join('')}
日期${e(label.replace('人数',''))}
当日总人数较昨日变化
${e(row.date)}${number(row[part+'Count'])}${change(row[part+'Change'],row[part+'ChangeReason'])}
所选日期暂无人数记录
期末/本期变化
结束日总人数 ${number(value.endTotal)}
本期净增 ${value.netChange===null?'未知':e(peopleCountSignedText(value.netChange))}
${value.netChange===null?`
${e(peopleCountUnknownReason(value.netChangeReason,true))}
`:''}

本期净增=${e(result.date)}总人数-${e(result.baselineDate)}总人数;每日总人数不累加。

`; + const change=(row,part)=>{const value=row[part+'Change'],reason=row[part+'ChangeReason'],previousDate=row.previousDates?.[part];return (value===null?`${row[part+'Count']!==null&&reason==='missing-previous'?'首次记录':'未知'}
${e(peopleCountUnknownReason(reason))}
`:e(peopleCountDeltaText(value)))+(previousDate?`
上次记录:${e(previousDate)}
`:'');}; + return `

${e(result.from)} 至 ${e(result.date)} · 已记录 ${rows.length} 天。

${parts.map(([,label])=>``).join('')}${parts.map(()=>'').join('')}${rows.length?rows.map(row=>`${parts.map(([part])=>``).join('')}`).join(''):``}${parts.map(([key])=>{const value=result.summary[key];return ``;}).join('')}
日期${e(label.replace('人数',''))}
当日总人数较上次记录变化
${e(row.date)}${number(row[part+'Count'])}${change(row,part)}
所选日期暂无人数记录
期末/本期变化
结束日总人数 ${number(value.endTotal)}
本期净增 ${value.netChange===null?'未知':e(peopleCountSignedText(value.netChange))}
${value.baselineDate?`
期初基准:${e(value.baselineDate)}
`:''}${value.netChange===null?`
${e(peopleCountUnknownReason(value.netChangeReason,true))}
`:''}

本期净增=${e(result.date)}总人数-各自开始日前最近记录总人数;结束日未记录则未知,每日总人数不累加。

`; } 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){ diff --git a/新账系统/public/index.html b/新账系统/public/index.html index 981674e..301e35d 100644 --- a/新账系统/public/index.html +++ b/新账系统/public/index.html @@ -2,6 +2,7 @@ 麦麦珠宝 · 新账系统
diff --git a/新账系统/server.js b/新账系统/server.js index d6730ab..307d56d 100644 --- a/新账系统/server.js +++ b/新账系统/server.js @@ -41,6 +41,15 @@ function peopleCountResponse(ledger,result,actor){ if(!result.previous||typeof result.previous!=='object'||Array.isArray(result.previous))unavailable();filtered.previous={}; for(const part of parts)if(Object.hasOwn(result.previous,part+'Count')){const value=result.previous[part+'Count'];if(!count(value))unavailable();filtered.previous[part+'Count']=value;} } + if(Object.hasOwn(result,'previousDates')){ + if(!result.previousDates||typeof result.previousDates!=='object'||Array.isArray(result.previousDates))unavailable();filtered.previousDates={}; + for(const part of parts)if(Object.hasOwn(result.previousDates,part)){ + const value=result.previousDates[part]; + if(value!==null&&(typeof value!=='string'||!/^\d{4}-\d{2}-\d{2}$/.test(value)||!Number.isFinite(Date.parse(value+'T00:00:00Z'))||new Date(value+'T00:00:00Z').toISOString().slice(0,10)!==value||value<'2000-01-01'||value>=result.date))unavailable(); + if(Object.hasOwn(filtered.previous||{},part+'Count')&&((value===null)!==(filtered.previous[part+'Count']===null)))unavailable(); + filtered.previousDates[part]=value; + } + } return filtered; } @@ -106,6 +115,8 @@ function createApp(options={}){ const actor=user(req);const actorLedger=ledger.asActor(actor); if(route.startsWith('/api/')||route.startsWith('/print/')){ if(!actor)fail('请先登录',401); + // 仅校验本次页面的原账号与cookie一致,实际授权仍由登录和成员权限决定。 + if(req.headers['x-ledger-user']!==undefined&&req.headers['x-ledger-user']!==actor.id){const error=new Error('登录账号已在其他页面切换,请刷新后继续;原操作已暂停。');error.status=409;error.code='ACCOUNT_CHANGED';throw error;} if(route==='/api/team-members'&&!isPost)return send(res,200,actorLedger.teamMembers()); if(route==='/api/team-funds'&&!isPost)return send(res,200,actorLedger.teamFunds(Object.fromEntries(url.searchParams),actor)); const memberPasswordMatch=route.match(/^\/api\/team-members\/(owner|assistant|assistant2)\/password$/); @@ -228,7 +239,7 @@ function createApp(options={}){ } const assets={'/':'index.html','/app.js':'app.js','/order-copy.js':'order-copy.js','/order-templates.js':'order-templates.js','/order-templates-ui.js':'order-templates-ui.js','/order-edit-ui.js':'order-edit-ui.js','/order-cancellations-ui.js':'order-cancellations-ui.js','/order-changes-ui.js':'order-changes-ui.js','/order-ownership-ui.js':'order-ownership-ui.js','/daily-funds-ui.js':'daily-funds-ui.js','/team-funds-ui.js':'team-funds-ui.js','/cost-funding-ui.js':'cost-funding-ui.js','/price-locks-ui.js':'price-locks-ui.js','/material-pools-ui.js':'material-pools-ui.js','/recoveries-ui.js':'recoveries-ui.js','/inventory-changes-ui.js':'inventory-changes-ui.js','/credit-card-fees.js':'credit-card-fees.js','/calculations.js':'calculations.js','/fee-estimates.js':'fee-estimates.js','/app.css':'app.css','/print.js':'print.js'};const file=assets[route];if(!file||isPost)fail('地址不存在',404); send(res,200,fs.readFileSync(path.join(__dirname,'public',file)),file.endsWith('.js')?'application/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8'); - }catch(e){if(!res.headersSent)send(res,e.status||400,{error:e.status||e.message?.startsWith('打印')?e.message:(e.code?.startsWith('SQLITE')?'保存失败,请保留操作内容并联系维护者':e.message||'操作失败')});else res.end();} + }catch(e){if(!res.headersSent)send(res,e.status||400,{error:e.status||e.message?.startsWith('打印')?e.message:(e.code?.startsWith('SQLITE')?'保存失败,请保留操作内容并联系维护者':e.message||'操作失败'),...(e.code==='ACCOUNT_CHANGED'?{code:e.code}:{})});else res.end();} }); const timers=[]; function startTimers(){if(timers.length)return false;timers.push(setInterval(()=>sync.tick(),60000));timers.push(setInterval(()=>doBackup().catch(()=>{}),6*60*60*1000));automaticSnapshots.start();doBackup().catch(()=>{});for(const t of timers)t.unref();return true;} diff --git a/新账系统/test/people-count-ui.test.js b/新账系统/test/people-count-ui.test.js index 12fbda0..e74d08b 100644 --- a/新账系统/test/people-count-ui.test.js +++ b/新账系统/test/people-count-ui.test.js @@ -3,8 +3,8 @@ const {test}=require('node:test'),assert=require('node:assert/strict'),fs=requir const D='2026-10-22',NEXT='2026-10-23',user={id:'people-ui-user',name:'合成麦麦',role:'owner'}; const previousDate=date=>new Date(Date.parse(date+'T00:00:00Z')-86400000).toISOString().slice(0,10); const reason=(current,previous)=>current===null?(previous===null?'missing-both':'missing-current'):previous===null?'missing-previous':null; -const period=(endTotal,baselineTotal,recordedDays=1)=>({total:endTotal,endTotal,baselineTotal,netChange:endTotal===null||baselineTotal===null?null:endTotal-baselineTotal,netChangeReason:reason(endTotal,baselineTotal),recordedDays}); -const record=(date,count,revision,assistant1Count=null,assistant2Count=null,previous1=null,previous2=null)=>({date,count,assistant1Count,assistant2Count,revision,previousDate:previousDate(date),previous:{assistant1Count:previous1,assistant2Count:previous2},assistant1Change:assistant1Count===null||previous1===null?null:assistant1Count-previous1,assistant1ChangeReason:reason(assistant1Count,previous1),assistant2Change:assistant2Count===null||previous2===null?null:assistant2Count-previous2,assistant2ChangeReason:reason(assistant2Count,previous2),mode:'daily-total'}); +const period=(endTotal,baselineTotal,recordedDays=1,baselineDate=null)=>({total:endTotal,endTotal,baselineTotal,baselineDate,netChange:endTotal===null||baselineTotal===null?null:endTotal-baselineTotal,netChangeReason:reason(endTotal,baselineTotal),recordedDays}); +const record=(date,count,revision,assistant1Count=null,assistant2Count=null,previous1=null,previous2=null,previousDate1=previous1===null?null:previousDate(date),previousDate2=previous2===null?null:previousDate(date))=>({date,count,assistant1Count,assistant2Count,revision,previousDate:previousDate(date),previous:{assistant1Count:previous1,assistant2Count:previous2},previousDates:{assistant1:previousDate1,assistant2:previousDate2},assistant1Change:assistant1Count===null||previous1===null?null:assistant1Count-previous1,assistant1ChangeReason:reason(assistant1Count,previous1),assistant2Change:assistant2Count===null||previous2===null?null:assistant2Count-previous2,assistant2ChangeReason:reason(assistant2Count,previous2),mode:'daily-total'}); function harness(){ const nodes=new Map(),handlers={},saved=new Map(),calls=[],toasts=[],save={disabled:true}; const form={id:'people-count-form',dataset:{},elements:Object.fromEntries(['date','assistant1Count','assistant2Count'].map(name=>[name,{value:name==='date'?D:'残留值',disabled:false}])),querySelector:()=>save}; @@ -24,27 +24,43 @@ function historyHarness(){ } function history(from,date){ const days=(Date.parse(date)-Date.parse(from))/86400000+1,rows=[]; - for(let i=0;i{ const h=harness();await h.run('showPeopleCountForm()');const html=h.dialog.innerHTML; assert.doesNotMatch(html,/name="count"/);assert.match(html,/助理1当日总人数/);assert.match(html,/助理2当日总人数/);assert.match(html,/同一天再次保存会替换当天总数/);for(const name of ['assistant1Count','assistant2Count'])assert.doesNotMatch(html,new RegExp('name="'+name+'"[^>]*required')); - h.context.__summary={from:D,date:NEXT,baselineDate:previousDate(D),total:999,recordedDays:2,assistant1:{...period(0,0,1),total:999},assistant2:period(9,5,2)}; + h.context.__summary={from:D,date:NEXT,baselineDate:previousDate(D),total:999,recordedDays:2,assistant1:{...period(0,0,1,previousDate(D)),total:999},assistant2:period(9,5,2,previousDate(D))}; const lines=h.json('peopleCountReportLines(__summary)');assert.match(lines[0],/助理1结束日总人数:0 人(已记录) · 本期净增 0 人/);assert.match(lines[1],/助理2结束日总人数:9 人(已记录) · 本期净增 \+4 人/);assert.ok(lines.every(line=>line.includes(previousDate(D))&&line.includes(NEXT))); const combined=h.run('peopleCountHTML(__summary)');assert.equal((combined.match(/class="people-count-item"/g)||[]).length,2);assert.match(combined,/结束日总人数/);assert.doesNotMatch(combined,/人数合计|999 人/); - h.context.__summary={from:D,date:D,assistant1:period(null,10,1),assistant2:period(0,2,1)};assert.match(h.run("peopleCountText(__summary,'assistant1')"),/当日未记录.*变化未知/);assert.match(h.run("peopleCountText(__summary,'assistant2')"),/0 人(已记录).*减少 2 人/); + h.context.__summary={from:D,date:D,assistant1:period(null,10,1,previousDate(D)),assistant2:period(0,2,1,previousDate(D))};assert.match(h.run("peopleCountText(__summary,'assistant1')"),/当日未记录.*变化未知/);assert.match(h.run("peopleCountText(__summary,'assistant2')"),/0 人(已记录).*减少 2 人/); }); -test('当日输入与昨日实时计算新增减少,清空或缺昨日不按0,已存Change不固定预览',async()=>{ - const h=harness();h.context.__response=record(D,999,2,108,null,100,0);await h.run('loadPeopleCount()');const preview=h.nodes.get('#people-count-preview');assert.match(preview.innerHTML,/昨日总人数:100 人/);assert.match(preview.innerHTML,/100 → 108,新增 8 人/); +test('当日输入与上次记录实时计算新增减少,清空不按0,首次记录不把总人数当新增',async()=>{ + const h=harness();h.context.__response=record(D,999,2,108,null,100,0);await h.run('loadPeopleCount()');const preview=h.nodes.get('#people-count-preview');assert.match(preview.innerHTML,/上次记录(2026-10-21)总人数:100 人/);assert.match(preview.innerHTML,/100 → 108,新增 8 人/); h.form.elements.assistant1Count.value='98';h.run('syncPeopleCountPreview()');assert.match(preview.innerHTML,/100 → 98,减少 2 人/);h.form.elements.assistant1Count.value='';h.form.elements.assistant2Count.value='0';h.run('syncPeopleCountPreview()');assert.match(preview.innerHTML,/变化未知:当日未记录/);assert.match(preview.innerHTML,/0 → 0,无变化/);assert.doesNotMatch(preview.innerHTML,/100 → 0/); - h.context.__response=record(D,999,3,0,5,null,null);await h.run('loadPeopleCount()');assert.match(preview.innerHTML,/昨日总人数:未记录/);assert.match(preview.innerHTML,/变化未知:昨日未记录/);assert.doesNotMatch(preview.innerHTML,/999|新增 5 人/); + h.context.__response=record(D,999,3,0,5,null,null);await h.run('loadPeopleCount()');assert.match(preview.innerHTML,/暂无上次记录/);assert.match(preview.innerHTML,/首次记录(暂无上次记录)/);assert.doesNotMatch(preview.innerHTML,/999|新增 5 人/); +}); +test('10月28日即时预览、摘要及下载均显示较10月26日新增8/27,历史不展示空日',async()=>{ + const h=historyHarness(),date='2026-10-28',baseline='2026-10-26';h.run(`state.today='${date}';`);h.form.elements.date.value=date; + h.context.__response=record(date,999,1,8212,160,8204,133,baseline,baseline);await h.run('loadPeopleCount()');const preview=h.nodes.get('#people-count-preview').innerHTML; + assert.match(preview,/上次记录(2026-10-26)总人数:8204 人/);assert.match(preview,/上次记录(2026-10-26)总人数:133 人/);assert.match(preview,/新增 8 人/);assert.match(preview,/新增 27 人/);assert.doesNotMatch(preview,/昨日|999/); + h.context.__summary={from:date,date,assistant1:period(8212,8204,1,baseline),assistant2:period(160,133,1,baseline)};const summary=h.run('peopleCountHTML(__summary)'),download=h.json('peopleCountReportLines(__summary)').join('\n'); + for(const text of [summary,download]){assert.match(text,/较上次记录(2026-10-26)新增 8 人/);assert.match(text,/较上次记录(2026-10-26)新增 27 人/);assert.doesNotMatch(text,/昨日|2026-10-27/);} + const from='2026-10-27';h.context.__history={from,date,today:date,baselineDate:baseline,mode:'daily-total',rows:[record(from,0,0,null,null,8204,133,baseline,baseline),record(date,0,1,8212,160,8204,133,baseline,baseline)],summary:{assistant1:period(8212,8204,1,baseline),assistant2:period(160,133,1,baseline)}}; + assert.doesNotThrow(()=>h.run('validatePeopleCountHistory(__history)'));const html=h.run('peopleCountHistoryHTML(__history)');assert.match(html,/已记录 1 天/);assert.match(html,/上次记录:2026-10-26/);assert.match(html,/新增 27 人/);assert.doesNotMatch(html,/2026-10-27<\/td>/); +}); +test('人数读取校验同时要求真实日期与基数,拒绝丢字段、未来日期和不配对的0',async()=>{ + const h=harness(),good=record(D,0,1,108,7,100,0,'2026-09-30','2026-09-28');h.context.__response=good;await h.run('loadPeopleCount()');assert.equal(h.save.disabled,false); + for(const mutate of [entry=>delete entry.previousDates,entry=>delete entry.previousDates.assistant1,entry=>entry.previousDates.assistant1=D,entry=>entry.previousDates.assistant1='2026-02-30',entry=>entry.previousDates.assistant2=null,entry=>entry.previous.assistant2Count=null,entry=>entry.assistant1Change=9]){ + const bad=JSON.parse(JSON.stringify(good));mutate(bad);h.context.__response=bad;await h.run('loadPeopleCount()');assert.equal(h.save.disabled,true);assert.match(h.nodes.get('#people-count-error').innerHTML,/未完整返回/); + } }); test('切日期读取时两项清空禁用,晚到响应不覆盖新日期或新用户,缺助理字段不能保存',async()=>{ const h=harness(),pending=[];h.context.__pending=pending;h.run('api=function(){return new Promise(resolve=>__pending.push(resolve));};'); const first=h.run('loadPeopleCount()');for(const field of ['assistant1Count','assistant2Count']){assert.equal(h.form.elements[field].value,'');assert.equal(h.form.elements[field].disabled,true);}assert.equal(h.save.disabled,true); h.form.elements.date.value=NEXT;const second=h.run('loadPeopleCount()');pending[1](record(NEXT,8,2,null,0));await second; - assert.equal(h.form.elements.assistant1Count.value,'');assert.equal(h.form.elements.assistant2Count.value,0);assert.match(h.nodes.get('#people-count-preview').innerHTML,/昨日总人数:未记录/);assert.doesNotMatch(h.nodes.get('#people-count-status').textContent,/8 人/); + assert.equal(h.form.elements.assistant1Count.value,'');assert.equal(h.form.elements.assistant2Count.value,0);assert.match(h.nodes.get('#people-count-preview').innerHTML,/暂无上次记录/);assert.doesNotMatch(h.nodes.get('#people-count-status').textContent,/8 人/); pending[0](record(D,99,3,99,99));await first;assert.equal(h.form.elements.assistant2Count.value,0);assert.equal(h.json('peopleEntry.date'),NEXT); const changedUser=h.run('loadPeopleCount()');h.run("state={...state,user:{id:'another-user'}}");pending[2](record(NEXT,30,4,30,30));await changedUser;assert.equal(h.run('peopleEntry'),null);assert.equal(h.save.disabled,true); h.run('state={...state,user:__user};api=async function(){return {date:state.today,count:1,revision:2};};');await h.run('loadPeopleCount()');assert.equal(h.save.disabled,true);assert.match(h.nodes.get('#people-count-error').innerHTML,/未完整返回/); @@ -66,14 +82,21 @@ test('旧中断请求恢复时省略的助理字段原样省略,不被新页 const button={dataset:{action:'retry'},closest(){return null;}};for(const handler of h.handlers.click)await handler({target:{closest:()=>button}}); assert.equal(h.calls.length,1);assert.equal(JSON.stringify(h.calls[0].data),JSON.stringify(pending.data));assert.equal(h.calls[0].key,pending.key);assert.equal(h.saved.get(h.key),undefined);assert.equal(h.run('__savedDate'),D); }); -test('每日人数显示逐日总数和昨日变化、期末与本期净增,月快捷不改变订单筛选',async()=>{ - const h=historyHarness();h.context.__response=history('2026-10-01',NEXT);h.run("orderBookFilters={mode:'date',date:'2026-10-20',q:'原客户',status:'returned'};");const filters=h.json('orderBookFilters');await h.run('openPeopleCountHistory()');assert.equal(h.calls[0].url,'/api/people-count-history');assert.equal(h.calls[0].data,undefined);assert.match(h.historyDialog.innerHTML,/本月|上月/);assert.doesNotMatch(h.historyDialog.innerHTML,/name="count"|people-count-form/);assert.match(h.historyContent.innerHTML,/助理1/);assert.match(h.historyContent.innerHTML,/助理2/);assert.match(h.historyContent.innerHTML,/当日总人数/);assert.match(h.historyContent.innerHTML,/较昨日变化/);assert.match(h.historyContent.innerHTML,/0 人/);assert.match(h.historyContent.innerHTML,/未记录/);assert.match(h.historyContent.innerHTML,/本期净增 \+3 人/);assert.match(h.historyContent.innerHTML,/已记录 2 天/);assert.equal((h.historyContent.innerHTML.match(/\d{4}-\d{2}-\d{2}<\/td>/g)||[]).length,2);assert.doesNotMatch(h.historyContent.innerHTML,/>合计{ + const h=historyHarness();h.context.__response=history('2026-10-01',NEXT);h.run("orderBookFilters={mode:'date',date:'2026-10-20',q:'原客户',status:'returned'};");const filters=h.json('orderBookFilters');await h.run('openPeopleCountHistory()');assert.equal(h.calls[0].url,'/api/people-count-history');assert.equal(h.calls[0].data,undefined);assert.match(h.historyDialog.innerHTML,/本月|上月/);assert.doesNotMatch(h.historyDialog.innerHTML,/name="count"|people-count-form/);assert.match(h.historyContent.innerHTML,/助理1/);assert.match(h.historyContent.innerHTML,/助理2/);assert.match(h.historyContent.innerHTML,/当日总人数/);assert.match(h.historyContent.innerHTML,/较上次记录变化/);assert.match(h.historyContent.innerHTML,/0 人/);assert.match(h.historyContent.innerHTML,/未记录/);assert.match(h.historyContent.innerHTML,/本期净增 \+3 人/);assert.match(h.historyContent.innerHTML,/已记录 2 天/);assert.equal((h.historyContent.innerHTML.match(/\d{4}-\d{2}-\d{2}<\/td>/g)||[]).length,2);assert.doesNotMatch(h.historyContent.innerHTML,/>合计call.data===undefined)); }); -test('历史按自然昨日处理断档,端点齐全仍可算本期净增,不累加每日变化或总数',()=>{ - const h=historyHarness(),from='2026-10-20',date=D,rows=[record(from,0,0,103,null,100,10),record('2026-10-21',0,0,null,null,103,null),record(date,0,0,108,8,null,null)],result={from,date,today:NEXT,baselineDate:'2026-10-19',mode:'daily-total',rows,summary:{assistant1:period(108,100,2),assistant2:period(8,10,1)}};h.context.__history=result; - assert.doesNotThrow(()=>h.run('validatePeopleCountHistory(__history)'));const html=h.run('peopleCountHistoryHTML(__history)');assert.match(html,/本期净增 \+8 人/);assert.match(html,/本期净增 -2 人/);assert.match(html,/昨日未记录/);assert.match(html,/已记录 2 天/);assert.doesNotMatch(html,/2026-10-21<\/td>|211 人|>合计h.run('validatePeopleCountHistory(__history)'),/不完整/);result.rows[2].assistant1Change=null;result.summary.assistant1.endTotal=null;assert.throws(()=>h.run('validatePeopleCountHistory(__history)'),/不完整/); +test('历史跳过未记录日且显示实际基准日期,不累加每日变化或总数',()=>{ + const h=historyHarness(),from='2026-10-20',date=D,rows=[record(from,0,0,103,null,100,10),record('2026-10-21',0,0,null,null,103,10,from,'2026-10-19'),record(date,0,0,108,8,103,10,from,'2026-10-19')],result={from,date,today:NEXT,baselineDate:'2026-10-19',mode:'daily-total',rows,summary:{assistant1:period(108,100,2,'2026-10-19'),assistant2:period(8,10,1,'2026-10-19')}};h.context.__history=result; + assert.doesNotThrow(()=>h.run('validatePeopleCountHistory(__history)'));const html=h.run('peopleCountHistoryHTML(__history)');assert.match(html,/本期净增 \+8 人/);assert.match(html,/本期净增 -2 人/);assert.match(html,/上次记录:2026-10-20/);assert.match(html,/已记录 2 天/);assert.doesNotMatch(html,/2026-10-21<\/td>|211 人|>合计h.run('validatePeopleCountHistory(__history)'),/不完整/);result.rows[2].assistant1Change=5;result.summary.assistant1.endTotal=null;assert.throws(()=>h.run('validatePeopleCountHistory(__history)'),/不完整/); +}); +test('历史严格校验跨空日每人的人数和日期连续性,范围基准不能换成自然前一天',()=>{ + const h=historyHarness(),good=history('2026-10-20',D);h.context.__history=good;assert.doesNotThrow(()=>h.run('validatePeopleCountHistory(__history)')); + for(const mutate of [result=>result.rows[2].previousDates.assistant1='2026-10-21',result=>result.rows[2].previousDates.assistant2='2026-10-20',result=>{result.rows[2].previous.assistant1Count=null;result.rows[2].previousDates.assistant1=null;result.rows[2].assistant1ChangeReason='missing-both';},result=>result.summary.assistant2.baselineDate='2026-10-18',result=>result.summary.assistant2.baselineTotal=6,result=>result.summary.assistant1.recordedDays=2,result=>result.summary.assistant2.total=null]){ + const bad=JSON.parse(JSON.stringify(good));mutate(bad);h.context.__history=bad;assert.throws(()=>h.run('validatePeopleCountHistory(__history)'),/不完整/); + } + h.context.__history=good;h.run('state.user={...state.user,role:"assistant",member:"assistant2"};');assert.doesNotThrow(()=>h.run('validatePeopleCountHistory(__history)')); }); test('人数历史保留0记录,全空提示无记录,助理仅按本人记录筛日期',()=>{ const h=historyHarness(),result=history('2026-10-20',D);h.context.__history=result; diff --git a/新账系统/test/people-count.test.js b/新账系统/test/people-count.test.js index 44ef6f5..17209d4 100644 --- a/新账系统/test/people-count.test.js +++ b/新账系统/test/people-count.test.js @@ -6,9 +6,9 @@ const owner={id:'people-owner',name:'测试麦麦',role:'owner'},assistant={id:' const D='2026-09-30',D2='2026-10-01',D3='2026-10-02'; const previousDate=date=>new Date(Date.parse(date+'T00:00:00Z')-86400000).toISOString().slice(0,10); const missing=(current,previous)=>current===null?(previous===null?'missing-both':'missing-current'):previous===null?'missing-previous':null; -const entry=(date,count,revision,assistant1Count=null,assistant2Count=null,previous1=null,previous2=null)=>({date,previousDate:previousDate(date),previous:{assistant1Count:previous1,assistant2Count:previous2},mode:'daily-total',assistant1Count,assistant1Change:assistant1Count===null||previous1===null?null:assistant1Count-previous1,assistant1ChangeReason:missing(assistant1Count,previous1),assistant2Count,assistant2Change:assistant2Count===null||previous2===null?null:assistant2Count-previous2,assistant2ChangeReason:missing(assistant2Count,previous2),revision,count}); -const historyEntry=(date,a1=null,a2=null,p1=null,p2=null)=>{const result=entry(date,null,0,a1,a2,p1,p2);delete result.count;delete result.revision;return result;}; -const part=(endTotal=null,recordedDays=0,baselineTotal=null)=>({total:endTotal,endTotal,baselineTotal,netChange:endTotal===null||baselineTotal===null?null:endTotal-baselineTotal,netChangeReason:missing(endTotal,baselineTotal),recordedDays}); +const entry=(date,count,revision,assistant1Count=null,assistant2Count=null,previous1=null,previous2=null,previousDate1=previous1===null?null:previousDate(date),previousDate2=previous2===null?null:previousDate(date))=>({date,previousDate:previousDate(date),previous:{assistant1Count:previous1,assistant2Count:previous2},previousDates:{assistant1:previousDate1,assistant2:previousDate2},mode:'daily-total',assistant1Count,assistant1Change:assistant1Count===null||previous1===null?null:assistant1Count-previous1,assistant1ChangeReason:missing(assistant1Count,previous1),assistant2Count,assistant2Change:assistant2Count===null||previous2===null?null:assistant2Count-previous2,assistant2ChangeReason:missing(assistant2Count,previous2),revision,count}); +const historyEntry=(date,a1=null,a2=null,p1=null,p2=null,pd1=p1===null?null:previousDate(date),pd2=p2===null?null:previousDate(date))=>{const result=entry(date,null,0,a1,a2,p1,p2,pd1,pd2);delete result.count;delete result.revision;return result;}; +const part=(endTotal=null,recordedDays=0,baselineTotal=null,baselineDate=null)=>({total:endTotal,endTotal,baselineTotal,baselineDate,netChange:endTotal===null||baselineTotal===null?null:endTotal-baselineTotal,netChangeReason:missing(endTotal,baselineTotal),recordedDays}); const aggregate=(from,date,total,recordedDays,assistant1=part(),assistant2=part())=>({from,date,baselineDate:previousDate(from),mode:'daily-total',total,recordedDays,assistant1,assistant2}); const wireEntry=(...args)=>{const result=entry(...args);delete result.count;return result;}; const wireAggregate=(...args)=>{const result=aggregate(...args);delete result.total;delete result.recordedDays;return result;}; @@ -78,13 +78,13 @@ test('新请求省略原人数只更新两位助理,新日兼容0且旧日原 assert.deepEqual(f.ledger.peopleCountSummary(D2,D),aggregate(D,D2,47,2,part(0,2),part(null,1))); }); -test('每日人数历史只查一次并逐日补齐闰日与缺录,期末值和自然昨日差独立且不返回旧人数',t=>{ +test('每日人数历史只查一次,跨过闰日缺录找上次记录,保留逐日接口且不返回旧人数',t=>{ const f=fixture(t),from='2024-02-28',date='2024-03-02'; f.write({date:from,count:99,revision:0});f.write({date:'2024-02-29',assistant1Count:0,assistant2Count:3,revision:0});f.write({date,assistant1Count:5,assistant2Count:0,revision:0}); const before=allContents(f.ledger),changes=f.ledger.one('SELECT total_changes() AS count').count,originalRows=f.ledger.rows;let selects=0,result; f.ledger.rows=function(sql,...args){if(sql.includes('FROM daily_people_counts'))selects++;return originalRows.call(this,sql,...args);}; try{result=f.ledger.peopleCountHistory({from,date});}finally{f.ledger.rows=originalRows;} - assert.equal(selects,1);assert.deepEqual(result.rows,[historyEntry(from),historyEntry('2024-02-29',0,3),historyEntry('2024-03-01',null,null,0,3),historyEntry(date,5,0)]); + assert.equal(selects,1);assert.deepEqual(result.rows,[historyEntry(from),historyEntry('2024-02-29',0,3),historyEntry('2024-03-01',null,null,0,3),historyEntry(date,5,0,0,3,'2024-02-29','2024-02-29')]); assert.deepEqual(result.summary,{assistant1:part(5,2),assistant2:part(0,2)});assert.equal(result.today,today());assert.ok(result.rows.every(row=>!Object.hasOwn(row,'count')));assert.ok(!Object.hasOwn(result,'count')); assert.equal(allContents(f.ledger),before);assert.equal(f.ledger.one('SELECT total_changes() AS count').count,changes); }); @@ -111,8 +111,8 @@ test('日月显示期末总人数和端点净增,统计已记录天数且不 for(const query of [{},{q:'不存在'},{status:'after_sale'},{status:'cancelled'}])assert.deepEqual(f.ledger.orderBook({from:D,date:D3,...query}).peopleCount,expected); assert.deepEqual(f.ledger.reportByOrderDate(D3,D).peopleCount,expected); assert.deepEqual(f.ledger.peopleCountSummary(D),aggregate(D,D,3,1,part(0,1),part())); - assert.deepEqual(f.ledger.peopleCountSummary(D2),aggregate(D2,D2,0,1,part(null,0,0),part(5,1))); - assert.deepEqual(f.ledger.peopleCountSummary(D3),aggregate(D3,D3,4,1,part(7,1),part(0,1,5))); + assert.deepEqual(f.ledger.peopleCountSummary(D2),aggregate(D2,D2,0,1,part(null,0,0,D),part(5,1))); + assert.deepEqual(f.ledger.peopleCountSummary(D3),aggregate(D3,D3,4,1,part(7,1,0,D),part(0,1,5,D2))); }); test('日期范围人数独立于订单搜索状态,零人数为已登记,日报透传同一聚合',t=>{ @@ -128,7 +128,7 @@ test('日期范围人数独立于订单搜索状态,零人数为已登记, assert.deepEqual(f.ledger.orderBook({from:D2,date:D3}).peopleCount,aggregate(D2,D3,4,2)); }); -test('100到108到105的日变化为加8和减3,范围净增5;历史修改动态影响当日与次日',t=>{ +test('100到108到105的日变化为加8和减3,范围净增5;历史修改动态影响后续基准',t=>{ const f=fixture(t);f.write({date:D,assistant1Count:100,assistant2Count:0,revision:0}); const input={date:D2,assistant1Count:108,assistant2Count:3,revision:0},key=randomUUID(),first=f.write(input,owner,key);f.write({date:D3,assistant1Count:105,assistant2Count:0,revision:0}); assert.equal(first.previousDate,D);assert.equal(first.previous.assistant1Count,100);assert.equal(first.assistant1Change,8);assert.equal(first.assistant2Change,3); @@ -140,9 +140,9 @@ test('100到108到105的日变化为加8和减3,范围净增5;历史修改 assert.deepEqual(f.write(input,owner,key),first);assert.equal(f.ledger.peopleCount(D2).assistant1Count,110); }); -test('缺自然昨日不跨取上一条,范围两端齐全即使中间缺日仍算净增,缺端点不能用部分增量凑数',t=>{ +test('缺日跳过取上次有效记录,范围保留精确结束日,缺端点不能用部分增量凑数',t=>{ const f=fixture(t);f.write({date:D,assistant1Count:100,assistant2Count:0,revision:0});f.write({date:D3,assistant1Count:105,assistant2Count:0,revision:0}); - const today=f.ledger.peopleCount(D3);assert.equal(today.previousDate,D2);assert.equal(today.previous.assistant1Count,null);assert.equal(today.assistant1Change,null);assert.equal(today.assistant1ChangeReason,'missing-previous'); + const today=f.ledger.peopleCount(D3);assert.equal(today.previousDate,D2);assert.equal(today.previous.assistant1Count,100);assert.equal(today.previousDates.assistant1,D);assert.equal(today.previousDates.assistant2,D);assert.equal(today.assistant1Change,5);assert.equal(today.assistant1ChangeReason,null); const missingDay=f.ledger.peopleCount(D2);assert.equal(missingDay.assistant1Change,null);assert.equal(missingDay.assistant1ChangeReason,'missing-current');assert.equal(missingDay.previous.assistant2Count,0); assert.equal(f.ledger.peopleCountSummary(D3,D2).assistant1.netChange,5);assert.equal(f.ledger.peopleCountSummary(D3,D2).assistant2.netChange,0); const missingBaseline=f.ledger.peopleCountSummary(D3,D);assert.equal(missingBaseline.assistant1.endTotal,105);assert.equal(missingBaseline.assistant1.netChange,null);assert.equal(missingBaseline.assistant1.netChangeReason,'missing-previous'); @@ -150,7 +150,44 @@ test('缺自然昨日不跨取上一条,范围两端齐全即使中间缺日 assert.equal(f.ledger.peopleCount('2026-09-29').assistant1ChangeReason,'missing-both'); }); -test('昨日基数跨月跨年和闰日精确,最早合法日缺基数也正常返回',t=>{ +test('10月26日8204/133到28日8212/160,漏27日仍显示新增8/27,单日摘要与历史一致',t=>{ + const f=fixture(t),beforeDate='2026-10-26',date='2026-10-28'; + f.write({date:beforeDate,count:73,assistant1Count:8204,assistant2Count:133,revision:0}); + f.write({date,count:91,assistant1Count:8212,assistant2Count:160,revision:0}); + const entry=f.ledger.peopleCount(date),summary=f.ledger.peopleCountSummary(date),history=f.ledger.peopleCountHistory({from:'2026-10-27',date}); + assert.deepEqual(entry.previousDates,{assistant1:beforeDate,assistant2:beforeDate});assert.equal(entry.assistant1Change,8);assert.equal(entry.assistant2Change,27); + for(const key of ['assistant1','assistant2']){ + assert.equal(summary[key].netChange,entry[key+'Change']);assert.equal(summary[key].baselineTotal,entry.previous[key+'Count']);assert.equal(summary[key].baselineDate,entry.previousDates[key]); + assert.deepEqual(history.summary[key],summary[key]);assert.equal(history.rows.at(-1)[key+'Change'],summary[key].netChange); + } + assert.equal(f.ledger.peopleCount('2026-10-27').assistant1Count,null);assert.equal(f.ledger.peopleCountSummary('2026-10-27').assistant1.endTotal,null); + assert.deepEqual(f.ledger.rows('SELECT date,count,assistant1_count,assistant2_count FROM daily_people_counts ORDER BY date').map(row=>({...row})),[{date:beforeDate,count:73,assistant1_count:8204,assistant2_count:133},{date,count:91,assistant1_count:8212,assistant2_count:160}]); +}); + +test('跨多日跨月各自取最近非NULL日期,0不跳过,范围以前找基准且结束日不借用旧值',t=>{ + const f=fixture(t),from='2026-10-03',date='2026-10-07'; + for(const input of [{date:'2026-08-19',assistant1Count:100,assistant2Count:40},{date:'2026-09-28',assistant2Count:0},{date:D,assistant1Count:120},{date:D2,count:300},{date:D3,assistant1Count:null,assistant2Count:null},{date,assistant1Count:128,assistant2Count:7}])f.write({...input,revision:0}); + const entry=f.ledger.peopleCount(date);assert.deepEqual(entry.previousDates,{assistant1:D,assistant2:'2026-09-28'});assert.deepEqual(entry.previous,{assistant1Count:120,assistant2Count:0});assert.equal(entry.assistant1Change,8);assert.equal(entry.assistant2Change,7); + const expected={assistant1:part(128,1,120,D),assistant2:part(7,1,0,'2026-09-28')},summary=f.ledger.peopleCountSummary(date,from); + assert.deepEqual({assistant1:summary.assistant1,assistant2:summary.assistant2},expected); + const history=f.ledger.peopleCountHistory({from,date});assert.deepEqual(history.summary,expected);assert.equal(history.rows.length,5);assert.ok(history.rows.every(row=>row.previousDates.assistant1===D&&row.previousDates.assistant2==='2026-09-28')); + const missing=f.ledger.peopleCountSummary('2026-10-06',from);assert.equal(missing.assistant1.endTotal,null);assert.equal(missing.assistant2.endTotal,null);assert.equal(missing.assistant1.baselineDate,D);assert.equal(missing.assistant2.baselineTotal,0);assert.equal(missing.assistant2.netChangeReason,'missing-current'); +}); + +test('历史补记、改为减少、设0和清空后自动改后续基准,后续原记录和财务均不重写',t=>{ + const f=fixture(t),first='2026-09-20',end='2026-10-07',late='2026-10-05'; + f.write({date:first,assistant1Count:100,assistant2Count:10,revision:0});f.write({date:D3,assistant1Count:120,assistant2Count:20,revision:0});f.write({date:end,assistant1Count:128,assistant2Count:27,revision:0}); + const stable=contents(f.ledger,['orders','payments','expenses','journal','movements','meta','sync','closes','inventory_snapshots']),original=JSON.stringify(f.ledger.one('SELECT * FROM daily_people_counts WHERE date=?',end)); + f.write({date:late,assistant1Count:125,assistant2Count:null,revision:0});let entry=f.ledger.peopleCount(end);assert.deepEqual(entry.previousDates,{assistant1:late,assistant2:D3});assert.equal(entry.assistant1Change,3);assert.equal(entry.assistant2Change,7); + f.write({date:late,assistant1Count:130,assistant2Count:0,revision:1});entry=f.ledger.peopleCount(end);assert.deepEqual(entry.previousDates,{assistant1:late,assistant2:late});assert.equal(entry.assistant1Change,-2);assert.equal(entry.assistant2Change,27); + f.write({date:late,assistant1Count:null,assistant2Count:null,revision:2});entry=f.ledger.peopleCount(end);assert.deepEqual(entry.previousDates,{assistant1:D3,assistant2:D3});assert.equal(entry.assistant1Change,8);assert.equal(entry.assistant2Change,7); + f.write({date:D3,assistant1Count:null,assistant2Count:null,revision:1});entry=f.ledger.peopleCount(end);assert.deepEqual(entry.previousDates,{assistant1:first,assistant2:first});assert.equal(entry.assistant1Change,28);assert.equal(entry.assistant2Change,17); + f.write({date:first,assistant1Count:null,assistant2Count:null,revision:1});entry=f.ledger.peopleCount(end);assert.deepEqual(entry.previousDates,{assistant1:null,assistant2:null});assert.equal(entry.assistant1Change,null);assert.equal(entry.assistant2ChangeReason,'missing-previous'); + const summary=f.ledger.peopleCountSummary(end),history=f.ledger.peopleCountHistory({from:late,date:end});for(const key of ['assistant1','assistant2']){assert.equal(summary[key].netChange,entry[key+'Change']);assert.equal(summary[key].baselineDate,null);assert.equal(history.rows.at(-1)[key+'Change'],null);} + assert.equal(JSON.stringify(f.ledger.one('SELECT * FROM daily_people_counts WHERE date=?',end)),original);assert.equal(contents(f.ledger,['orders','payments','expenses','journal','movements','meta','sync','closes','inventory_snapshots']),stable); +}); + +test('上次有效记录跨月跨年和闰日精确,最早合法日缺基数也正常返回',t=>{ const f=fixture(t);for(const [date,count] of [['2000-01-01',0],['2023-12-31',100],['2024-01-01',101],['2024-02-28',100],['2024-02-29',98],['2024-03-01',101]])f.write({date,assistant1Count:count,revision:0}); const first=f.ledger.peopleCount('2000-01-01');assert.equal(first.previousDate,'1999-12-31');assert.equal(first.assistant1Count,0);assert.equal(first.assistant1Change,null);assert.equal(first.assistant1ChangeReason,'missing-previous'); assert.equal(f.ledger.peopleCount('2024-01-01').assistant1Change,1);assert.equal(f.ledger.peopleCount('2024-02-29').assistant1Change,-2);assert.equal(f.ledger.peopleCount('2024-03-01').assistant1Change,3); @@ -266,3 +303,22 @@ test('旧人数幂等回执在HTTP发送前重新按固定成员投影,缓存 const cookie=await login('assistant'),failed=await call('/api/people-count',cookie,errorBody,errorKey);assert.equal(failed.status,409);const error=await failed.json();assert.match(error.error,/原人数回执不完整/);assert.ok(!JSON.stringify(error).includes('assistant2'));assert.equal(l.one('SELECT date FROM daily_people_counts WHERE date=?',D3),undefined); assert.equal(contents(l,tables),before,'发送前过滤不改原operations、原记录、审计或金融库存'); }); + +test('三人HTTP在新POST、查询、范围及重试中隔离各自真实基准日期与人数',async t=>{ + const l=new Ledger(':memory:'),actors={};for(const member of ['owner','assistant','assistant2']){const role=member==='owner'?'owner':'assistant',id=createUser(l,member,role,'synthetic-last-date-password',member);actors[member]={id,name:member,role,member};} + const firstDate='2026-09-17',secondDate='2026-09-28',date='2026-10-28'; + l.savePeopleCount({date:firstDate,assistant1Count:8204,revision:0},actors.owner);l.savePeopleCount({date:secondDate,assistant2Count:133,revision:0},actors.owner); + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-people-last-date-http-')),app=createApp({mode:'trial',dataDir:dir,ledger:l,port:0,feishuConfig:{enabled:false}});await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve)); + t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));l.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+app.server.address().port; + const call=(route,cookie,body,key=randomUUID())=>fetch(base+route,{method:body?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(body?{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{})},...(body?{body:JSON.stringify(body)}:{})}); + const samples=[]; + for(const [member,key,count,previousTotal,previousDate,otherDate,revision] of [['assistant','assistant1',8212,8204,firstDate,secondDate,0],['assistant2','assistant2',160,133,secondDate,firstDate,1]]){ + const login=await call('/api/login','',{name:member,password:'synthetic-last-date-password'}),cookie=login.headers.get('set-cookie').split(';')[0],body={date,[key+'Count']:count,revision},operation=randomUUID(),response=await call('/api/people-count',cookie,body,operation);assert.equal(response.status,200);const result=await response.json();samples.push({cookie,body,operation,result}); + assert.deepEqual(result.previousDates,{[key]:previousDate});assert.equal(result.previous[key+'Count'],previousTotal);assert.equal(result[key+'Change'],count-previousTotal); + const routes=['/api/people-count?date='+date,'/api/people-count-history?from=2026-10-01&date='+date,'/api/order-book?from=2026-10-01&date='+date,'/api/report?from=2026-10-01&date='+date+'&basis=orderDate']; + for(const route of routes){const response=await call(route,cookie);assert.equal(response.status,200);const raw=await response.json(),value=raw.peopleCount||raw,json=JSON.stringify(value),other=key==='assistant1'?'assistant2':'assistant1';assert.ok(!json.includes(other));assert.ok(!json.includes(otherDate));assert.ok(json.includes(previousDate));if(value[key])assert.equal(value[key].baselineDate,previousDate);if(value.summary)assert.equal(value.summary[key].baselineDate,previousDate);} + } + const before=contents(l,['daily_people_counts','operations','audit','orders','payments','expenses','journal','movements']); + for(const sample of samples){const response=await call('/api/people-count',sample.cookie,sample.body,sample.operation);assert.equal(response.status,200);assert.deepEqual(await response.json(),sample.result);} + assert.equal(contents(l,['daily_people_counts','operations','audit','orders','payments','expenses','journal','movements']),before); +}); diff --git a/新账系统/test/request-retry.test.js b/新账系统/test/request-retry.test.js new file mode 100644 index 0000000..1d8ac46 --- /dev/null +++ b/新账系统/test/request-retry.test.js @@ -0,0 +1,76 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),vm=require('node:vm'),{randomUUID}=require('node:crypto'); +const {Ledger}=require('../ledger'),{createApp,createUser}=require('../server'); +const D='2026-10-28',source=fs.readFileSync(path.join(__dirname,'../public/app.js'),'utf8').replace(/\ninit\(\);\s*$/,''); +function harness(fetcher,{user={id:'retry-user',name:'合成麦麦',role:'owner'},timeout=false,onDelay}={}){ + const saved=new Map(),calls=[],delays=[],messages=[],handlers={},buttons=[{disabled:false},{disabled:true}],status={hidden:true,_text:'',set textContent(value){this._text=value;messages.push(value);},get textContent(){return this._text;}},nodes=new Map([['#request-status',status],['#pending',{hidden:true,innerHTML:''}]]); + const context=vm.createContext({console,URLSearchParams,AbortController,crypto:{randomUUID},setInterval(){},setTimeout(fn,ms){if(ms===25000)return timeout?setImmediate(fn):0;delays.push(ms);onDelay?.(ms);return setImmediate(fn);},clearTimeout(id){if(id)clearImmediate(id);},document:{querySelector:q=>nodes.get(q)||null,querySelectorAll:q=>q==='button'?buttons:[],addEventListener:(name,handler)=>(handlers[name]??=[]).push(handler)},window:{scrollTo(){}},localStorage:{getItem:k=>saved.get(k)??null,setItem:(k,v)=>saved.set(k,String(v)),removeItem:k=>saved.delete(k)},fetch:async(url,options)=>{calls.push({url,...options});return fetcher(url,options,calls.length);},__user:user}); + const run=code=>vm.runInContext(code,context),json=code=>JSON.parse(JSON.stringify(run(code))); + run(source);run(`session={user:__user};state={user:__user,today:'${D}'};applyAfterSaleRestrictions=function(){};updateOrderDetailNavigation=function(){};toast=function(){};showSavedPeopleCount=async function(date){globalThis.__finished=date;};`); + return {context,run,json,saved,calls,delays,messages,status,buttons,handlers,user,key:'mm-pending-'+user.id}; +} +const ok=value=>new Response(JSON.stringify(value),{status:200,headers:{'Content-Type':'application/json'}}); +const httpError=(status,error)=>new Response(JSON.stringify({error}),{status,headers:{'Content-Type':'application/json'}}); + +test('GET只对短暂失败最多重试2次,502/503/504的HTML不掩盖状态,状态可见且成功后清理',async()=>{ + for(const status of [502,503,504]){const h=harness((url,options,attempt)=>attempt===1?new Response('网关中断',{status}):ok({ready:true}));assert.deepEqual(JSON.parse(JSON.stringify(await h.run("api('/api/state')"))),{ready:true});assert.equal(h.calls.length,2);assert.deepEqual(h.delays,[400]);assert.ok(h.messages.some(text=>text.includes('自动重连(1/2)')));assert.equal(h.status.hidden,true);assert.equal(h.saved.size,0);assert.ok(h.calls.every(call=>call.headers['X-Ledger-User']==='retry-user'));} + const h=harness(()=>{throw new TypeError('Failed to fetch');});await assert.rejects(h.run("api('/api/state')"),/Failed to fetch/);assert.equal(h.calls.length,3);assert.deepEqual(h.delays,[400,1200]);assert.equal(h.saved.size,0); +}); + +test('请求超时、响应正文中断与不完整JSON可有限重读,401/403等明确业务拒绝不重试',async()=>{ + const timed=harness((url,{signal})=>new Promise((resolve,reject)=>signal.addEventListener('abort',()=>reject(Object.assign(new Error('超时'),{name:'AbortError'})),{once:true})),{timeout:true});await assert.rejects(timed.run("api('/api/state')"),{name:'AbortError'});assert.equal(timed.calls.length,3); + for(const failure of [()=>{throw new TypeError('正文中断');},()=>{throw new SyntaxError('Unexpected end of JSON');}]){const h=harness((url,options,attempt)=>attempt===1?{status:200,ok:true,json:failure}:ok({complete:true}));await h.run("api('/api/state')");assert.equal(h.calls.length,2);} + for(const status of [400,401,403,404,409,413,429,500]){const h=harness(()=>httpError(status,'具体业务错误'));await assert.rejects(h.run("api('/api/state')"),error=>error.status===status&&error.message==='具体业务错误');assert.equal(h.calls.length,1);} +}); + +test('写入仅mutate幂等白名单可自动重试,原payload与操作号不变,连续点击只发一组请求',async()=>{ + let release;const gate=new Promise(resolve=>release=resolve),h=harness(async(url,options,attempt)=>{if(attempt===1){await gate;throw new TypeError('响应丢失');}return ok({saved:true});});h.context.__data={date:D,assistant1Count:8,assistant2Count:0,revision:0}; + const saving=h.run("mutate('/api/people-count',__data)");assert.equal(h.run('busy'),true);assert.ok(h.buttons.every(button=>button.disabled));assert.match(h.status.textContent,/正在保存/);await assert.rejects(h.run("mutate('/api/people-count',__data)"),/正在保存/);h.run('__data.assistant1Count=999');release();await saving; + assert.equal(h.calls.length,2);assert.equal(h.calls[0].body,h.calls[1].body);assert.equal(JSON.parse(h.calls[1].body).assistant1Count,8);assert.equal(h.calls[0].headers['Idempotency-Key'],h.calls[1].headers['Idempotency-Key']);assert.equal(h.saved.size,0);assert.equal(h.run('busy'),false);assert.deepEqual(h.buttons.map(button=>button.disabled),[false,true]);assert.ok(h.messages.some(text=>text.includes('自动确认(1/2)'))); + for(const url of ['/api/login','/api/setup','/api/password','/api/team-members/assistant2/password','/api/backup','/api/sync','/api/recoveries/quote','/api/unknown-write']){const h=harness(()=>{throw new TypeError('断线');});await assert.rejects(h.run(`api('${url}',{value:1},'original-key-12345')`));assert.equal(h.calls.length,1);assert.equal(h.delays.length,0);} + for(const url of ['/api/password','/api/backup','/api/unknown-write']){const h=harness(()=>{throw new TypeError('断线');});await assert.rejects(h.run(`mutate('${url}',{value:1})`));assert.equal(h.calls.length,1);} +}); + +test('自动确认用尽仍保留原pending,旧pending不自动执行,手动恢复沿用原请求并兼容无userId旧格式',async()=>{ + let connected=false;const h=harness(()=>{if(!connected)throw new TypeError('断线');return ok({saved:true});});h.context.__data={date:D,assistant1Count:8,revision:0};await assert.rejects(h.run("mutate('/api/people-count',__data)"),/提交结果待确认/);const job=JSON.parse(h.saved.get(h.key));assert.equal(h.calls.length,3);assert.match(h.json('pending().key'),/^[a-zA-Z0-9_-]{16,100}$/);assert.match(h.run("document.querySelector('#pending').innerHTML"),/恢复原操作/); + delete job.userId;h.saved.set(h.key,JSON.stringify(job));h.run('showPending()');assert.equal(h.calls.length,3);connected=true;const button={disabled:false,dataset:{action:'retry'},closest(){return null;}};for(const handler of h.handlers.click)await handler({target:{closest:()=>button}}); + assert.equal(h.calls.length,4);assert.equal(h.calls[3].headers['Idempotency-Key'],job.key);assert.equal(h.calls[3].body,h.calls[0].body);assert.equal(h.saved.size,0);assert.equal(h.run('__finished'),D); +}); + +test('已确认的参数/权限/冲突保留原错误并停止,HTML拒绝保留pending,新同账号操作不被旧回包删除',async()=>{ + for(const status of [400,403,404,409,413]){const h=harness(()=>httpError(status,'必须重新核对具体字段'));await assert.rejects(h.run("mutate('/api/people-count',{date:'2026-10-28',revision:0})"),error=>error.message==='必须重新核对具体字段'&&error.status===status);assert.equal(h.calls.length,1);assert.equal(h.saved.size,0);} + for(const status of [400,403,404,409]){const h=harness(()=>new Response('访问被拒绝',{status}));await assert.rejects(h.run("mutate('/api/people-count',{date:'2026-10-28',revision:0})"),error=>error.message.includes(String(status))&&!error.confirmed);assert.equal(h.calls.length,1);assert.ok(h.saved.has(h.key));} + let release;const h=harness(()=>new Promise(resolve=>release=resolve)),saving=h.run("mutate('/api/people-count',{date:'2026-10-28',revision:0})"),newJob={url:'/api/stock',data:{date:D},key:'newer-operation-key'};h.saved.set(h.key,JSON.stringify(newJob));release(ok({saved:true}));await saving;assert.deepEqual(JSON.parse(h.saved.get(h.key)),newJob); +}); + +test('本页账号在退避期间改变立即停止,不把旧操作移入新账号或清掉新账号pending',async()=>{ + let h;h=harness(()=>{throw new TypeError('断线');},{onDelay(){h.run("session.user={id:'different-user'};state.user=session.user;");h.saved.set('mm-pending-different-user','{"key":"other-user-operation"}');}});await assert.rejects(h.run("mutate('/api/people-count',{date:'2026-10-28',revision:0})"),error=>error.code==='ACCOUNT_CHANGED');assert.equal(h.calls.length,1);assert.ok(h.saved.has(h.key));assert.equal(h.saved.get('mm-pending-different-user'),'{"key":"other-user-operation"}'); +}); + +async function serverFixture(t){ + const ledger=new Ledger(':memory:'),dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-request-retry-')),users={};for(const member of ['owner','assistant']){const role=member==='owner'?'owner':'assistant',id=createUser(ledger,'合成'+member,role,'synthetic-retry-password',member);users[member]={id,name:'合成'+member,role,member};} + const app=createApp({mode:'trial',dataDir:dir,ledger,port:0,feishuConfig:{enabled:false}});await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));const base='http://127.0.0.1:'+app.server.address().port; + t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));ledger.close();fs.rmSync(dir,{recursive:true,force:true});}); + const cookies={};for(const member of ['owner','assistant']){const response=await fetch(base+'/api/login',{method:'POST',headers:{'Content-Type':'application/json','X-Requested-With':'maimai-ledger',Origin:base},body:JSON.stringify({name:'合成'+member,password:'synthetic-retry-password'})});assert.equal(response.status,200);cookies[member]=response.headers.get('set-cookie').split(';')[0];} + const send=(url,options,cookie=cookies.owner)=>fetch(base+url,{...options,headers:{...options.headers,Cookie:cookie,Origin:base}}); + return {ledger,users,cookies,send,base}; +} +const sale={date:D,project:'合成售后',customer:'合成客户',amount:'25.50',payer:'owner'}; + +test('真实HTTP首次保存已提交但响应丢失,自动确认只留1笔售后、审计和操作,不重复扣利润',async t=>{ + const f=await serverFixture(t),h=harness(async(url,options,attempt)=>{const response=await f.send(url,options);if(attempt===1){assert.equal(response.status,200);await response.json();throw new TypeError('首回执丢失');}return response;},{user:f.users.owner});h.context.__sale=sale;const result=await h.run("mutate('/api/after-sales',__sale)");assert.ok(result.after_sale_id);assert.equal(h.calls.length,2);assert.equal(f.ledger.rows('SELECT * FROM after_sales').length,1);assert.equal(f.ledger.rows("SELECT * FROM audit WHERE action='登记售后'").length,1);assert.equal(f.ledger.rows('SELECT * FROM operations').length,1);assert.equal(f.ledger.reportByOrderDate(D).profit,-2550);assert.equal(h.saved.size,0);assert.equal(h.calls[0].body,h.calls[1].body);assert.equal(h.calls[0].headers['Idempotency-Key'],h.calls[1].headers['Idempotency-Key']); +}); + +test('真实HTTP首单已提交丢回执后收到网关HTML403,停止自动确认并保留原pending供手动取回',async t=>{ + const f=await serverFixture(t);let gateway=true;const h=harness(async(url,options,attempt)=>{if(attempt===2&&gateway)return new Response('mTLS access denied',{status:403});const response=await f.send(url,options);if(attempt===1){await response.json();throw new TypeError('回执丢失');}return response;},{user:f.users.owner});h.context.__sale=sale;await assert.rejects(h.run("mutate('/api/after-sales',__sale)"),error=>error.status===403&&error.message.includes('403')&&!error.confirmed);assert.equal(h.calls.length,2);const job=JSON.parse(h.saved.get(h.key));assert.ok(job.key);assert.equal(f.ledger.rows('SELECT * FROM after_sales').length,1);gateway=false;h.context.__job=job;await h.run('mutate(__job.url,__job.data,__job)');assert.equal(h.calls.length,3);assert.equal(h.saved.size,0);assert.equal(f.ledger.rows('SELECT * FROM after_sales').length,1);assert.equal(f.ledger.rows('SELECT * FROM operations').length,1); +}); + +test('真实HTTP另一标签切cookie账号时原用户头阻止重试代写,旧客户端仍兼容且头不能代替权限',async t=>{ + for(const committed of [false,true]){ + const f=await serverFixture(t);let cookie=f.cookies.owner;const h=harness(async(url,options,attempt)=>{if(attempt===1){if(committed){const response=await f.send(url,options,cookie);assert.equal(response.status,200);await response.json();}cookie=f.cookies.assistant;throw new TypeError('连接断开后另标签切账号');}return f.send(url,options,cookie);},{user:f.users.owner});h.context.__sale=sale; + await assert.rejects(h.run("mutate('/api/after-sales',__sale)"),error=>error.status===409&&error.code==='ACCOUNT_CHANGED');assert.equal(h.calls.length,2);assert.equal(f.ledger.rows('SELECT * FROM after_sales').length,committed?1:0);assert.equal(f.ledger.rows('SELECT * FROM operations').length,committed?1:0);assert.ok(h.saved.has(h.key));assert.ok(!h.saved.has('mm-pending-'+f.users.assistant.id)); + const read=await f.send('/api/state',{method:'GET',headers:{'X-Ledger-User':f.users.owner.id}},f.cookies.assistant);assert.equal(read.status,409);assert.equal((await read.json()).code,'ACCOUNT_CHANGED'); + const legacy=await f.send('/api/after-sales',{method:'POST',headers:{'Content-Type':'application/json','X-Requested-With':'maimai-ledger','Idempotency-Key':randomUUID()},body:JSON.stringify({...sale,customer:'兼容旧客户端'})},f.cookies.owner);assert.equal(legacy.status,200); + const permission=await f.send('/api/printing',{method:'POST',headers:{'Content-Type':'application/json','X-Requested-With':'maimai-ledger','Idempotency-Key':randomUUID(),'X-Ledger-User':f.users.assistant.id},body:'{}'},f.cookies.assistant);assert.equal(permission.status,403); + } +}); diff --git a/新账系统/test/team-ui.test.js b/新账系统/test/team-ui.test.js index 27ad62d..0d871bc 100644 --- a/新账系统/test/team-ui.test.js +++ b/新账系统/test/team-ui.test.js @@ -82,7 +82,7 @@ test('历史报销引用以隐藏资料保留原金额和版本,付款人继 } }); test('助理2人数视图只展示本人,老板保留两项,不把未提供当0',()=>{ - const h=harness('assistant2');h.context.__summary={from:D,date:D,assistant2:{total:0,endTotal:0,baselineTotal:null,netChange:null,netChangeReason:'missing-previous',recordedDays:1}};const html=h.run('peopleCountHTML(__summary)');assert.match(html,/助理2当日总人数/);assert.match(html,/0 人(已记录)/);assert.match(html,/昨日未记录/);assert.doesNotMatch(html,/助理1当日总人数/); + const h=harness('assistant2');h.context.__summary={from:D,date:D,assistant2:{total:0,endTotal:0,baselineTotal:null,netChange:null,netChangeReason:'missing-previous',recordedDays:1,baselineDate:null}};const html=h.run('peopleCountHTML(__summary)');assert.match(html,/助理2当日总人数/);assert.match(html,/0 人(已记录)/);assert.match(html,/暂无上次记录/);assert.doesNotMatch(html,/助理1当日总人数/); const owner=harness();assert.deepEqual(owner.json('peopleParts()'),[['assistant1','助理1人数'],['assistant2','助理2人数']]); }); test('三人模板保留助理2付款人与收款账户,不继承已批准抵用身份',()=>{ diff --git a/新账系统/三人使用说明.md b/新账系统/三人使用说明.md index 71aa174..d15711d 100644 --- a/新账系统/三人使用说明.md +++ b/新账系统/三人使用说明.md @@ -52,9 +52,9 @@ 待批期间正常销售仍可进行。麦麦审批前重新打开申请核对最新库存,系统会检查更正后的每个历史日期余额及订单预留;不足时整笔不生效。修改库存日期会使原、新日期中较早日期及以后的库存快照和每日核对过期,原快照数值保留,核实实物后再保存。 -助理1只填写助理1人数,助理2只填写助理2人数,麦麦可以维护两项。每天填的是当天总人数,系统用它减去自然日前一天的总人数,得到新增或减少;100→108→105对应增加8、减少3,不把每天总数相加。留空是未记录,0是已经确认当天为0人;当天或昨天缺记录时,变化显示未知并说明缺哪一天,不跨过空日找上一条记录。 +助理1只填写助理1人数,助理2只填写助理2人数,麦麦可以维护两项。每天填的是当天总人数,系统分别与该助理上次有记录的总人数比较,得到新增或减少,并显示实际对比日期;100→108→105对应增加8、减少3,不把每天总数相加。没营业或漏录的日期自动跳过;留空是未记录,0是已经确认当天为0人,不能跳过0。两位助理的上次日期可以不同,没有更早记录时显示首次记录/暂无上次记录,不把总数算作新增。 -查询一段时间或本月时,显示结束日总人数,以及“结束日减开始日前一天”的本期净增;缺任一端点就显示未知。修改历史总数会动态更新当天和次日变化,同日重新保存仍覆盖当天总数。历史原人数保留,不自动拆分、清空或改写,也不影响订单、成本、利润和库存。 +查询一段时间或本月时,显示精确结束日总人数,以及“结束日减各自开始日前最近有效记录”的本期净增,基准可以跨月并显示真实日期;缺任一端点就显示未知,不拿此前总数代替未记录的结束日。补记、修改或清空历史总数会动态更新后续变化,同日重新保存仍覆盖当天总数。历史原人数保留,不自动拆分、清空或改写,也不影响订单、成本、利润和库存。 ## 旧账与本次交付范围 diff --git a/新账系统/使用说明.md b/新账系统/使用说明.md index 1a2142b..42dc9ab 100644 --- a/新账系统/使用说明.md +++ b/新账系统/使用说明.md @@ -21,6 +21,12 @@ 原来的 `server.js`、`启动台账.bat` 和飞书旧账保持原样。旧版入口仍会操作旧账,试用新版请选名字含「新账」的文件。 +## 短暂断连与恢复 + +保存时会显示「正在保存」,短暂断连后最多自动确认两次,期间不要重复点击。自动确认始终使用原操作号和原内容,已经保存的账务不会再记一笔;成功后继续正常使用,仍未取得明确结果时才显示「恢复原操作」。手动恢复也沿用原请求,刷新页面不会自动执行旧的待恢复操作。 + +登录过期、权限、参数或版本冲突会直接提示具体原因,不反复提交。访问被拒绝但没有取得可确认的业务结果时,原操作仍会保留;先核对登录和访问状态,再恢复。另一个标签页切换账号后,旧页面会暂停请求并要求刷新,不会以新账号提交旧内容。登录、修改密码和生成备份不自动重试。 + ## 开一张订单 客户称呼/代号和开单人均须填写,前后空格会去除。新建、继续保存草稿、修改订单及助理申请修改都会检查;模板可以暂存空客户,套用后仍须补齐才能开单。历史订单仍能查看和打印,旧单补齐账务及历史锁价交付沿用原资料;以后修改保存时须补齐必填项。此项已于2026-10-23备份后更新本机3100并重启,外部浏览器已打开;29张表267行数据在更新前、备份及更新后指纹一致,完整性检查为`ok`。该次仅更新本机,未提交、推送或部署云端。 @@ -205,9 +211,9 @@ 在「订单」页点「记录人数」,填写当天总人数,只保留「助理1人数」「助理2人数」。助理只看和填写自己的项目,麦麦可以维护两项。支持0~1000000的整数,留空表示未记录,0表示已经确认当天总数为0。 -日期默认今天,可改为以前的日期;当天已有记录时显示原值,重新保存覆盖当天总数。弹窗显示自然日前一天的基数,并按填写值实时计算新增或减少。例如昨天100、今天108,新增8;明天105则减少3。缺当天或昨天的记录时显示未知,不把缺录当0,也不跨空日取上一条。修改历史总数会动态影响当天和次日变化;历史原人数保留,不自动归给任一助理或重写。 +日期默认今天,可改为以前的日期;当天已有记录时显示原值,重新保存覆盖当天总数。弹窗分别显示每位助理上次有记录的日期与总人数,并按填写值实时计算新增或减少。没营业、漏录或留空的日期自动跳过,0仍是有效记录。例如10月26日记录8204/133人,10月27日未记录,10月28日记录8212/160人,显示新增8/27人,并注明与10月26日比较。没有更早记录时显示「首次记录/暂无上次记录」,不把当天总数当新增;当天未记录时变化仍未知。两位助理的上次记录日期可以不同。补记、修改或清空历史总数后,后续变化按新的最近有效记录动态更新;历史原人数保留,不自动归给任一助理或重写。 -订单页、每日对账及下载报告采用同一口径:显示所选结束日总人数,本期净增为“结束日总数减开始日前一天总数”。本月不再把每天总数相加;例如月初前一天100、所选结束日105,本期净增5。两端缺任一值则净增未知,中间缺日不妨碍两端齐全时计算净增。「每日人数」逐日显示总人数和较昨日变化,同时保留已记录天数。订单搜索和状态筛选不改变这项日期统计。 +订单页、每日对账及下载报告采用同一口径:单日显示较上次记录的变化;范围/本月显示所选结束日总人数,本期净增为“结束日总数减该助理开始日前最近一次有效记录总数”,并显示实际基准日期。基准可以跨月查找,两位助理分别计算;每日总数不相加。结束日没有记录时仍显示未记录,不拿此前日期代替;没有期初基准或结束日总数时净增未知。「每日人数」只展示有记录的日期,保留0及已记录天数,每条变化注明实际对比日期。订单搜索和状态筛选不改变这项日期统计。 这里是手动记录的通用人数,不自动等同咨询人数、成交人数或销售单数,也不参与成本、利润或库存计算。若两人同时修改同一天,后保存的一方需先读取最新记录,避免覆盖对方刚保存的数。连接中断后点击「恢复原操作」,沿用原请求和操作号,不重复保存。下方2026-10-23验证保留为历史记录,当时的求和展示已被本次总人数与净增口径替代。 diff --git a/新账系统/维护与部署.md b/新账系统/维护与部署.md index b237fd9..558cc9f 100644 --- a/新账系统/维护与部署.md +++ b/新账系统/维护与部署.md @@ -1,5 +1,13 @@ # 新账系统:维护与部署 +## 2026-10-29 短暂断连的安全自动确认(本地,未提交、未推送) + +读取及 `mutate` 内事务幂等白名单写入,遇到网络失败、25秒超时、响应正文中断或408/502/503/504,最多重试2次,退避400/1200毫秒。写入首发前复制内容,重试复用原操作号和原JSON正文,状态在页面及当前弹窗可见;成功才清除同一操作号的待恢复记录,用尽后仍可手动恢复。旧待恢复请求兼容原格式,但不在启动或重连事件中自动执行。登录、密码、备份、同步和无幂等写入不自动重试;明确业务拒绝立即停止,非JSON网关拒绝保留待确认状态。 + +受保护请求携带 `X-Ledger-User` 原用户ID,服务端用当前cookie登录身份核对,不一致时以409/`ACCOUNT_CHANGED`停止,防止另一标签切账号后代写。此头只做一致性检查,登录、CSRF、成员权限及mTLS保持;旧客户端无头仍兼容。既有人数未提交变更保留,无数据库迁移,无真实账本读写。 + +新增 `test/request-retry.test.js` 9项通过,覆盖真实HTTP已提交丢回执后的单笔幂等、HTML403保留原操作、换cookie前后身份隔离,以及有限重试、双击、原payload、旧待恢复格式和同账号新操作保护。主任务完整回归845/845通过,隔离3101已重启并浏览器回读;线上未更新,部署时需同时更新前后端并重启服务。 + ## 2026-10-26 库存流水分页与手动类型筛选(本地实现,尚未发布) 库存流水改为每页100条,通过上一页、下一页查看完整可见历史。货盘与动作可共同筛选,动作包括全部流水、手动增加、手动减少、手动平移及全部手动变动。切换筛选回第一页,翻页保留筛选条件及库存登记表单;条数与页数均在成员权限和筛选后计算。 @@ -38,7 +46,15 @@ 发布流程为推送仓库后由麦麦更新服务器。线上 `tz.summermai.top` 的实际版本与功能是否生效,须在服务器更新后核验;不依据仓库代码或本地预览推断已上线。真实数据库、备份及凭据不纳入Git。正式启动升级前通过主入口创建并校验SQLite一致性备份,再执行必要升级;助理2由麦麦在成员设置中设置密码。以下“本地”“未提交”“未推送”“未部署”等是各实施阶段当时的记录,当前发布状态以实际推送记录及线上核验为准。 -## 2026-10-25 人数按每日总数与自然昨日计算(本地,未推送) +## 2026-10-28 人数与各自上次有效记录比较(本地,未提交、未推送) + +日变化=当日总人数-该助理当前日期之前最近一次非NULL总人数,未记录日跳过,0仍是有效记录;每人基准日期独立。没有更早记录时返回NULL及缺基准原因,页面显示首次记录/暂无上次记录。范围基准同样取开始日前最近有效记录,但期末只认所选结束日,不用此前日期代替缺录的结束日。补记、修改或清空历史值后,只在读取时派生新的后续变化,不重写后续记录或原人数。 + +单日及历史行新增 `previousDates:{assistant1,assistant2}`,每助理范围结果新增 `baselineDate`,均为实际比较日期或NULL;顶层 `previousDate/baselineDate` 仅保留原自然日前边界以兼容既有接口,不作为显示基准。一次SQL读取范围及各可见成员最近基准,内存跳过NULL推进;历史接口保留逐日行,页面仍只展示有记录日。前端校验同时核对总数、差值、原因、每人实际日期、跨空日基准连续性及范围端点。新POST日期字段同样按成员白名单投影;旧幂等回执只投影原缓存,不重算、不改缓存、不重复写入。订单财务、利润、库存及版本不受人数显示规则影响。 + +定向测试51/51通过:`node --test test/people-count.test.js test/people-count-ui.test.js test/team-ui.test.js test/team-privacy-http.test.js`。新增7项覆盖8204/133→8212/160的8/27增量、跨月不同基准与0、历史补记/更改/清空、三人HTTP日期隔离与幂等、新日期字段和跨空日连续性的严格前端校验;均使用内存或系统临时目录合成账本。 + +## 历史:2026-10-25 人数按每日总数与自然昨日计算(已由10月28日口径替代) `assistant1_count/assistant2_count` 解释为对应日期的总人数。日变化=当天总数-自然日前一天总数,可为负;缺当天或昨日时返回 `null`,不能取上一条记录或把缺录当0。范围/月度显示所选结束日 `endTotal`,净增 `netChange=endTotal-baselineTotal`,基数为开始日前一天;缺任一端点返回未知,内部缺日且两端齐全仍可计算净增,不累加部分变化。单日、历史、订单簿和日报使用相同派生口径,前端下载沿用同一结果。