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

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

+67 -11
View File
@@ -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);
});