2026-10-23 00:21:53 +08:00
'use strict' ;
const { test } = require ( 'node:test' ), assert = require ( 'node:assert/strict' ), fs = require ( 'node:fs' ), path = require ( 'node:path' ), vm = require ( 'node:vm' ),{ randomUUID } = require ( 'node:crypto' );
const D = '2026-10-22' , NEXT = '2026-10-23' , user = { id : 'people-ui-user' , name : '合成麦麦' , role : 'owner' };
const record = ( date , count , revision , assistant1Count = null , assistant2Count = null )=>({ date , count , assistant1Count , assistant2Count , revision });
function harness (){
const nodes = new Map (), handlers = {}, saved = new Map (), calls = [], toasts = [], save = { disabled : true };
2026-10-24 16:09:45 +08:00
const form = { id : 'people-count-form' , dataset : {}, elements : Object . fromEntries ([ 'date' , 'assistant1Count' , 'assistant2Count' ]. map ( name =>[ name ,{ value : name === 'date' ? D : '残留值' , disabled : false }])), querySelector : ()=> save };
2026-10-23 00:21:53 +08:00
const dialog = { open : true , innerHTML : '' , close (){ this . open = false ;}, showModal (){ this . open = true ;}};
for ( const [ name , node ] of [[ '#people-count-dialog' , dialog ],[ '#people-count-form' , form ],[ '#people-count-status' ,{ textContent : '' }],[ '#people-count-error' ,{ innerHTML : '' }],[ '#pending' ,{ hidden : true , innerHTML : '' }]]) nodes . set ( name , node );
const context = vm . createContext ({ console , URLSearchParams , crypto : { randomUUID }, setInterval (){}, setTimeout (){}, clearTimeout (){}, FormData : class { constructor ( value ){ return Object . entries ( value . elements ). filter (([, field ])=> ! field . disabled ). map (([ name , field ])=>[ name , field . value ]);}},
document : { addEventListener ( type , handler ){( handlers [ type ] ??= []). push ( handler );}, querySelector : selector => nodes . get ( selector ) || null , querySelectorAll : ()=>[]}, window : { scrollTo (){}},
localStorage : { getItem : key => saved . get ( key ) ?? null , setItem : ( key , value )=> saved . set ( key , String ( value )), removeItem : key => saved . delete ( key )}, __user : user , __calls : calls , __toasts : toasts , __form : form , __response : record ( D , 3 , 1 , 0 , null ), __savedDate : null });
const run = code => vm . runInContext ( code , context ), json = code => JSON . parse ( JSON . stringify ( run ( code )));
run ( fs . readFileSync ( path . join ( __dirname , '../public/app.js' ), 'utf8' ). replace ( /\ninit\(\);\s*$/ , '' ));
run ( `session={user:__user};state={user:__user,today:' ${ NEXT } '};tab='orders';api=async function(url,data,key){__calls.push({url,data,key});return __response;};toast=function(message,error){__toasts.push({message,error});};showSavedPeopleCount=async function(date){__savedDate=date;};` );
return { context , run , json , nodes , handlers , saved , calls , toasts , form , dialog , save , key : 'mm-pending-' + user . id };
}
2026-10-24 16:09:45 +08:00
function historyHarness (){
const h = harness (), form = { id : 'people-count-history-form' , dataset : {}, elements : { from : { value : '2026-10-01' }, date : { value : NEXT }}}, dialog = { open : true , innerHTML : '' , showModal (){ this . open = true ;}, close (){ this . open = false ;}}, content = { innerHTML : '' , attributes : {}, setAttribute ( key , value ){ this . attributes [ key ] = value ;}};
h . nodes . set ( '#people-count-history-dialog' , dialog ); h . nodes . set ( '#people-count-history-form' , form ); h . nodes . set ( '#people-count-history-content' , content ); h . run ( `peopleHistoryToday=' ${ NEXT } ';` ); return {... h , historyForm : form , historyDialog : dialog , historyContent : content };
}
function history ( from , date ){
const days = ( Date . parse ( date ) - Date . parse ( from )) / 86400000 + 1 , rows = Array . from ({ length : days },( _ , i )=>({ date : new Date ( Date . parse ( from ) + i * 86400000 ). toISOString (). slice ( 0 , 10 ), assistant1Count : i === 0 ? 0 : null , assistant2Count : i === days - 1 ? 8 : null }));
return { from , date , today : NEXT , rows , summary : { assistant1 : { total : 0 , recordedDays : 1 }, assistant2 : { total : 8 , recordedDays : 1 }}};
}
test ( '人数表单与日月汇总只保留两位助理,可空与零及各自记录天数明确,旧人数不展示' , async ()=>{
2026-10-23 00:21:53 +08:00
const h = harness (); await h . run ( 'showPeopleCountForm()' ); const html = h . dialog . innerHTML ;
2026-10-24 16:09:45 +08:00
assert . doesNotMatch ( html , /name="count"/ ); for ( const name of [ 'assistant1Count' , 'assistant2Count' ]){ assert . ok ( html . includes ( 'name="' + name + '"' )); assert . doesNotMatch ( html , new RegExp ( 'name="' + name + '"[^>]*required' ));}
2026-10-23 00:21:53 +08:00
h . context . __summary = { from : D , date : NEXT , total : 7 , recordedDays : 2 , assistant1 : { total : 0 , recordedDays : 1 }, assistant2 : { total : 9 , recordedDays : 2 }};
2026-10-24 16:09:45 +08:00
assert . deepEqual ( h . json ( 'peopleCountReportLines(__summary)' ),[ '助理1人数:0 人 · 已记录 1 天(按所选日期分别统计)' , '助理2人数:9 人 · 已记录 2 天(按所选日期分别统计)' ]);
const combined = h . run ( 'peopleCountHTML(__summary)' ); assert . equal (( combined . match ( /class="people-count-item"/g ) || []). length , 2 ); assert . ok ( combined . includes ( '助理1人数合计' )); assert . ok ( combined . includes ( '助理2人数合计' )); assert . doesNotMatch ( combined , />人数合计<|7 人/ );
2026-10-23 00:21:53 +08:00
h . context . __summary = { from : D , date : D , total : 0 , recordedDays : 1 , assistant1 : { total : 0 , recordedDays : 0 }, assistant2 : { total : 0 , recordedDays : 1 }};
assert . equal ( h . run ( "peopleCountText(__summary,'assistant1')" ), '未记录' ); assert . equal ( h . run ( "peopleCountText(__summary,'assistant2')" ), '0 人(已记录)' );
});
2026-10-24 16:09:45 +08:00
test ( '切日期读取时两项清空禁用,晚到响应不覆盖新日期或新用户,缺助理字段不能保存' , async ()=>{
2026-10-23 00:21:53 +08:00
const h = harness (), pending = []; h . context . __pending = pending ; h . run ( 'api=function(){return new Promise(resolve=>__pending.push(resolve));};' );
2026-10-24 16:09:45 +08:00
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 );
2026-10-23 00:21:53 +08:00
h . form . elements . date . value = NEXT ; const second = h . run ( 'loadPeopleCount()' ); pending [ 1 ]( record ( NEXT , 8 , 2 , null , 0 )); await second ;
2026-10-24 16:09:45 +08:00
assert . equal ( h . form . elements . assistant1Count . value , '' ); assert . equal ( h . form . elements . assistant2Count . value , 0 ); assert . match ( h . nodes . get ( '#people-count-status' ). textContent , /助理1人数:未记录;助理2人数:0 人(已记录)/ ); 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 );
2026-10-23 00:21:53 +08:00
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 , /未完整返回/ );
2026-10-24 16:09:45 +08:00
h . run ( 'api=async function(){return {date:state.today,assistant1Count:0,assistant2Count:null,revision:3};};' ); await h . run ( 'loadPeopleCount()' ); assert . equal ( h . save . disabled , false ); assert . equal ( h . form . elements . assistant1Count . value , 0 ); assert . equal ( h . form . elements . assistant2Count . value , '' );
2026-10-23 00:21:53 +08:00
});
2026-10-24 16:09:45 +08:00
test ( '只提交两位助理,校验整数边界与空白null,断网恢复保留原操作号且不补旧count' , async ()=>{
const h = harness (); await h . run ( 'loadPeopleCount()' ); h . form . elements . assistant1Count . value = '0' ; h . form . elements . assistant2Count . value = '' ;
2026-10-23 00:21:53 +08:00
h . run ( "api=async function(url,data,key){__calls.push({url,data,key});throw new Error('断线');};" );
for ( const handler of h . handlers . submit ) await handler ({ preventDefault (){}, target : h . form });
2026-10-24 16:09:45 +08:00
const pending = JSON . parse ( h . saved . get ( h . key )); assert . deepEqual ( pending . data ,{ date : D , assistant1Count : 0 , assistant2Count : null , revision : 1 }); assert . equal ( pending . url , '/api/people-count' ); assert . match ( h . toasts . at ( - 1 ). message , /不要重复记录人数/ );
2026-10-23 00:21:53 +08:00
h . run ( 'api=async function(url,data,key){__calls.push({url,data,key});return __response;};' ); const button = { dataset : { action : 'retry' }, closest (){ return null ;}};
for ( const handler of h . handlers . click ) await handler ({ target : { closest : ()=> button }});
const retries = h . calls . filter ( call => call . data ); assert . equal ( retries . length , 2 ); assert . equal ( retries [ 1 ]. key , pending . key ); assert . deepEqual ( JSON . parse ( JSON . stringify ( retries [ 1 ]. data )), pending . data ); assert . equal ( h . saved . get ( h . key ), undefined ); assert . equal ( h . run ( '__savedDate' ), D );
2026-10-24 16:09:45 +08:00
assert . equal ( h . run ( "peopleCountInput('', '助理1人数',true)" ), null ); assert . equal ( h . run ( "peopleCountInput('1000000','助理2人数',true)" ), 1000000 );
for ( const value of [ - 1 , 0.5 , '1.0' , '1e2' , 1000001 , true ]){ h . context . __bad = value ; assert . throws (()=> h . run ( "peopleCountInput(__bad,'助理1人数',true)" ));}
2026-10-23 00:21:53 +08:00
});
test ( '旧中断请求恢复时省略的助理字段原样省略,不被新页面补成null覆盖' , async ()=>{
const h = harness (), pending = { url : '/api/people-count' , data : { date : D , count : 5 , revision : 4 }, key : randomUUID ()}; h . saved . set ( h . key , JSON . stringify ( pending ));
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 );
});
2026-10-24 16:09:45 +08:00
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 , /0 人/ ); assert . match ( h . historyContent . innerHTML , /未记录/ ); assert . match ( h . historyContent . innerHTML , /已记录 1 天/ ); assert . deepEqual ( h . json ( 'orderBookFilters' ), filters );
h . context . __response = history ( '2026-09-01' , '2026-09-30' ); await h . run ( 'peopleCountHistoryMonth(true)' ); assert . equal ( h . historyForm . elements . from . value , '2026-09-01' ); assert . equal ( h . historyForm . elements . date . value , '2026-09-30' ); assert . equal ( h . calls [ 1 ]. url , '/api/people-count-history?from=2026-09-01&date=2026-09-30' ); assert . deepEqual ( h . json ( 'orderBookFilters' ), filters ); assert . ok ( h . calls . every ( call => call . data === undefined ));
});
test ( '每日人数失败清旧结果并可重查,切范围、关闭或换账号均拒绝迟到回包' , async ()=>{
const h = historyHarness (); h . historyContent . innerHTML = '旧人数' ; h . run ( "api=async function(){throw new Error('<断线>');}" ); await h . run ( 'loadPeopleCountHistory()' ); assert . match ( h . historyContent . innerHTML , /<断线>/ ); assert . match ( h . historyContent . innerHTML , /people-history-retry/ ); assert . doesNotMatch ( h . historyContent . innerHTML , /旧人数/ );
const pending = []; h . context . __pending = pending ; h . run ( 'api=function(){return new Promise(resolve=>__pending.push(resolve));};' ); const first = h . run ( 'loadPeopleCountHistory()' ); h . historyForm . elements . from . value = D ; h . historyForm . elements . date . value = D ; const second = h . run ( 'loadPeopleCountHistory()' ); pending [ 1 ]( history ( D , D )); await second ; const latest = h . historyContent . innerHTML ; pending [ 0 ]( history ( '2026-10-01' , NEXT )); await first ; assert . equal ( h . historyContent . innerHTML , latest );
const closing = h . run ( 'loadPeopleCountHistory()' ); h . run ( 'closePeopleCountHistory()' ); pending [ 2 ]( history ( D , D )); await closing ; assert . equal ( h . historyDialog . open , false ); assert . doesNotMatch ( h . historyContent . innerHTML , /<table/ );
h . historyDialog . open = true ; const switching = h . run ( 'loadPeopleCountHistory()' ); h . run ( "session.user={id:'new-user'};state.user=session.user;" ); pending [ 3 ]( history ( D , D )); await switching ; assert . doesNotMatch ( h . historyContent . innerHTML , /<table/ );
});