diff --git a/PLAN.md b/PLAN.md index 6f9021d..5c02401 100644 --- a/PLAN.md +++ b/PLAN.md @@ -160,7 +160,7 @@ GET /healthz (unauthenticated) - **Midnight enforcement**: `end_time` must be on the same calendar day as `start_time`. Server auto-stops any running entry at 23:59:59 local time via a background goroutine. Client warns the user. - **Close day**: requires all entries for that day to have `end_time != NULL` (409 otherwise). Computes `worked_ms = sum(end_time - start_time)` across non-deleted entries. Entries are preserved but the day is now locked. - **Mark day**: writes a `closed_days` row with `kind != 'work'`; `worked_ms` = expected daily ms (hours_per_week * 3600000 / popcount(workdays_mask)) for workdays, 0 for non-workdays. -- **Close week**: all workdays in the week must have a `closed_days` row. Sums `worked_ms`, snapshots `expected_ms` from settings effective at close time, stores signed `delta_ms`. +- **Close week**: all workdays in the week must have a `closed_days` row. Sums `worked_ms`, snapshots `expected_ms` as the sum of the daily expected time of each workday with the settings effective on that day, stores signed `delta_ms`. - **Settings change**: new row in `settings_history` with `effective_from`. Past closed weeks are unaffected because they store a frozen snapshot. - **Future intervals**: server rejects `CreateInterval` and `Update` if the resulting day key is in the future (400 Bad Request). diff --git a/internal/tracking/settings.go b/internal/tracking/settings.go index c59c736..f2b0ee3 100644 --- a/internal/tracking/settings.go +++ b/internal/tracking/settings.go @@ -75,8 +75,32 @@ func location(tx core.App, owner, dayKey string) *time.Location { return loc } -func weekExpectedMs(set *core.Record) int64 { - return int64(set.GetFloat("hours_per_week") * 3_600_000) +// weekExpectedMs adds up the expected time of the workdays of the week. Each day +// counts towards the settings effective on it, so a week in which the settings +// change is only partly computed with the new hours. +func weekExpectedMs(tx core.App, owner string, dayKeys []string) (int64, error) { + var expectedMs int64 + for _, dayKey := range dayKeys { + ms, err := dayExpectedMsAt(tx, owner, dayKey) + if err != nil { + return 0, err + } + expectedMs += ms + } + return expectedMs, nil +} + +// dayExpectedMsAt returns the expected daily working time of the settings effective +// on dayKey, or 0 on a non-workday or without settings. +func dayExpectedMsAt(tx core.App, owner, dayKey string) (int64, error) { + set, err := settingsAt(tx, owner, dayKey) + if err != nil || set == nil { + return 0, err + } + if !isWorkday(set, parseDayKey(dayKey).Weekday()) { + return 0, nil + } + return dayExpectedMs(set), nil } func dayExpectedMs(set *core.Record) int64 { @@ -84,7 +108,7 @@ func dayExpectedMs(set *core.Record) int64 { if days == 0 { return 0 } - return weekExpectedMs(set) / int64(days) + return int64(set.GetFloat("hours_per_week")*3_600_000) / int64(days) } func isWorkday(set *core.Record, wd time.Weekday) bool { diff --git a/internal/tracking/weeks.go b/internal/tracking/weeks.go index 5ddec50..73100b9 100644 --- a/internal/tracking/weeks.go +++ b/internal/tracking/weeks.go @@ -38,7 +38,10 @@ func CloseWeek(app core.App, owner string, weekKey string, now time.Time) (*core if set == nil { return nil, ErrNoSettings } - expectedMs := weekExpectedMs(set) + expectedMs, err := weekExpectedMs(tx, owner, dayKeys) + if err != nil { + return nil, err + } var workedMs int64 for _, dayKey := range dayKeys { diff --git a/internal/tracking/weeks_test.go b/internal/tracking/weeks_test.go index a68f740..a2b6fcf 100644 --- a/internal/tracking/weeks_test.go +++ b/internal/tracking/weeks_test.go @@ -334,9 +334,41 @@ func TestCloseWeekUsesSettingsEffectiveToday(t *testing.T) { if err != nil { t.Fatalf("CloseWeek: %v", err) } - wantInt(t, cw, "expected_ms", 20*hourMs) + // Mon to Wed are 8h each, Thu and Fri count as 20h / 5 = 4h. + wantInt(t, cw, "expected_ms", 3*eightH+2*4*hourMs) wantInt(t, cw, "worked_ms", 3*eightH) - wantInt(t, cw, "delta_ms", 3*eightH-20*hourMs) + wantInt(t, cw, "delta_ms", 3*eightH-(3*eightH+2*4*hourMs)) +} + +func TestCloseWeekUsesSettingsEffectiveOnEachDay(t *testing.T) { + // 32h until 14.05., 36h from Friday 15.05. The week is closed a month later, + // when the 36h row is the only one effective today. + e := setup(t) + e.settings("2026-01-01", 32, 31, "UTC") + e.settings("2026-05-15", 36, 31, "UTC") + markWeekDays(t, e, weekKey, 5) + june := time.Date(2026, 6, 13, 10, 0, 0, 0, time.UTC) + + cw, err := CloseWeek(e.app, e.owner.Id, weekKey, june) + if err != nil { + t.Fatalf("CloseWeek: %v", err) + } + // 4 days with 32h / 5 = 6.4h and Friday with 36h / 5 = 7.2h. + want := int64(4*6.4*float64(hourMs)) + int64(7.2*float64(hourMs)) + wantInt(t, cw, "expected_ms", want) + // Every day was marked, so the credited time adds up to exactly the expectation. + wantInt(t, cw, "worked_ms", want) + wantInt(t, cw, "delta_ms", 0) + + // A week that lies before the change keeps 32h. + markWeekDays(t, e, "2026-W19", 5) + cw, err = CloseWeek(e.app, e.owner.Id, "2026-W19", june) + if err != nil { + t.Fatalf("CloseWeek: %v", err) + } + wantInt(t, cw, "expected_ms", 32*hourMs) + wantInt(t, cw, "worked_ms", 32*hourMs) + wantInt(t, cw, "delta_ms", 0) } func TestReopenWeekWithoutClosedWeekFails(t *testing.T) { diff --git a/web/src/lib/app.svelte.ts b/web/src/lib/app.svelte.ts index 593c7f5..dd80e34 100644 --- a/web/src/lib/app.svelte.ts +++ b/web/src/lib/app.svelte.ts @@ -10,7 +10,7 @@ import { type Entry, type Settings } from '$lib/types'; -import { dayKeyForMs, endOfDayMs } from '$lib/utils'; +import { dayKeyForMs, endOfDayMs, isWorkday, weekDayKeys } from '$lib/utils'; const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/; const LAST_DAY = '9999-12-31'; @@ -44,6 +44,25 @@ export function currentSettings(dayKey: string = todayKey()): Doc { return settingsAt(dayKey); } +export function dayExpectedMs(dayKey: string): number { + const s = currentSettings(dayKey); + if (!isWorkday(dayKey, s.workdays_mask)) return 0; + // Truncated to whole milliseconds like the server does, so that days add up + // to exactly the same week total on both sides. + return Math.trunc((s.hours_per_week * 3_600_000) / workdayCount(s.workdays_mask)); +} + +/** Expected time of the week: the sum over its days, each with its own settings. */ +export function weekExpectedMs(weekKey: string): number { + return weekDayKeys(weekKey).reduce((sum, dayKey) => sum + dayExpectedMs(dayKey), 0); +} + +function workdayCount(mask: number): number { + let count = 0; + for (let m = mask; m; m >>= 1) count += m & 1; + return count; +} + export function settingsHistory(): Doc[] { return all('settings_history').sort((a, b) => { if (a.effective_from !== b.effective_from) return a.effective_from < b.effective_from ? 1 : -1; diff --git a/web/src/lib/app.test.ts b/web/src/lib/app.test.ts index 5d392a0..b1c8bf2 100644 --- a/web/src/lib/app.test.ts +++ b/web/src/lib/app.test.ts @@ -7,10 +7,12 @@ import { currentSettings, createInterval, deleteSettings, + dayExpectedMs, entriesForDay, runningEntry, settingsHistory, startEntry, + weekExpectedMs, stopEntry, todayKey, updateEntry @@ -91,6 +93,22 @@ describe('settings', () => { expect(settingsHistory().map((s) => s.effective_from)).toEqual(['2026-07-01', '2026-06-01', '2026-01-01']); }); + it('expected hours follow the settings effective on each day of the week', async () => { + await addSettings(row('2000-01-01', 32)); + await addSettings(row('2026-11-30', 32)); + await addSettings(row('2026-12-01', 36)); + const h = 3_600_000; + // Monday 30.11. counts 32h / 5, Tuesday to Friday 36h / 5. + expect(weekExpectedMs('2026-W49')).toBe(6.4 * h + 4 * 7.2 * h); + expect(dayExpectedMs('2026-11-30')).toBe(6.4 * h); + expect(dayExpectedMs('2026-12-01')).toBe(7.2 * h); + expect(weekExpectedMs('2026-W48')).toBe(32 * h); + expect(weekExpectedMs('2026-W50')).toBe(36 * h); + // Weekends never count. + expect(dayExpectedMs('2026-12-05')).toBe(0); + expect(weekExpectedMs('2026-W53')).toBe(36 * h); + }); + it('addSettings rejects rows outside the bounds of the server', async () => { for (const hours of [0, 0.009, 168.01, NaN]) { await expect(addSettings(row('2026-01-01', hours))).rejects.toThrow('hours_per_week must be between 0.01 and 168'); diff --git a/web/src/lib/components/WeekView.svelte b/web/src/lib/components/WeekView.svelte index 495df17..9c5f416 100644 --- a/web/src/lib/components/WeekView.svelte +++ b/web/src/lib/components/WeekView.svelte @@ -5,9 +5,11 @@ closedWeek as findClosedWeek, closeWeek, currentSettings as getSettings, + dayExpectedMs, entriesForRange, reopenWeek, - todayKey + todayKey, + weekExpectedMs } from '$lib/app.svelte'; import type { Doc } from '$lib/db.svelte'; import type { ClosedDay } from '$lib/types'; @@ -113,17 +115,10 @@ .reduce((sum, e) => sum + (e.end_time! - e.start_time), 0); } - function dailyExpectedMs(dk: string): number { - const mask = currentSettings.workdays_mask; - if (!isWorkday(dk, mask)) return 0; - const workdayCount = [1, 2, 4, 8, 16, 32, 64].filter((b) => mask & b).length; - return (currentSettings.hours_per_week * 3_600_000) / workdayCount; - } - const totalWorkedMs = $derived( dayKeys.reduce((sum, dk) => sum + dayWorkedMs(dk), 0) ); - const expectedMs = $derived(currentSettings.hours_per_week * 3_600_000); + const expectedMs = $derived(weekExpectedMs(weekKey)); const daysWithEntries = $derived(new Set(weekEntries.map((e) => e.day_key))); @@ -166,12 +161,12 @@ dayKey={dk} weekdayLabel={DAY_NAMES[i]} workedMs={dayWorkedMs(dk)} - expectedMs={dailyExpectedMs(dk)} + expectedMs={dayExpectedMs(dk)} kind={closedDaysMap[dk]?.kind ?? null} closed={!!closedDaysMap[dk]} isToday={dk === todayKey()} selected={dk === selectedDay} - isWorkday={isWorkday(dk, currentSettings.workdays_mask)} + isWorkday={isWorkday(dk, getSettings(dk).workdays_mask)} onclick={() => ondaychange(dk)} />