'use strict'; const { createBrowserContext } = require('./fixtures/browser-context.cjs'); 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 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, 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, }; 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-preview', { innerHTML: '' }], ['#people-count-error', { innerHTML: '' }], ['#pending', { hidden: true, innerHTML: '' }], ]) nodes.set(name, node); const context = createBrowserContext({ 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, }; } 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 = []; let previous1 = null, previous2 = 5, previousDate1 = null, previousDate2 = previousDate(from); for (let i = 0; i < days; i++) { const day = new Date(Date.parse(from) + i * 86400000).toISOString().slice(0, 10), entry = record( day, 99, 0, i === 0 ? 0 : null, i === days - 1 ? 8 : null, previous1, previous2, previousDate1, previousDate2, ); delete entry.count; delete entry.revision; rows.push(entry); if (entry.assistant1Count !== null) { previous1 = entry.assistant1Count; previousDate1 = day; } if (entry.assistant2Count !== null) { previous2 = entry.assistant2Count; previousDate2 = day; } } return { from, date, today: NEXT, baselineDate: previousDate(from), mode: 'daily-total', rows, summary: { assistant1: period(rows.at(-1).assistant1Count, null, 1), assistant2: period(8, 5, 1, previousDate(from)), }, }; } test('人数只显示期末总数和端点净变化,不显示每日总数SUM及旧count', async () => { const h = harness(); await h.run('showPeopleCountForm()'); const html = h.dialog.innerHTML; assert.doesNotMatch(html, /name="count"/); assert.match(html, /娜娜当日总人数/); assert.match(html, /小昊当日总人数/); 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, previousDate(D)), total: 999 }, assistant2: period(9, 5, 2, previousDate(D)), }; const lines = h.json('peopleCountReportLines(__summary)'); assert.match(lines[0], /娜娜结束日总人数:0 人(已记录) · 本期净增 0 人/); assert.match(lines[1], /小昊结束日总人数: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, 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,首次记录不把总人数当新增', 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 人/); }); 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 人/); 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, /未完整返回/); h.context.__good = record(NEXT, 999, 3, 0, null); h.run('api=async function(){return __good;};'); 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, ''); }); test('只提交两位助理,校验整数边界与空白null,断网恢复保留原操作号且不补旧count', async () => { const h = harness(); await h.run('loadPeopleCount()'); h.form.elements.assistant1Count.value = '0'; h.form.elements.assistant2Count.value = ''; 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 }); 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, /不要重复记录人数/); 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); assert.equal(h.run("peopleCountInput('', '娜娜人数',true)"), null); assert.equal(h.run("peopleCountInput('1000000','小昊人数',true)"), 1000000); for (const value of [-1, 0.5, '1.0', '1e2', 1000001, true]) { h.context.__bad = value; assert.throws(() => h.run("peopleCountInput(__bad,'娜娜人数',true)")); } }); 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); }); 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, /娜娜/); assert.match(h.historyContent.innerHTML, /小昊/); 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, 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; let html = h.run('peopleCountHistoryHTML(__history)'); assert.match(html, /已记录 2 天/); assert.match(html, /2026-10-20<\/td>0 人/); assert.match(html, /未记录/); h.run("state.user={...state.user,role:'assistant',member:'assistant2'};"); html = h.run('peopleCountHistoryHTML(__history)'); assert.match(html, /已记录 1 天/); assert.match(html, /2026-10-22<\/td>/); assert.doesNotMatch(html, /2026-10-20<\/td>|娜娜/); result.rows[2].assistant2Count = undefined; html = h.run('peopleCountHistoryHTML(__history)'); assert.match(html, /已记录 0 天/); assert.match(html, /所选日期暂无人数记录/); assert.doesNotMatch(html, /\d{4}-\d{2}-\d{2}<\/td>/); result.rows.forEach(row => { row.assistant1Count = null; row.assistant2Count = null; }); h.run("state.user={...state.user,role:'owner',member:'owner'};"); html = h.run('peopleCountHistoryHTML(__history)'); assert.match(html, /已记录 0 天/); assert.match(html, /所选日期暂无人数记录/); assert.match(html, /期末/本期变化/); assert.doesNotMatch(html, /\d{4}-\d{2}-\d{2}<\/td>/); }); 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, /