'use strict'; const { test } = require('node:test'), assert = require('node:assert/strict'); const { randomUUID, createHash } = require('node:crypto'), fs = require('node:fs'), os = require('node:os'), path = require('node:path'); const { Ledger, today } = require('../ledger'), { createApp, createUser } = require('../server'); const owner = { id: 'people-owner', name: '测试麦麦', role: 'owner' }, assistant = { id: 'people-assistant', name: '测试助理', role: 'assistant' }; 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, 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; }; function fixture(t) { const ledger = new Ledger(':memory:'); t.after(() => ledger.close()); const write = (input, actor = owner, key = randomUUID()) => ledger.transact(key, actor, input, () => ledger.savePeopleCount(input, actor)); const save = (date, count, revision, actor = owner, key = randomUUID()) => { return write({ date, count, revision }, actor, key); }; return { ledger, save, write }; } function contents(ledger, tables) { return JSON.stringify(tables.map(table => [table, ledger.rows('SELECT * FROM "' + table + '"')])); } function allContents(ledger) { return contents( ledger, ledger.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(row => row.name), ); } test('每日人数区分未登记与0,按日期保存总数而非累加,双方修改保留版本和审计', t => { const f = fixture(t); assert.deepEqual(f.ledger.peopleCount(D), entry(D, null, 0)); assert.deepEqual(f.save(D, 0, 0, assistant), entry(D, 0, 1)); const initial = f.ledger.one('SELECT * FROM daily_people_counts WHERE date=?', D); assert.equal(initial.actor, assistant.name); assert.equal(initial.revision, 1); assert.equal(initial.count, 0); assert.deepEqual(f.save(D, 15, 1, owner), entry(D, 15, 2)); assert.deepEqual(f.save(D, 4, 2, assistant), entry(D, 4, 3)); assert.equal(f.ledger.rows('SELECT * FROM daily_people_counts').length, 1); const record = f.ledger.one('SELECT * FROM daily_people_counts WHERE date=?', D); assert.equal(record.created, initial.created); assert.ok(record.updated >= initial.updated); assert.equal(record.actor, assistant.name); assert.deepEqual(f.ledger.peopleCount(D), entry(D, 4, 3)); assert.deepEqual(f.ledger.peopleCount(D2), entry(D2, null, 0)); const audits = f.ledger.rows('SELECT * FROM audit WHERE entity=? ORDER BY id', 'people-count:' + D); assert.equal(audits.length, 3); assert.deepEqual( audits.map(row => JSON.parse(row.detail).previousCount), [null, 0, 15], ); assert.deepEqual( audits.map(row => JSON.parse(row.detail).count), [0, 15, 4], ); }); test('人数拒绝空白、负数、非整数、超限、非法日期和非法版本,失败不改已有记录', t => { const f = fixture(t), before = allContents(f.ledger); for (const count of [ '', undefined, null, ' ', true, false, [], {}, '-1', '1.5', '1.0', '1e2', 'NaN', Infinity, NaN, 1000001, Number.MAX_SAFE_INTEGER + 1, ]) assert.throws(() => f.save(D, count, 0)); for (const date of ['', undefined, null, '2026-02-30', '2026-9-30', '1999-12-31', '2099-01-01']) assert.throws(() => f.save(date, 1, 0)); for (const revision of [undefined, null, -1, 1.5, '0', Number.MAX_SAFE_INTEGER + 1]) assert.throws(() => f.save(D, 1, revision)); assert.throws(() => f.ledger.savePeopleCount(null, owner)); assert.throws(() => f.ledger.savePeopleCount([], owner)); assert.throws(() => f.save(D, 1, 0, { ...owner, role: 'customer' }), /麦麦或助理账号/); assert.equal(allContents(f.ledger), before); assert.deepEqual(f.save(D, '1000000', 0), entry(D, 1000000, 1)); const existing = allContents(f.ledger); assert.throws(() => f.save(D, 9, 0), { status: 409 }); assert.throws(() => f.save(D2, 9, 1), { status: 409 }); assert.equal(allContents(f.ledger), existing); }); test('人数操作幂等只保存一次,旧版本不能覆盖新记录,操作号内容或用户改变会冲突', t => { const f = fixture(t), key = randomUUID(), first = f.save(D, 7, 0, assistant, key); assert.deepEqual(f.save(D, 7, 0, assistant, key), first); assert.equal(f.ledger.peopleCount(D).revision, 1); assert.equal(f.ledger.rows('SELECT * FROM audit').length, 1); assert.equal(f.ledger.rows('SELECT * FROM operations').length, 1); assert.throws(() => f.save(D, 8, 0, assistant, key), { status: 409 }); assert.throws(() => f.save(D, 7, 0, owner, key), { status: 409 }); f.save(D, 12, 1, owner); const before = allContents(f.ledger); assert.throws(() => f.save(D, 3, 1, assistant), { status: 409 }); assert.equal(allContents(f.ledger), before); assert.deepEqual(f.ledger.peopleCount(D), entry(D, 12, 2)); }); test('助理两项独立于原人数,空白未记录与0区分,旧请求缺省保留且显式null可清空', t => { const f = fixture(t), first = { date: D, count: 3, assistant1Count: 100, assistant2Count: 0, revision: 0 }, key = randomUUID(); assert.deepEqual(f.write(first, assistant, key), entry(D, 3, 1, 100, 0)); assert.deepEqual(f.save(D, 9, 1), entry(D, 9, 2, 100, 0)); assert.deepEqual(f.write({ date: D, count: 9, assistant1Count: null, revision: 2 }), entry(D, 9, 3, null, 0)); assert.deepEqual( f.write({ date: D, count: 9, assistant1Count: '0', assistant2Count: ' ', revision: 3 }), entry(D, 9, 4, 0, null), ); const before = allContents(f.ledger); assert.deepEqual(f.write(first, assistant, key), entry(D, 3, 1, 100, 0)); assert.equal(allContents(f.ledger), before, '中断重试返回原结果,不能覆盖后来保存的三项'); const audit = JSON.parse(f.ledger.rows('SELECT detail FROM audit ORDER BY id DESC LIMIT 1')[0].detail); assert.deepEqual([audit.previousCount, audit.previousAssistant1Count, audit.previousAssistant2Count], [9, null, 0]); assert.deepEqual([audit.count, audit.assistant1Count, audit.assistant2Count], [9, 0, null]); assert.equal(f.ledger.rows('SELECT * FROM daily_people_counts').length, 1); }); test('新请求省略原人数只更新两位助理,新日兼容0且旧日原值保留,不由分项求和', t => { const f = fixture(t), input = { date: D, assistant1Count: 8, assistant2Count: 0, revision: 0 }, key = randomUUID(); assert.deepEqual(f.write(input, assistant, key), entry(D, 0, 1, 8, 0)); assert.equal(f.ledger.one('SELECT count FROM daily_people_counts WHERE date=?', D).count, 0); f.save(D2, 47, 0); assert.deepEqual( f.write({ date: D2, assistant1Count: 10, assistant2Count: 12, revision: 1 }), entry(D2, 47, 2, 10, 12, 8, 0), ); assert.deepEqual( f.write({ date: D2, assistant1Count: null, assistant2Count: ' ', revision: 2 }), entry(D2, 47, 3, null, null, 8, 0), ); assert.deepEqual(f.write({ date: D2, assistant1Count: 0, revision: 3 }), entry(D2, 47, 4, 0, null, 8, 0)); const before = allContents(f.ledger); assert.deepEqual(f.write(input, assistant, key), entry(D, 0, 1, 8, 0)); assert.equal(allContents(f.ledger), before); assert.throws(() => f.write({ date: D2, assistant2Count: 3, revision: 3 }), { status: 409 }); assert.throws(() => f.write({ date: D2, count: null, assistant2Count: 3, revision: 4 }), /人数/); assert.equal(allContents(f.ledger), before); const audit = JSON.parse( f.ledger.one('SELECT detail FROM audit WHERE entity=? ORDER BY id DESC LIMIT 1', 'people-count:' + D2).detail, ); assert.equal(audit.count, 47); assert.equal(audit.previousCount, 47); assert.deepEqual(f.ledger.peopleCountSummary(D2, D), aggregate(D, D2, 47, 2, part(0, 2), part(null, 1))); }); 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, 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); }); test('每日人数默认本月至今天,含366天边界、同一天和空日,非法或过大日期范围不读写', t => { const f = fixture(t), current = today(), result = f.ledger.peopleCountHistory(); assert.equal(result.from, current.slice(0, 7) + '-01'); assert.equal(result.date, current); assert.equal(result.rows.at(-1).date, current); assert.ok( result.rows.every(row => row.date <= current && row.assistant1Count === null && row.assistant2Count === null), ); assert.deepEqual(result.summary, { assistant1: part(), assistant2: part() }); assert.equal(f.ledger.peopleCountHistory({ from: '2024-01-01', date: '2024-12-31' }).rows.length, 366); assert.deepEqual(f.ledger.peopleCountHistory({ from: D, date: D }).rows, [historyEntry(D)]); const before = allContents(f.ledger); for (const query of [ { from: '2024-01-01', date: '2025-01-01' }, { from: D2, date: D }, { from: '2023-02-29', date: '2023-03-01' }, { from: '', date: D }, { from: D, date: '2099-01-01' }, { from: '1999-12-31', date: D }, ]) assert.throws(() => f.ledger.peopleCountHistory(query), { status: 400 }); assert.equal(allContents(f.ledger), before); }); test('助理人数只接受空白null或范围内整数,非法任一项和并发旧版本全部不写入', t => { const f = fixture(t); f.write({ date: D, count: 7, assistant1Count: 1, assistant2Count: 2, revision: 0 }); const before = allContents(f.ledger); for (const name of ['assistant1Count', 'assistant2Count']) for (const value of [ undefined, true, false, [], {}, '-1', '0.1', '1.0', '1e3', Infinity, NaN, 1000001, Number.MAX_SAFE_INTEGER + 1, ]) assert.throws(() => f.write({ date: D, count: 9, [name]: value, revision: 1 })); assert.throws(() => f.write({ date: D, count: '', assistant1Count: 0, assistant2Count: 0, revision: 1 }), /人数/); assert.throws(() => f.write({ date: D, count: 9, assistant1Count: 0, assistant2Count: 0, revision: 0 }), { status: 409, }); assert.equal(allContents(f.ledger), before); assert.deepEqual( f.write({ date: D, count: 1000000, assistant1Count: 1000000, assistant2Count: 1000000, revision: 1 }), entry(D, 1000000, 2, 1000000, 1000000), ); }); test('日月显示期末总人数和端点净增,统计已记录天数且不受订单筛选影响', t => { const f = fixture(t); f.write({ date: D, count: 3, assistant1Count: 0, assistant2Count: null, revision: 0 }); f.write({ date: D2, count: 0, assistant1Count: null, assistant2Count: 5, revision: 0 }); f.write({ date: D3, count: 4, assistant1Count: 7, assistant2Count: 0, revision: 0 }); const expected = aggregate(D, D3, 4, 3, part(7, 2), part(0, 2)); 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, 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 => { const f = fixture(t); f.save(D, 3, 0); f.save(D2, 0, 0); f.save(D3, 4, 0); const expected = aggregate(D, D3, 4, 3); for (const query of [ {}, { q: '不存在' }, { status: 'after_sale' }, { status: 'draft' }, { q: '售后', status: 'delivered' }, ]) { const b = f.ledger.orderBook({ from: D, date: D3, ...query }); assert.deepEqual(b.peopleCount, expected); assert.equal(b.summary.recordCount, 0); assert.equal(b.summary.profit, 0); } assert.deepEqual(f.ledger.reportByOrderDate(D3, D).peopleCount, expected); assert.deepEqual(f.ledger.orderBook({ date: D2 }).peopleCount, aggregate(D2, D2, 0, 1)); assert.deepEqual( f.ledger.orderBook({ date: '2026-09-29' }).peopleCount, aggregate('2026-09-29', '2026-09-29', null, 0), ); assert.deepEqual(f.ledger.orderBook({ from: '2026-09-01', date: D }).peopleCount, aggregate('2026-09-01', D, 3, 1)); assert.deepEqual(f.ledger.orderBook({ from: D2, date: D3 }).peopleCount, aggregate(D2, D3, 4, 2)); }); 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); assert.equal(f.ledger.peopleCount(D3).assistant1Change, -3); assert.equal(f.ledger.peopleCount(D3).assistant2Change, -3); const summary = f.ledger.peopleCountSummary(D3, D2); assert.equal(summary.assistant1.endTotal, 105); assert.equal(summary.assistant1.baselineTotal, 100); assert.equal(summary.assistant1.netChange, 5); assert.notEqual(summary.assistant1.total, 213); assert.equal(summary.assistant2.netChange, 0); const history = f.ledger.peopleCountHistory({ from: D2, date: D3 }); assert.equal(history.rows[0].assistant1Change, 8); assert.equal(history.rows[1].assistant1Change, -3); assert.deepEqual(history.summary.assistant1, summary.assistant1); const last = JSON.stringify(f.ledger.one('SELECT * FROM daily_people_counts WHERE date=?', D3)); f.write({ date: D2, assistant1Count: 110, revision: 1 }); assert.equal(f.ledger.peopleCount(D2).assistant1Change, 10); assert.equal(f.ledger.peopleCount(D3).assistant1Change, -5); assert.equal(f.ledger.peopleCountSummary(D3, D2).assistant1.netChange, 5); assert.equal( JSON.stringify(f.ledger.one('SELECT * FROM daily_people_counts WHERE date=?', D3)), last, '派生次日变化不重写次日原记录', ); assert.deepEqual(f.write(input, owner, key), first); assert.equal(f.ledger.peopleCount(D2).assistant1Count, 110); }); 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, 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'); const missingEnd = f.ledger.peopleCountSummary(D2, D2); assert.equal(missingEnd.assistant1.baselineTotal, 100); assert.equal(missingEnd.assistant1.netChange, null); assert.equal(missingEnd.assistant1.netChangeReason, 'missing-current'); assert.equal(f.ledger.peopleCount('2026-09-29').assistant1ChangeReason, 'missing-both'); }); 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); const history = f.ledger.peopleCountHistory({ from: '2024-02-29', date: '2024-03-01' }); assert.equal(history.baselineDate, '2024-02-28'); assert.deepEqual( history.rows.map(row => row.assistant1Change), [-2, 3], ); assert.equal(history.summary.assistant1.netChange, 1); assert.equal(f.ledger.peopleCountSummary('2000-01-01').assistant1.baselineTotal, null); }); test('人数登记修改不改变销售成本利润、收款、库存、财务版本、核对快照或同步', t => { const f = fixture(t), input = { date: D, customer: '合成客户', salesperson: '合成开单人', lines: [{ name: '合成商品', unit: 'g', quantity: '1', pocket: '', payer: 'owner', cost: '80', sale: '100' }], fee_items: [], }; f.ledger.transact(randomUUID(), owner, input, () => f.ledger.issueOrder(input, owner)); f.ledger.transact(randomUUID(), owner, { date: D }, () => f.ledger.closeDay(D, owner, 'orderDate')); const tables = [ 'orders', 'payments', 'expenses', 'after_sales', 'settlements', 'movements', 'journal', 'meta', 'sync', 'closes', 'inventory_snapshots', ], before = contents(f.ledger, tables), r = f.ledger.reportByOrderDate(D), book = f.ledger.orderBook({ date: D }); f.save(D, 20, 0); f.write({ date: D, assistant1Count: 0, assistant2Count: 7, revision: 1 }, assistant); f.write({ date: D2, assistant1Count: 100, assistant2Count: null, revision: 0 }); assert.equal(contents(f.ledger, tables), before); const after = f.ledger.reportByOrderDate(D); assert.equal(after.reportRevision, r.reportRevision); assert.equal(after.close.stale, false); assert.equal(f.ledger.report(D).close.stale, false); assert.equal(f.ledger.inventorySnapshot(D).stale, false); assert.deepEqual(after.summary, r.summary); assert.deepEqual(after.orderRows, r.orderRows); assert.deepEqual(after.accounts, r.accounts); assert.deepEqual(after.payerCosts, r.payerCosts); assert.deepEqual(f.ledger.orderBook({ date: D }).summary, book.summary); assert.deepEqual(after.peopleCount, aggregate(D, D, 20, 1, part(0, 1), part(7, 1))); const readBefore = allContents(f.ledger), changes = f.ledger.one('SELECT total_changes() AS count').count; f.ledger.peopleCount(D); f.ledger.peopleCount(D3); f.ledger.peopleCountSummary(D3, D); f.ledger.orderBook({ date: D }); f.ledger.reportByOrderDate(D); assert.equal(allContents(f.ledger), readBefore); assert.equal(f.ledger.one('SELECT total_changes() AS count').count, changes); }); test('旧库增量建人数表,0与版本重启后保留,重试不再覆盖新总人数', t => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-people-persist-')), filename = path.join(dir, 'ledger.sqlite'); let ledger = new Ledger(filename); t.after(() => { try { ledger.close(); } catch {} fs.rmSync(dir, { recursive: true, force: true }); }); ledger.setMeta('synthetic-existing', 7); ledger.db.exec('DROP TABLE daily_people_counts'); ledger.close(); ledger = new Ledger(filename); assert.equal(ledger.meta('synthetic-existing'), 7); assert.deepEqual(ledger.peopleCount(D), entry(D, null, 0)); const value = { date: D, count: 0, revision: 0 }, key = randomUUID(), result = ledger.transact(key, owner, value, () => ledger.savePeopleCount(value, owner)); ledger.close(); ledger = new Ledger(filename); assert.deepEqual(ledger.peopleCount(D), entry(D, 0, 1)); assert.deepEqual( ledger.transact(key, owner, value, () => ledger.savePeopleCount(value, owner)), result, ); const changed = { date: D, count: 11, revision: 1 }; ledger.transact(randomUUID(), assistant, changed, () => ledger.savePeopleCount(changed, assistant)); assert.deepEqual( ledger.transact(key, owner, value, () => ledger.savePeopleCount(value, owner)), result, ); assert.deepEqual(ledger.peopleCount(D), entry(D, 11, 2)); assert.deepEqual(ledger.peopleCount(D2), entry(D2, null, 0)); }); test('已有原人数的旧表增量加两列NULL,原列原值和历史操作结果逐字保留,重开不回填助理', t => { const { DatabaseSync } = require('node:sqlite'), { createHash } = require('node:crypto'); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-people-columns-')), filename = path.join(dir, 'ledger.sqlite'); t.after(() => fs.rmSync(dir, { recursive: true, force: true })); const old = new DatabaseSync(filename); old.exec( 'CREATE TABLE daily_people_counts(date TEXT PRIMARY KEY,count INTEGER NOT NULL CHECK(count>=0 AND count<=1000000),revision INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,updated TEXT NOT NULL)', ); old .prepare('INSERT INTO daily_people_counts VALUES (?,?,?,?,?,?)') .run(D, 0, 4, '旧录入人', '2026-09-30T01:00:00.000Z', '2026-09-30T02:00:00.000Z'); old .prepare('INSERT INTO daily_people_counts VALUES (?,?,?,?,?,?)') .run(D2, 17, 2, '另一旧录入人', '2026-10-01T01:00:00.000Z', '2026-10-01T01:00:00.000Z'); const rows = old.prepare('SELECT * FROM daily_people_counts ORDER BY date').all(), key = randomUUID(), payload = { date: D, count: 0, revision: 3 }, oldResult = { date: D, count: 0, revision: 4 }; old.exec('CREATE TABLE operations(id TEXT PRIMARY KEY,hash TEXT NOT NULL,result TEXT NOT NULL)'); old.prepare('INSERT INTO operations VALUES (?,?,?)').run( key, createHash('sha256') .update(JSON.stringify({ actor: owner.id, payload })) .digest('hex'), JSON.stringify(oldResult), ); old.close(); let ledger = new Ledger(filename); try { assert.deepEqual( ledger.rows('SELECT date,count,revision,actor,created,updated FROM daily_people_counts ORDER BY date'), rows, ); assert.deepEqual(ledger.peopleCount(D), entry(D, 0, 4)); assert.deepEqual(ledger.peopleCount(D2), entry(D2, 17, 2)); assert.deepEqual( ledger.transact(key, owner, payload, () => ledger.savePeopleCount(payload, owner)), oldResult, ); ledger.transact(randomUUID(), owner, {}, () => ledger.savePeopleCount({ date: D, count: 0, assistant1Count: 0, assistant2Count: 8, revision: 4 }, owner), ); assert.deepEqual( ledger.transact(key, owner, payload, () => ledger.savePeopleCount(payload, owner)), oldResult, ); } finally { ledger.close(); } ledger = new Ledger(filename); try { assert.deepEqual(ledger.peopleCount(D), entry(D, 0, 5, 0, 8)); assert.deepEqual(ledger.peopleCount(D2), entry(D2, 17, 2, null, null, 0, 8)); assert.equal(ledger.one('PRAGMA integrity_check').integrity_check, 'ok'); } finally { ledger.close(); } }); test('HTTP人数须登录与CSRF,老板可维护分项、员工不可访问,相同版本并发只成功一笔,GET不补造记录', async t => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-people-http-')), app = createApp({ mode: 'demo', dataDir: dir, ledger: new Ledger(':memory:'), 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.closeAllConnections(); app.server.close(resolve); }); app.ledger.close(); fs.rmSync(dir, { recursive: true, force: true }); }); const base = 'http://127.0.0.1:' + app.server.address().port; let cookie = ''; const call = (route, data, key = randomUUID(), origin = base) => fetch(base + route, { method: data ? 'POST' : 'GET', headers: { ...(cookie ? { Cookie: cookie } : {}), ...(data ? { 'Content-Type': 'application/json', Origin: origin, 'X-Requested-With': 'maimai-ledger', 'Idempotency-Key': key, } : {}), }, ...(data ? { body: JSON.stringify(data) } : {}), }); assert.equal((await call('/api/people-count?date=' + D)).status, 401); assert.equal((await call('/api/people-count', { date: D, count: 0, revision: 0 })).status, 401); assert.equal((await call('/api/people-count-history?from=' + D + '&date=' + D3)).status, 401); let login = await call('/api/demo-login', { role: 'owner' }); cookie = login.headers.get('set-cookie').split(';')[0]; assert.deepEqual(await (await call('/api/people-count')).json(), wireEntry(today(), null, 0)); assert.equal(app.ledger.rows('SELECT * FROM daily_people_counts').length, 0); for (const date of ['2099-01-01', '2026-02-30', '']) assert.equal((await call('/api/people-count?date=' + date)).status, 400); assert.equal( (await call('/api/people-count', { date: D, count: 0, revision: 0 }, randomUUID(), 'https://invalid.example')) .status, 403, ); assert.equal((await call('/api/people-count', { date: D, count: 1 })).status, 400); assert.equal((await call('/api/people-count', { date: D, count: 1.5, revision: 0 })).status, 400); const key = randomUUID(), retries = await Promise.all([ call('/api/people-count', { date: D, count: 0, revision: 0 }, key), call('/api/people-count', { date: D, count: 0, revision: 0 }, key), ]); assert.deepEqual( retries.map(r => r.status), [200, 200], ); const first = await retries[0].json(); assert.deepEqual(await retries[1].json(), first); assert.deepEqual(first, wireEntry(D, 0, 1)); const writes = await Promise.all([ call('/api/people-count', { date: D, count: 5, revision: 1 }), call('/api/people-count', { date: D, count: 7, revision: 1 }), ]); assert.deepEqual(writes.map(r => r.status).sort(), [200, 409]); const saved = await writes.find(r => r.status === 200).json(); assert.equal(saved.revision, 2); assert.deepEqual(await (await call('/api/people-count?date=' + D)).json(), saved); assert.equal(app.ledger.rows('SELECT * FROM daily_people_counts').length, 1); assert.equal(app.ledger.rows('SELECT * FROM audit WHERE entity=?', 'people-count:' + D).length, 2); login = await call('/api/demo-login', { role: 'owner' }); cookie = login.headers.get('set-cookie').split(';')[0]; const ownerWrite = await call('/api/people-count', { date: D, count: 0, revision: 2 }); assert.equal(ownerWrite.status, 200); assert.deepEqual(await ownerWrite.json(), wireEntry(D, 0, 3)); assert.equal((await call('/api/people-count', { date: D, count: 20, revision: 2 })).status, 409); const book = await (await call('/api/order-book?date=' + D + '&q=none&status=after_sale')).json(); assert.deepEqual(book.peopleCount, wireAggregate(D, D, 0, 1)); const report = await (await call('/api/report?date=' + D + '&basis=orderDate')).json(); assert.deepEqual(report.peopleCount, book.peopleCount); assert.equal(report.profit, 0); const independent = await call('/api/people-count', { date: D, count: 0, assistant1Count: 8, assistant2Count: 0, revision: 3, }); assert.deepEqual(await independent.json(), wireEntry(D, 0, 4, 8, 0)); const legacyWrite = await call('/api/people-count', { date: D, count: 12, revision: 4 }); assert.deepEqual(await legacyWrite.json(), wireEntry(D, 12, 5, 8, 0)); const cleared = await call('/api/people-count', { date: D, count: 12, assistant1Count: null, assistant2Count: '', revision: 5, }); assert.deepEqual(await cleared.json(), wireEntry(D, 12, 6)); const splitKey = randomUUID(), split = { date: D, assistant1Count: 0, assistant2Count: 9, revision: 6 }; const savedSplit = await call('/api/people-count', split, splitKey); assert.equal(savedSplit.status, 200); assert.deepEqual(await savedSplit.json(), wireEntry(D, 12, 7, 0, 9)); assert.deepEqual(await (await call('/api/people-count', split, splitKey)).json(), wireEntry(D, 12, 7, 0, 9)); const newDay = await call('/api/people-count', { date: D2, assistant1Count: null, assistant2Count: 0, revision: 0 }); assert.equal(newDay.status, 200); assert.deepEqual(await newDay.json(), wireEntry(D2, 0, 1, null, 0, 0, 9)); for (const role of ['owner', 'assistant', 'assistant2']) { login = await call( '/api/demo-login', role === 'assistant2' ? { role: 'assistant', member: 'assistant2' } : { role }, ); cookie = login.headers.get('set-cookie').split(';')[0]; const before = allContents(app.ledger), response = await call('/api/people-count-history?from=' + D + '&date=' + D3); if (role === 'owner') { assert.equal(response.status, 200); const history = await response.json(); assert.equal(history.rows.length, 3); assert.deepEqual(history.summary, { assistant1: part(null, 1), assistant2: part(null, 2) }); assert.equal((await call('/api/people-count-history?from=2024-01-01&date=2025-01-01')).status, 400); } else { assert.equal(response.status, 403); assert.equal((await call('/api/people-count?date=' + D2)).status, 403); assert.equal((await call('/api/people-count', { date: D2, assistant1Count: 1, revision: 1 })).status, 403); for (const route of [ '/api/order-book?from=' + D + '&date=' + D3, '/api/report?from=' + D + '&date=' + D3 + '&basis=orderDate', ]) assert.equal((await (await call(route)).json()).peopleCount, null); } assert.equal(allContents(app.ledger), before); } }); test('员工旧人数幂等回执也拒绝读取,缓存与原写入不改', async t => { const l = new Ledger(':memory:'), actors = {}, samples = []; for (const member of ['owner', 'assistant', 'assistant2']) { const role = member === 'owner' ? 'owner' : 'assistant', id = createUser(l, member, role, 'synthetic-replay-password', member); actors[member] = { id, name: member, role, member }; } for (const [member, date, assistant1Count, assistant2Count] of [ ['assistant', D, 100, 432109], ['assistant2', D2, 876543, 200], ]) { const body = { date, count: 17, assistant1Count, assistant2Count, revision: 0 }, key = randomUUID(), payload = { route: '/api/people-count', body }; const result = l.transact(key, actors[member], payload, () => l.savePeopleCount(body, actors[member])); const cached = member === 'assistant2' ? { date, count: 17, assistant1Count, assistant2Count, revision: result.revision } : result; l.run('UPDATE operations SET result=? WHERE id=?', JSON.stringify(cached), key); samples.push({ member, date, body, key, result: cached }); } l.savePeopleCount({ date: D, assistant1Count: 111, revision: 1 }, actors.owner); const errorBody = { date: D3, assistant1Count: 5, revision: 0 }, errorKey = randomUUID(), errorPayload = { route: '/api/people-count', body: errorBody }; l.run( 'INSERT INTO operations VALUES (?,?,?)', errorKey, createHash('sha256') .update(JSON.stringify({ actor: actors.assistant.id, payload: errorPayload })) .digest('hex'), JSON.stringify({ date: D3, revision: 1, error: '合成旧错误,不能当成功', assistant2Count: 432109 }), ); const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'maimai-people-replay-')), 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.closeAllConnections(); 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 login = async member => { const response = await call('/api/login', '', { name: member, password: 'synthetic-replay-password' }); assert.equal(response.status, 200); return response.headers.get('set-cookie').split(';')[0]; }; const tables = [ 'daily_people_counts', 'operations', 'audit', 'orders', 'payments', 'expenses', 'journal', 'movements', 'team_fund_cash', ], before = contents(l, tables); for (const sample of samples) { const cookie = await login(sample.member); assert.equal((await call('/api/people-count', cookie, sample.body, sample.key)).status, 403); assert.equal((await call('/api/people-count?date=' + D, cookie)).status, 403); } const cookie = await login('assistant'); assert.equal((await call('/api/people-count', cookie, errorBody, errorKey)).status, 403); assert.equal(contents(l, tables), before, '拒绝访问不改原operations、人数或账务'); }); test('员工不能通过旧人数、订单簿或日报取得总数和基准日期', 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.closeAllConnections(); 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) } : {}), }); for (const member of ['assistant', 'assistant2']) { const login = await call('/api/login', '', { name: member, password: 'synthetic-last-date-password' }), cookie = login.headers.get('set-cookie').split(';')[0]; assert.equal((await call('/api/people-count', cookie, { date, assistant1Count: 8212, revision: 0 })).status, 403); for (const route of ['/api/people-count?date=' + date, '/api/people-count-history?from=2026-10-01&date=' + date]) assert.equal((await call(route, cookie)).status, 403); for (const route of [ '/api/order-book?from=2026-10-01&date=' + date, '/api/report?from=2026-10-01&date=' + date + '&basis=orderDate', ]) { const response = await call(route, cookie); assert.equal(response.status, 200); assert.equal((await response.json()).peopleCount, null); } } });