diff --git a/web/src/lib/app.test.ts b/web/src/lib/app.test.ts new file mode 100644 index 0000000..7772c2c --- /dev/null +++ b/web/src/lib/app.test.ts @@ -0,0 +1,182 @@ +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + addAdjustment, + addSettings, + autoStopStale, + balance, + currentSettings, + createInterval, + deleteSettings, + entriesForDay, + runningEntry, + settingsHistory, + startEntry, + stopEntry, + todayKey +} from './app.svelte'; +import { closeDb, get, openDb, remove, save, status } from './db.svelte'; +import { DEFAULT_SETTINGS } from './types'; + +const mocks = vi.hoisted(() => { + const server = new Map>>(); + let tick = 0; + return { + server, + stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ') + }; +}); + +vi.mock('$lib/pb', () => ({ + pb: { + autoCancellation: () => undefined, + filter: (tpl: string, params: Record) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))), + collection: (name: string) => ({ + getFullList: async () => [...(mocks.server.get(name)?.values() ?? [])], + subscribe: async () => async () => undefined + }), + send: async (path: string, options: { method?: string; body?: unknown }) => { + if (path !== '/api/sync/push' || options.method !== 'POST') return {}; + const body = options.body as { changes: { collection: string; id: string; data: Record; client_updated_at: number; deleted: boolean }[] }; + const results = body.changes.map((c) => { + const record = { id: c.id, ...c.data, client_updated_at: c.client_updated_at, rev: 1, deleted: c.deleted, updated: mocks.stamp() }; + let store = mocks.server.get(c.collection); + if (!store) { + store = new Map(); + mocks.server.set(c.collection, store); + } + store.set(c.id, record); + return { id: c.id, collection: c.collection, status: 'ok', record }; + }); + return { results }; + } + } +})); + +let n = 0; +const row = (effective_from: string, hours_per_week: number) => ({ effective_from, hours_per_week, workdays_mask: 31, timezone: 'UTC' }); + +beforeEach(async () => { + status.online = false; + await openDb(`app-user-${++n}`); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +afterAll(async () => { + await closeDb(); +}); + +describe('settings', () => { + it('currentSettings picks the greatest effective_from not after the day', async () => { + expect(currentSettings('2026-06-15')).toEqual({ + ...DEFAULT_SETTINGS, + id: '', + client_updated_at: 0, + rev: 0, + deleted: false, + updated: '' + }); + await addSettings(row('2026-01-01', 40)); + await addSettings(row('2026-06-01', 30)); + await addSettings(row('2026-07-01', 20)); + expect(currentSettings('2026-06-15').hours_per_week).toBe(30); + expect(currentSettings('2026-07-15').hours_per_week).toBe(20); + expect(currentSettings('2025-12-31')).toMatchObject({ hours_per_week: 40, id: '' }); + expect(currentSettings().hours_per_week).toBe(20); + expect(settingsHistory().map((s) => s.effective_from)).toEqual(['2026-07-01', '2026-06-01', '2026-01-01']); + }); + + it('addSettings rejects invalid rows', async () => { + await expect(addSettings(row('2026-01-01', 0))).rejects.toThrow('hours_per_week must be greater than 0'); + await expect(addSettings({ ...row('2026-01-01', 40), workdays_mask: 0 })).rejects.toThrow('workdays_mask must be between 1 and 127'); + await expect(addSettings({ ...row('2026-01-01', 40), workdays_mask: 128 })).rejects.toThrow(); + await expect(addSettings(row('01.01.2026', 40))).rejects.toThrow('effective_from must be a date'); + await expect(addSettings({ ...row('2026-01-01', 40), timezone: 'Mars/Olympus' })).rejects.toThrow('unknown timezone'); + expect(settingsHistory()).toHaveLength(0); + }); + + it('deleteSettings refuses the last row', async () => { + const a = await addSettings(row('2026-01-01', 40)); + await expect(deleteSettings(a)).rejects.toThrow('cannot delete the only settings row'); + const b = await addSettings(row('2026-02-01', 32)); + await deleteSettings(a); + expect(settingsHistory().map((s) => s.id)).toEqual([b]); + await expect(deleteSettings(b)).rejects.toThrow('cannot delete the only settings row'); + }); +}); + +describe('time', () => { + it('todayKey uses the settings timezone', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date('2026-06-15T22:30:00Z')); + expect(todayKey()).toBe('2026-06-15'); + await addSettings({ ...row('2026-01-01', 40), timezone: 'Europe/Berlin' }); + expect(todayKey()).toBe('2026-06-16'); + }); +}); + +describe('entries', () => { + it('autoStopStale stops a running entry from yesterday at the end of that day', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date('2026-06-16T10:00:00Z')); + const stale = await save('entries', null, { start_time: Date.parse('2026-06-15T17:00:00Z'), end_time: null, auto_stopped: false, note: '', day_key: '2026-06-15' }); + const today = await save('entries', null, { start_time: Date.parse('2026-06-16T08:00:00Z'), end_time: null, auto_stopped: false, note: '', day_key: '2026-06-16' }); + expect(await autoStopStale()).toBe(1); + expect(entriesForDay('2026-06-15')[0]).toMatchObject({ id: stale, end_time: Date.parse('2026-06-15T23:59:59.999Z'), auto_stopped: true }); + expect(runningEntry()?.id).toBe(today); + expect(await autoStopStale()).toBe(0); + }); + + it('startEntry twice throws an entry is already running', async () => { + await startEntry('first'); + await expect(startEntry('second')).rejects.toThrow('an entry is already running'); + expect(runningEntry()?.note).toBe('first'); + }); + + it('createInterval validates the interval', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date('2026-06-16T10:00:00Z')); + await expect(createInterval(100, 100)).rejects.toThrow('end_time must be after start_time'); + await expect(createInterval(Date.parse('2026-06-15T23:00:00Z'), Date.parse('2026-06-16T01:00:00Z'))).rejects.toThrow( + 'entry end_time must be on the same calendar day as start_time' + ); + await expect(createInterval(Date.parse('2026-06-17T08:00:00Z'), Date.parse('2026-06-17T09:00:00Z'))).rejects.toThrow( + 'intervals cannot be created or edited in the future' + ); + await save('closed_days', null, { day_key: '2026-06-15', worked_ms: 0, kind: 'work', closed_at: 1 }); + await expect(createInterval(Date.parse('2026-06-15T08:00:00Z'), Date.parse('2026-06-15T09:00:00Z'))).rejects.toThrow( + 'day is already closed' + ); + await expect(createInterval(Date.parse('2026-06-16T08:00:00Z'), Date.parse('2026-06-16T09:00:00Z'))).resolves.toMatch(/^[a-z0-9]{15}$/); + }); + + it('stopEntry caps a stale running entry at the end of its day', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(new Date('2026-06-16T10:00:00Z')); + const id = await save('entries', null, { start_time: Date.parse('2026-06-15T17:00:00Z'), end_time: null, auto_stopped: false, note: '', day_key: '2026-06-15' }); + await stopEntry(id); + expect(get('entries', id)).toMatchObject({ end_time: Date.parse('2026-06-15T23:59:59.999Z'), auto_stopped: true }); + await expect(stopEntry(id)).rejects.toThrow('no running entry found'); + }); +}); + +describe('balance', () => { + it('balance sums non-deleted weeks and adjustments', async () => { + await save('closed_weeks', null, { week_key: '2026-W23', expected_ms: 1, worked_ms: 2, delta_ms: 3_600_000, closed_at: 1 }); + await save('closed_weeks', null, { week_key: '2026-W24', expected_ms: 1, worked_ms: 2, delta_ms: -600_000, closed_at: 1 }); + const gone = await save('closed_weeks', null, { week_key: '2026-W25', expected_ms: 1, worked_ms: 2, delta_ms: 999, closed_at: 1 }); + await remove('closed_weeks', gone); + await addAdjustment({ delta_ms: 1_200_000 }); + await addAdjustment({ delta_ms: -300_000, note: 'fix' }); + await expect(addAdjustment({ delta_ms: 0 })).rejects.toThrow('delta_ms must be non-zero'); + expect(balance()).toEqual({ + total_delta_ms: 3_900_000, + weeks_delta_ms: 3_000_000, + adjustments_delta_ms: 900_000, + closed_week_count: 2, + adjustment_count: 2 + }); + }); +}); diff --git a/web/src/lib/db.test.ts b/web/src/lib/db.test.ts new file mode 100644 index 0000000..ca92620 --- /dev/null +++ b/web/src/lib/db.test.ts @@ -0,0 +1,162 @@ +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { all, closeDb, get, openDb, pendingCount, remove, save, status, syncNow, toRecord, update } from './db.svelte'; + +const mocks = vi.hoisted(() => { + const server = new Map>>(); + const pushes: { collection: string; id: string; data: Record; client_updated_at: number; deleted: boolean }[] = []; + const batches: number[] = []; + let tick = 0; + return { + server, + pushes, + batches, + stamp: () => new Date(Date.UTC(2026, 0, 1) + tick++).toISOString().replace('T', ' ') + }; +}); + +vi.mock('$lib/pb', () => ({ + pb: { + autoCancellation: () => undefined, + filter: (tpl: string, params: Record) => tpl.replace(/\{:(\w+)\}/g, (_m, key: string) => JSON.stringify(String(params[key]))), + collection: (name: string) => ({ + getFullList: async () => [...(mocks.server.get(name)?.values() ?? [])], + subscribe: async () => async () => undefined + }), + send: async (path: string, options: { method?: string; body?: unknown }) => { + if (path !== '/api/sync/push' || options.method !== 'POST') return {}; + const body = options.body as { changes: (typeof mocks.pushes)[number][] }; + mocks.batches.push(body.changes.length); + const results = body.changes.map((c) => { + const record = { id: c.id, ...c.data, client_updated_at: c.client_updated_at, rev: 1, deleted: c.deleted, updated: mocks.stamp() }; + let store = mocks.server.get(c.collection); + if (!store) { + store = new Map(); + mocks.server.set(c.collection, store); + } + store.set(c.id, record); + mocks.pushes.push(c); + return { id: c.id, collection: c.collection, status: 'ok', record }; + }); + return { results }; + } + } +})); + +let n = 0; +const settingsRow = { effective_from: '2026-01-01', hours_per_week: 40, workdays_mask: 31, timezone: 'UTC' }; + +beforeEach(async () => { + status.online = false; + await openDb(`user-${++n}`); +}); + +afterAll(async () => { + await closeDb(); +}); + +describe('local collections', () => { + it('save assigns a 15 char id and all returns the record', async () => { + const id = await save('balance_adjustments', null, { delta_ms: 1000, note: 'overtime', effective_at: 5 }); + expect(id).toMatch(/^[a-z0-9]{15}$/); + const rows = all('balance_adjustments'); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ id, delta_ms: 1000, note: 'overtime', effective_at: 5, deleted: false, rev: 0, updated: '' }); + expect(get('balance_adjustments', id)?.note).toBe('overtime'); + expect(get('balance_adjustments', 'nope')).toBeUndefined(); + }); + + it('update patches the data and bumps client_updated_at', async () => { + const id = await save('settings_history', null, settingsRow); + const before = get('settings_history', id)?.client_updated_at ?? 0; + await update('settings_history', id, { hours_per_week: 32.5 }); + const row = get('settings_history', id); + expect(row).toMatchObject({ hours_per_week: 32.5, workdays_mask: 31, timezone: 'UTC', deleted: false }); + expect(row?.client_updated_at).toBeGreaterThanOrEqual(before + 1); + }); + + it('remove hides a record from all but keeps it as deleted', async () => { + const id = await save('entries', null, { start_time: 1, end_time: 2, auto_stopped: false, note: '', day_key: '2026-01-01' }); + await remove('entries', id); + expect(all('entries')).toHaveLength(0); + expect(all('entries', true)).toHaveLength(1); + expect(all('entries', true)[0]).toMatchObject({ id, deleted: true }); + expect(get('entries', id)?.deleted).toBe(true); + }); + + it('data survives closeDb and a second openDb', async () => { + const uid = `user-${n}`; + const id = await save('settings_history', null, settingsRow); + await closeDb(); + expect(status.ready).toBe(false); + expect(all('settings_history')).toEqual([]); + await openDb(uid); + expect(all('settings_history')).toHaveLength(1); + expect(get('settings_history', id)?.hours_per_week).toBe(40); + }); +}); + +describe('sync boundary', () => { + it('toRecord turns end_time 0 into null and coerces the metadata', () => { + const doc = toRecord('entries', { + id: 'abc', + owner: 'u1', + start_time: '10', + end_time: 0, + auto_stopped: 1, + note: null, + day_key: '2026-01-01', + client_updated_at: '7', + rev: null, + deleted: false, + updated: 123, + created: 'x' + }); + expect(doc).toEqual({ + id: 'abc', + start_time: 10, + end_time: null, + auto_stopped: true, + note: '', + day_key: '2026-01-01', + client_updated_at: 7, + rev: 0, + deleted: false, + updated: '123' + }); + }); + + it('toRecord keeps 0 in fields that are not zero-means-null', () => { + expect(toRecord('balance_adjustments', { id: 'a', delta_ms: 0, note: '', effective_at: 0 }).delta_ms).toBe(0); + expect(toRecord('entries', { id: 'a', start_time: 0, end_time: 5, auto_stopped: false, note: '', day_key: '' }).start_time).toBe(0); + }); + + it('a sync round pushes end_time null as 0 and pulls 0 back as null', async () => { + status.online = true; + await save('entries', null, { start_time: 1000, end_time: null, auto_stopped: false, note: 'run', day_key: '1970-01-01' }); + expect(pendingCount()).toBe(1); + await syncNow(); + expect(pendingCount()).toBe(0); + const pushed = mocks.pushes.filter((c) => c.collection === 'entries'); + expect(pushed).toHaveLength(1); + expect(pushed[0].data).toEqual({ start_time: 1000, end_time: 0, auto_stopped: false, note: 'run', day_key: '1970-01-01' }); + expect(pushed[0].deleted).toBe(false); + const row = all('entries')[0]; + expect(row).toMatchObject({ start_time: 1000, end_time: null, note: 'run', deleted: false, rev: 1 }); + expect(row.updated).not.toBe(''); + expect(localStorage.getItem(`wotra-cursor:user-${n}:entries`)).not.toBeNull(); + expect(status.error).toBeNull(); + }); + + it('a sync round pushes in batches below the server limit', async () => { + status.online = true; + mocks.batches.length = 0; + for (let i = 0; i < 250; i++) { + await save('balance_adjustments', null, { delta_ms: i + 1, note: '', effective_at: i }); + } + await syncNow(); + expect(pendingCount()).toBe(0); + expect(mocks.batches.length).toBeGreaterThan(1); + expect(Math.max(...mocks.batches)).toBeLessThanOrEqual(200); + expect(mocks.batches.reduce((sum, size) => sum + size, 0)).toBe(250); + }, 20000); +}); diff --git a/web/src/lib/utils.test.ts b/web/src/lib/utils.test.ts index b7b0cf7..1a0f10c 100644 --- a/web/src/lib/utils.test.ts +++ b/web/src/lib/utils.test.ts @@ -1,5 +1,15 @@ import { describe, it, expect } from 'vitest'; -import { dayCapabilities, weekDayKeys, isWorkday, composeDeltaMs, decomposeDeltaMs } from './utils'; +import { + dayCapabilities, + weekDayKeys, + isWorkday, + composeDeltaMs, + decomposeDeltaMs, + dayKeyForMs, + defaultDayForWeek, + endOfDayMs, + newId +} from './utils'; describe('dayCapabilities', () => { const today = '2026-04-30'; @@ -114,3 +124,50 @@ describe('decomposeDeltaMs', () => { expect(composeDeltaMs(sign, hours, minutes)).toBe(original); }); }); + +describe('dayKeyForMs', () => { + it('UTC keeps the calendar day of the instant', () => { + expect(dayKeyForMs(Date.parse('2026-06-15T22:30:00Z'), 'UTC')).toBe('2026-06-15'); + expect(dayKeyForMs(Date.parse('2026-06-15T23:59:59.999Z'), 'UTC')).toBe('2026-06-15'); + }); + + it('Europe/Berlin is already the next day', () => { + expect(dayKeyForMs(Date.parse('2026-06-15T22:30:00Z'), 'Europe/Berlin')).toBe('2026-06-16'); + }); + + it('Pacific/Auckland is already the next day', () => { + expect(dayKeyForMs(Date.parse('2026-06-15T12:30:00Z'), 'Pacific/Auckland')).toBe('2026-06-16'); + }); +}); + +describe('endOfDayMs', () => { + it('2026-06-16 in Europe/Berlin ends at 21:59:59.999Z', () => { + expect(endOfDayMs('2026-06-16', 'Europe/Berlin')).toBe(Date.parse('2026-06-16T21:59:59.999Z')); + }); + + it('DST day 2026-10-25 in Europe/Berlin ends at 22:59:59.999Z', () => { + expect(endOfDayMs('2026-10-25', 'Europe/Berlin')).toBe(Date.parse('2026-10-25T22:59:59.999Z')); + }); + + it('UTC ends at 23:59:59.999Z', () => { + expect(endOfDayMs('2026-06-16', 'UTC')).toBe(Date.parse('2026-06-16T23:59:59.999Z')); + }); +}); + +describe('defaultDayForWeek', () => { + it('picks the given today when it is in the week, else Monday', () => { + expect(defaultDayForWeek('2026-W18', '2026-04-30')).toBe('2026-04-30'); + expect(defaultDayForWeek('2026-W18', '2026-05-10')).toBe('2026-04-27'); + }); +}); + +describe('newId', () => { + it('is 15 chars [a-z0-9]', () => { + for (let i = 0; i < 100; i++) expect(newId()).toMatch(/^[a-z0-9]{15}$/); + }); + + it('is unique over 1000 draws', () => { + const ids = new Set(Array.from({ length: 1000 }, () => newId())); + expect(ids.size).toBe(1000); + }); +});