package tracking import ( "bytes" "log/slog" "strings" "testing" "time" "github.com/pocketbase/pocketbase/core" ) // loggedApp wraps an app so that a test can read what a call logged. type loggedApp struct { core.App logs *bytes.Buffer } func (a loggedApp) Logger() *slog.Logger { return slog.New(slog.NewTextHandler(a.logs, &slog.HandlerOptions{Level: slog.LevelDebug})) } func ids(records []*core.Record) string { list := make([]string, len(records)) for i, r := range records { list[i] = r.Id } return strings.Join(list, ",") } func zone(t testing.TB, name string) *time.Location { t.Helper() loc, err := time.LoadLocation(name) if err != nil { t.Fatal(err) } return loc } func endOf(dayKey string, loc *time.Location) int64 { d := parseDayKey(dayKey) return time.Date(d.Year(), d.Month(), d.Day(), 23, 59, 59, 999_000_000, loc).UnixMilli() } func TestAutoStopStalled(t *testing.T) { e := setup(t) berlin := zone(t, "Europe/Berlin") e.settings("2026-01-01", 40, 31, "Europe/Berlin") // testNow is 12:00 in Berlin (CEST). now := testNow yesterday := e.entry(dayTue, utc(dayTue, 8, 0), time.Time{}) today := e.entry(dayWed, utc(dayWed, 8, 0), time.Time{}) done := e.entry(dayMon, utc(dayMon, 8, 0), utc(dayMon, 9, 0)) stopped, err := AutoStopStalled(e.app, now) if err != nil { t.Fatalf("AutoStopStalled: %v", err) } if stopped != 1 { t.Fatalf("stopped %d entries, want 1", stopped) } got := e.load("entries", yesterday.Id) wantInt(t, got, "end_time", endOf(dayTue, berlin)) wantInt(t, got, "end_time", utc(dayTue, 21, 59).UnixMilli()+59_999) wantBool(t, got, "auto_stopped", true) wantInt(t, got, "rev", 2) wantInt(t, got, "client_updated_at", now.UnixMilli()) untouched := e.load("entries", today.Id) wantInt(t, untouched, "end_time", 0) wantBool(t, untouched, "auto_stopped", false) wantInt(t, untouched, "rev", 1) wantInt(t, untouched, "client_updated_at", testNow.UnixMilli()) finished := e.load("entries", done.Id) wantInt(t, finished, "end_time", utc(dayMon, 9, 0).UnixMilli()) wantBool(t, finished, "auto_stopped", false) wantInt(t, finished, "rev", 1) // Nothing is left to stop. if stopped, err = AutoStopStalled(e.app, now.Add(time.Minute)); err != nil || stopped != 0 { t.Errorf("second run stopped %d entries (err %v), want 0", stopped, err) } } func TestAutoStopStalledUsesOwnerTimezone(t *testing.T) { e := setup(t) other := newUser(t, e.app, "other@example.com") mine := e.entry(dayWed, utc(dayWed, 8, 0), time.Time{}) theirs := seedRecord(t, e.app, "entries", other.Id, map[string]any{ "start_time": utc(dayWed, 9, 0).UnixMilli(), "end_time": 0, "auto_stopped": false, "note": "", "day_key": dayWed, }) e.settings("2026-01-01", 40, 31, "Asia/Tokyo") // 18:00 UTC is already Thursday in Tokyo (UTC+9) but still Wednesday in UTC. now := time.Date(2026, 5, 13, 18, 0, 0, 0, time.UTC) stopped, err := AutoStopStalled(e.app, now) if err != nil { t.Fatalf("AutoStopStalled: %v", err) } if stopped != 1 { t.Fatalf("stopped %d entries, want 1", stopped) } tokyo := e.load("entries", mine.Id) wantInt(t, tokyo, "end_time", endOf(dayWed, zone(t, "Asia/Tokyo"))) wantInt(t, tokyo, "end_time", utc(dayWed, 14, 59).UnixMilli()+59_999) wantBool(t, tokyo, "auto_stopped", true) utcOwner := e.load("entries", theirs.Id) wantInt(t, utcOwner, "end_time", 0) wantBool(t, utcOwner, "auto_stopped", false) wantInt(t, utcOwner, "rev", 1) } func TestAutoStopStalledIgnoresDeletedAndInvalidEntries(t *testing.T) { e := setup(t) gone := e.entry(dayTue, utc(dayTue, 8, 0), time.Time{}) gone.Set("deleted", true) if err := e.app.Save(gone); err != nil { t.Fatal(err) } // The day key passes the collection pattern but is not a real date. invalid := e.seed("entries", map[string]any{ "start_time": 1000, "end_time": 0, "auto_stopped": false, "note": "", "day_key": "2026-02-30", }) stopped, err := AutoStopStalled(e.app, testNow) if err != nil { t.Fatalf("AutoStopStalled: %v", err) } if stopped != 0 { t.Errorf("stopped %d entries, want 0", stopped) } got := e.load("entries", invalid.Id) wantInt(t, got, "end_time", 0) wantBool(t, got, "auto_stopped", false) wantInt(t, got, "rev", 1) } func TestAutoStopStalledSkipsEntriesWithoutRealDayKey(t *testing.T) { e := setup(t) app := loggedApp{App: e.app, logs: &bytes.Buffer{}} // The day key passes the collection pattern but is not a real date. invalid := e.seed("entries", map[string]any{ "start_time": 1000, "end_time": 0, "auto_stopped": false, "note": "", "day_key": "2026-02-30", }) stale := e.entry(dayTue, utc(dayTue, 8, 0), time.Time{}) listed, err := stalledEntries(app, testNow) if err != nil { t.Fatal(err) } if len(listed) != 1 || listed[0].Id != stale.Id { t.Fatalf("listed %s, want only the stale entry %s", ids(listed), stale.Id) } stopped, err := AutoStopStalled(app, testNow) if err != nil { t.Fatal(err) } if stopped != 1 { t.Fatalf("stopped %d entries, want 1", stopped) } got := e.load("entries", invalid.Id) wantInt(t, got, "end_time", 0) wantBool(t, got, "auto_stopped", false) wantInt(t, got, "rev", 1) // The skip is a debug message only: an error used to be logged every minute. logs := app.logs.String() if !strings.Contains(logs, "level=DEBUG") || !strings.Contains(logs, invalid.Id) { t.Errorf("logs lack the debug message for %s:\n%s", invalid.Id, logs) } if strings.Contains(logs, "level=ERROR") { t.Errorf("logs contain an error:\n%s", logs) } } func TestAutoStopStalledEndsAtTheLocalEndOfDay(t *testing.T) { e := setup(t) berlin := zone(t, "Europe/Berlin") e.settings("2026-01-01", 40, 31, "Europe/Berlin") // The days of the DST transitions in Berlin: the night of 29 March loses // an hour, the night of 25 October gains one. spring := e.entry("2026-03-29", utc("2026-03-29", 8, 0), time.Time{}) autumn := e.entry("2026-10-25", utc("2026-10-25", 8, 0), time.Time{}) now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) stopped, err := AutoStopStalled(e.app, now) if err != nil { t.Fatalf("AutoStopStalled: %v", err) } if stopped != 2 { t.Fatalf("stopped %d entries, want 2", stopped) } got := e.load("entries", spring.Id) wantInt(t, got, "end_time", endOf("2026-03-29", berlin)) wantInt(t, got, "end_time", utc("2026-03-29", 21, 59).UnixMilli()+59_999) // CEST is UTC+2 wantBool(t, got, "auto_stopped", true) got = e.load("entries", autumn.Id) wantInt(t, got, "end_time", endOf("2026-10-25", berlin)) wantInt(t, got, "end_time", utc("2026-10-25", 22, 59).UnixMilli()+59_999) // CET is UTC+1 again wantBool(t, got, "auto_stopped", true) } func TestAutoStopStalledUsesTimezoneOfTheEntryDay(t *testing.T) { e := setup(t) e.settings("2026-01-01", 40, 31, "Europe/Berlin") e.settings("2026-06-01", 40, 31, "UTC") // The owner switched to UTC in June: the entry of 31 May still ends at the // end of the day in Berlin, the one of 1 June at the end of the day in UTC. may := e.entry("2026-05-31", utc("2026-05-31", 8, 0), time.Time{}) june := e.entry("2026-06-01", utc("2026-06-01", 8, 0), time.Time{}) now := time.Date(2026, 6, 2, 12, 0, 0, 0, time.UTC) stopped, err := AutoStopStalled(e.app, now) if err != nil { t.Fatalf("AutoStopStalled: %v", err) } if stopped != 2 { t.Fatalf("stopped %d entries, want 2", stopped) } wantInt(t, e.load("entries", may.Id), "end_time", utc("2026-05-31", 21, 59).UnixMilli()+59_999) wantInt(t, e.load("entries", june.Id), "end_time", utc("2026-06-01", 23, 59).UnixMilli()+59_999) } func TestStopStalledKeepsChangesMadeSinceListing(t *testing.T) { e := setup(t) // The client stops the entry after it was listed but before it is processed. running := e.entry(dayTue, utc(dayTue, 8, 0), time.Time{}) listed, err := stalledEntries(e.app, testNow) if err != nil || len(listed) != 1 { t.Fatalf("stalledEntries listed %s, err %v", ids(listed), err) } client := e.load("entries", running.Id) client.Set("end_time", utc(dayTue, 16, 30).UnixMilli()) client.Set("client_updated_at", 5) client.Set("rev", 2) if err := e.app.Save(client); err != nil { t.Fatal(err) } if stopStalled(e.app, listed[0].Id, testNow) { t.Error("the entry was reported as stopped although the client had stopped it") } got := e.load("entries", running.Id) wantInt(t, got, "end_time", utc(dayTue, 16, 30).UnixMilli()) wantBool(t, got, "auto_stopped", false) wantInt(t, got, "rev", 2) wantInt(t, got, "client_updated_at", 5) // A delete pushed in between is kept too. running = e.entry(dayMon, utc(dayMon, 8, 0), time.Time{}) listed, err = stalledEntries(e.app, testNow) if err != nil || len(listed) != 1 { t.Fatalf("stalledEntries listed %s, err %v", ids(listed), err) } gone := e.load("entries", running.Id) gone.Set("deleted", true) gone.Set("rev", 2) if err := e.app.Save(gone); err != nil { t.Fatal(err) } if stopStalled(e.app, listed[0].Id, testNow) { t.Error("a deleted entry was reported as stopped") } got = e.load("entries", running.Id) wantBool(t, got, "deleted", true) wantInt(t, got, "end_time", 0) wantInt(t, got, "rev", 2) // An entry that was removed from the server in between is not a failure either. removed := e.entry("2026-05-04", utc("2026-05-04", 8, 0), time.Time{}) // the Monday before listed, err = stalledEntries(e.app, testNow) if err != nil || len(listed) != 1 { t.Fatalf("stalledEntries listed %s, err %v", ids(listed), err) } if err := e.app.Delete(removed); err != nil { t.Fatal(err) } app := loggedApp{App: e.app, logs: &bytes.Buffer{}} if stopStalled(app, listed[0].Id, testNow) { t.Error("a removed entry was reported as stopped") } if logs := app.logs.String(); strings.Contains(logs, "auto-stop failed") { t.Errorf("removing the entry was logged as a failure:\n%s", logs) } } func TestLocation(t *testing.T) { e := setup(t) e.settings("2026-01-01", 40, 31, "Europe/Berlin") tokyo := e.settings("2026-06-01", 40, 31, "Asia/Tokyo") cases := map[string]string{ "2025-12-31": "UTC", // only the seeded default row is effective "2026-01-01": "Europe/Berlin", // effective_from is inclusive "2026-05-13": "Europe/Berlin", "2026-06-01": "Asia/Tokyo", } for dayKey, want := range cases { if got := location(e.app, e.owner.Id, dayKey).String(); got != want { t.Errorf("%s: got %s, want %s", dayKey, got, want) } } // An unknown timezone falls back to UTC. tokyo.Set("timezone", "Mars/Olympus") if err := e.app.Save(tokyo); err != nil { t.Fatal(err) } if got := location(e.app, e.owner.Id, "2026-07-01"); got != time.UTC { t.Errorf("invalid timezone: got %s, want UTC", got) } if got := location(e.app, e.owner.Id, "2026-05-01").String(); got != "Europe/Berlin" { t.Errorf("May: got %s, want Europe/Berlin", got) } // Without a live settings row the location is UTC too. for _, r := range e.rows("settings_history", "") { r.Set("deleted", true) if err := e.app.Save(r); err != nil { t.Fatal(err) } } if got := location(e.app, e.owner.Id, "2026-07-01"); got != time.UTC { t.Errorf("deleted settings: got %s, want UTC", got) } if got := location(e.app, "someone-else", "2026-07-01"); got != time.UTC { t.Errorf("owner without settings: got %s, want UTC", got) } } func TestOwnersAreIsolated(t *testing.T) { e := setup(t) other := newUser(t, e.app, "other@example.com") entryOf := func(owner, dayKey string, start, end time.Time) *core.Record { data := map[string]any{ "start_time": start.UnixMilli(), "end_time": 0, "auto_stopped": false, "note": "", "day_key": dayKey, } if !end.IsZero() { data["end_time"] = end.UnixMilli() } return seedRecord(t, e.app, "entries", owner, data) } // Owner A works 1h on Monday. Owner B works 8h and still runs a timer. entryOf(e.owner.Id, dayMon, utc(dayMon, 9, 0), utc(dayMon, 10, 0)) entryOf(other.Id, dayMon, utc(dayMon, 9, 0), utc(dayMon, 17, 0)) otherRunning := entryOf(other.Id, dayMon, utc(dayMon, 17, 0), time.Time{}) closed, err := CloseDay(e.app, e.owner.Id, dayMon, testNow) if err != nil { t.Fatalf("CloseDay: %v", err) } wantInt(t, closed, "worked_ms", hourMs) if b, err := findClosedDay(e.app, other.Id, dayMon); err != nil || b != nil { t.Errorf("owner B got a closed day from A's close (err %v)", err) } // A closes the week: only A's Monday counts. weekA, err := CloseWeek(e.app, e.owner.Id, weekKey, testNow) if err != nil { t.Fatalf("CloseWeek A: %v", err) } wantInt(t, weekA, "worked_ms", hourMs) // B closes the same week with two marked days. for _, key := range []string{dayMon, dayTue} { if _, err := MarkDay(e.app, other.Id, key, kindVacation, testNow); err != nil { t.Fatalf("MarkDay B: %v", err) } } weekB, err := CloseWeek(e.app, other.Id, weekKey, testNow) if err != nil { t.Fatalf("CloseWeek B: %v", err) } wantInt(t, weekB, "worked_ms", 2*eightH) if weekB.Id == weekA.Id { t.Error("both owners share one closed week row") } // B reopens Tuesday: only B's week snapshot changes. if err := ReopenDay(e.app, other.Id, dayTue, testNow.Add(time.Minute)); err != nil { t.Fatalf("ReopenDay B: %v", err) } wantInt(t, e.load("closed_weeks", weekB.Id), "worked_ms", eightH) weekA = e.load("closed_weeks", weekA.Id) wantInt(t, weekA, "worked_ms", hourMs) wantInt(t, weekA, "rev", 1) if e.day(dayMon) == nil { t.Error("A's Monday was reopened by B") } // B reopens the week: A's week stays closed. if err := ReopenWeek(e.app, other.Id, weekKey, testNow.Add(time.Minute)); err != nil { t.Fatalf("ReopenWeek B: %v", err) } if e.week(weekKey) == nil { t.Error("A's week was reopened by B") } wantErr(t, ReopenWeek(e.app, other.Id, weekKey, testNow), ErrWeekNotClosed) // Only B's stale running entry is stopped. stopped, err := AutoStopStalled(e.app, testNow.Add(time.Hour)) if err != nil { t.Fatalf("AutoStopStalled: %v", err) } if stopped != 1 { t.Errorf("stopped %d entries, want 1", stopped) } wantInt(t, e.load("entries", otherRunning.Id), "end_time", endOf(dayMon, time.UTC)) }