Marking a day answered every error except an invalid day key with 422, including database errors. Only an invalid kind is a 422 now. Server errors are logged with their cause and answered with a generic message instead of the error text, which can contain SQL, and the timezone lookup logs at warn before it falls back to UTC.
880 lines
28 KiB
Go
880 lines
28 KiB
Go
package tracking
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/pocketbase/dbx"
|
|
"github.com/pocketbase/pocketbase/core"
|
|
"github.com/pocketbase/pocketbase/tests"
|
|
_ "time/tzdata"
|
|
|
|
_ "github.com/wotra/wotra/internal/migrations"
|
|
)
|
|
|
|
// testNow is a fixed Wednesday (2026-W20) used as "now" throughout the tests.
|
|
var testNow = time.Date(2026, 5, 13, 10, 0, 0, 0, time.UTC)
|
|
|
|
const (
|
|
dayMon = "2026-05-11"
|
|
dayTue = "2026-05-12"
|
|
dayWed = "2026-05-13"
|
|
dayThu = "2026-05-14"
|
|
dayFri = "2026-05-15"
|
|
daySat = "2026-05-16"
|
|
daySun = "2026-05-17"
|
|
weekKey = "2026-W20"
|
|
)
|
|
|
|
const (
|
|
hourMs = 3_600_000
|
|
eightH = 8 * hourMs
|
|
fortyH = 40 * hourMs
|
|
password = "password123456"
|
|
)
|
|
|
|
type env struct {
|
|
t testing.TB
|
|
app *tests.TestApp
|
|
owner *core.Record
|
|
token string
|
|
}
|
|
|
|
func setup(t testing.TB) *env {
|
|
t.Helper()
|
|
app, err := tests.NewTestApp()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
Register(app)
|
|
t.Cleanup(app.Cleanup)
|
|
owner := newUser(t, app, "owner@example.com")
|
|
token, err := owner.NewAuthToken()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return &env{t: t, app: app, owner: owner, token: token}
|
|
}
|
|
|
|
func newUser(t testing.TB, app core.App, email string) *core.Record {
|
|
t.Helper()
|
|
users, err := app.FindCollectionByNameOrId("users")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
u := core.NewRecord(users)
|
|
u.SetEmail(email)
|
|
u.SetPassword(password)
|
|
if err := app.Save(u); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return u
|
|
}
|
|
|
|
// seed inserts a live record for the owner (rev 1, updated at testNow).
|
|
func (e *env) seed(collection string, data map[string]any) *core.Record {
|
|
e.t.Helper()
|
|
return seedRecord(e.t, e.app, collection, e.owner.Id, data)
|
|
}
|
|
|
|
func seedRecord(t testing.TB, app core.App, collection, owner string, data map[string]any) *core.Record {
|
|
t.Helper()
|
|
col, err := app.FindCollectionByNameOrId(collection)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
r := core.NewRecord(col)
|
|
r.Set("owner", owner)
|
|
for field, value := range data {
|
|
r.Set(field, value)
|
|
}
|
|
r.Set("client_updated_at", testNow.UnixMilli())
|
|
r.Set("rev", 1)
|
|
if err := app.Save(r); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return r
|
|
}
|
|
|
|
// entry inserts an entry on dayKey. A zero end leaves the entry running.
|
|
func (e *env) entry(dayKey string, start, end time.Time) *core.Record {
|
|
e.t.Helper()
|
|
return e.entryNoted(dayKey, start, end, "")
|
|
}
|
|
|
|
func (e *env) entryNoted(dayKey string, start, end time.Time, note string) *core.Record {
|
|
e.t.Helper()
|
|
data := map[string]any{
|
|
"start_time": start.UnixMilli(),
|
|
"end_time": 0,
|
|
"auto_stopped": false,
|
|
"note": note,
|
|
"day_key": dayKey,
|
|
}
|
|
if !end.IsZero() {
|
|
data["end_time"] = end.UnixMilli()
|
|
}
|
|
return e.seed("entries", data)
|
|
}
|
|
|
|
// settings inserts a settings row for the owner next to the seeded default row.
|
|
func (e *env) settings(effectiveFrom string, hours float64, mask int, timezone string) *core.Record {
|
|
e.t.Helper()
|
|
return e.seed("settings_history", map[string]any{
|
|
"effective_from": effectiveFrom,
|
|
"hours_per_week": hours,
|
|
"workdays_mask": mask,
|
|
"timezone": timezone,
|
|
})
|
|
}
|
|
|
|
func (e *env) load(collection, id string) *core.Record {
|
|
e.t.Helper()
|
|
r, err := e.app.FindRecordById(collection, id)
|
|
if err != nil {
|
|
e.t.Fatal(err)
|
|
}
|
|
return r
|
|
}
|
|
|
|
// rows returns every row of the owner in the collection, soft deleted ones included.
|
|
func (e *env) rows(collection string, extra string) []*core.Record {
|
|
e.t.Helper()
|
|
filter := "owner = {:owner}"
|
|
if extra != "" {
|
|
filter += " && " + extra
|
|
}
|
|
rows, err := e.app.FindRecordsByFilter(collection, filter, "id", 0, 0, dbx.Params{"owner": e.owner.Id})
|
|
if err != nil {
|
|
e.t.Fatal(err)
|
|
}
|
|
return rows
|
|
}
|
|
|
|
// day returns the live closed day of the owner, or nil.
|
|
func (e *env) day(dayKey string) *core.Record {
|
|
e.t.Helper()
|
|
rec, err := findClosedDay(e.app, e.owner.Id, dayKey)
|
|
if err != nil {
|
|
e.t.Fatal(err)
|
|
}
|
|
return rec
|
|
}
|
|
|
|
func (e *env) week(weekKey string) *core.Record {
|
|
e.t.Helper()
|
|
rec, err := findClosedWeek(e.app, e.owner.Id, weekKey)
|
|
if err != nil {
|
|
e.t.Fatal(err)
|
|
}
|
|
return rec
|
|
}
|
|
|
|
// utc returns the time on a day key at hour:minute in UTC.
|
|
func utc(dayKey string, hour, minute int) time.Time {
|
|
d := parseDayKey(dayKey)
|
|
return time.Date(d.Year(), d.Month(), d.Day(), hour, minute, 0, 0, time.UTC)
|
|
}
|
|
|
|
func wantErr(t testing.TB, err, target error) {
|
|
t.Helper()
|
|
if !errors.Is(err, target) {
|
|
t.Fatalf("got error %v, want %v", err, target)
|
|
}
|
|
}
|
|
|
|
func wantInt(t testing.TB, rec *core.Record, field string, want int64) {
|
|
t.Helper()
|
|
if got := rec.GetInt64(field); got != want {
|
|
t.Errorf("%s: got %d, want %d", field, got, want)
|
|
}
|
|
}
|
|
|
|
func wantString(t testing.TB, rec *core.Record, field, want string) {
|
|
t.Helper()
|
|
if got := rec.GetString(field); got != want {
|
|
t.Errorf("%s: got %q, want %q", field, got, want)
|
|
}
|
|
}
|
|
|
|
func wantBool(t testing.TB, rec *core.Record, field string, want bool) {
|
|
t.Helper()
|
|
if got := rec.GetBool(field); got != want {
|
|
t.Errorf("%s: got %t, want %t", field, got, want)
|
|
}
|
|
}
|
|
|
|
func auth(token string) map[string]string {
|
|
return map[string]string{"Authorization": token}
|
|
}
|
|
|
|
func disposition(prefix string) func(testing.TB, *tests.TestApp, *http.Response) {
|
|
return func(t testing.TB, _ *tests.TestApp, res *http.Response) {
|
|
if got := res.Header.Get("Content-Type"); got != "text/csv" {
|
|
t.Errorf("Content-Type: got %q, want %q", got, "text/csv")
|
|
}
|
|
if got := res.Header.Get("Content-Disposition"); !strings.HasPrefix(got, prefix) {
|
|
t.Errorf("Content-Disposition: got %q, want prefix %q", got, prefix)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSeedDefaultSettings(t *testing.T) {
|
|
e := setup(t)
|
|
|
|
rows := e.rows("settings_history", "")
|
|
if len(rows) != 1 {
|
|
t.Fatalf("new user: got %d settings rows, want 1", len(rows))
|
|
}
|
|
seeded := rows[0]
|
|
wantString(t, seeded, "effective_from", "2000-01-01")
|
|
wantString(t, seeded, "timezone", "UTC")
|
|
wantInt(t, seeded, "hours_per_week", 40)
|
|
wantInt(t, seeded, "workdays_mask", 31)
|
|
wantInt(t, seeded, "rev", 1)
|
|
wantBool(t, seeded, "deleted", false)
|
|
if seeded.GetInt64("client_updated_at") <= 0 {
|
|
t.Errorf("client_updated_at: got %d, want a timestamp", seeded.GetInt64("client_updated_at"))
|
|
}
|
|
|
|
// A later settings row does not make the hook seed another default row.
|
|
e.settings("2026-01-01", 30, 31, "Europe/Berlin")
|
|
defaults := 0
|
|
for _, r := range e.rows("settings_history", "") {
|
|
if r.GetString("effective_from") == "2000-01-01" {
|
|
defaults++
|
|
}
|
|
}
|
|
if defaults != 1 {
|
|
t.Errorf("after adding a settings row: got %d default rows, want 1", defaults)
|
|
}
|
|
|
|
other := newUser(t, e.app, "other@example.com")
|
|
seedRecord(t, e.app, "settings_history", other.Id, map[string]any{
|
|
"effective_from": "2026-02-01", "hours_per_week": 32.0, "workdays_mask": 31, "timezone": "Europe/Berlin",
|
|
})
|
|
otherRows, err := e.app.FindRecordsByFilter("settings_history", "owner = {:owner}", "", 0, 0, dbx.Params{"owner": other.Id})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defaults = 0
|
|
for _, r := range otherRows {
|
|
if r.GetString("effective_from") == "2000-01-01" {
|
|
defaults++
|
|
}
|
|
}
|
|
if len(otherRows) != 2 || defaults != 1 {
|
|
t.Errorf("second user: got %d rows with %d defaults, want 2 rows with 1 default", len(otherRows), defaults)
|
|
}
|
|
}
|
|
|
|
func TestWeekKeyForDayKey(t *testing.T) {
|
|
cases := map[string]string{
|
|
"2024-01-15": "2024-W03",
|
|
"2026-01-01": "2026-W01",
|
|
"2024-12-30": "2025-W01",
|
|
"2026-12-31": "2026-W53",
|
|
"2027-01-01": "2026-W53",
|
|
}
|
|
for dayKey, want := range cases {
|
|
if got := WeekKeyForDayKey(dayKey); got != want {
|
|
t.Errorf("%s: got %s, want %s", dayKey, got, want)
|
|
}
|
|
}
|
|
for _, dayKey := range []string{"", "2026-1-5", "2026-13-01", "2026-01-05x", "2026-W03"} {
|
|
if got := WeekKeyForDayKey(dayKey); got != "" {
|
|
t.Errorf("%q: got %s, want an empty week key", dayKey, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestWeekDayKeys(t *testing.T) {
|
|
cases := []struct {
|
|
weekKey string
|
|
wantMon string
|
|
wantSun string
|
|
}{
|
|
{"2024-W03", "2024-01-15", "2024-01-21"}, // Jan 4 is a Thursday
|
|
{"2026-W18", "2026-04-27", "2026-05-03"}, // Jan 4 is a Sunday
|
|
{"2023-W01", "2023-01-02", "2023-01-08"}, // Jan 4 is a Wednesday
|
|
{"2026-W53", "2026-12-28", "2027-01-03"}, // the week ends in the next year
|
|
{"2025-W52", "2025-12-22", "2025-12-28"},
|
|
}
|
|
for _, tc := range cases {
|
|
keys, err := WeekDayKeys(tc.weekKey)
|
|
if err != nil {
|
|
t.Fatalf("%s: %v", tc.weekKey, err)
|
|
}
|
|
if len(keys) != 7 {
|
|
t.Fatalf("%s: expected 7 keys, got %d", tc.weekKey, len(keys))
|
|
}
|
|
if keys[0] != tc.wantMon {
|
|
t.Errorf("%s: Monday want %s, got %s", tc.weekKey, tc.wantMon, keys[0])
|
|
}
|
|
if keys[6] != tc.wantSun {
|
|
t.Errorf("%s: Sunday want %s, got %s", tc.weekKey, tc.wantSun, keys[6])
|
|
}
|
|
for i, key := range keys {
|
|
if got := WeekKeyForDayKey(key); got != tc.weekKey {
|
|
t.Errorf("%s: day %s maps to week %s", tc.weekKey, key, got)
|
|
}
|
|
if i > 0 && key <= keys[i-1] {
|
|
t.Errorf("%s: keys are not ascending: %v", tc.weekKey, keys)
|
|
}
|
|
}
|
|
}
|
|
for _, weekKey := range []string{"", "2024-W00", "2024-W54", "2024-w03", "2024-W3", "2024-03", "2024W03", "x2024-W03"} {
|
|
if _, err := WeekDayKeys(weekKey); !errors.Is(err, ErrInvalidWeekKey) {
|
|
t.Errorf("%q: got %v, want ErrInvalidWeekKey", weekKey, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestWeekDayKeysRejectsWeeksTheYearDoesNotHave(t *testing.T) {
|
|
// 2025 has 52 weeks: its days around New Year belong to 2025-W01 and 2026-W01.
|
|
keys, err := WeekDayKeys("2025-W53")
|
|
if !errors.Is(err, ErrInvalidWeekKey) {
|
|
t.Fatalf("2025-W53: got %v and %v, want ErrInvalidWeekKey", keys, err)
|
|
}
|
|
// 2026 has 53 weeks: the last one ends in 2027.
|
|
keys, err = WeekDayKeys("2026-W53")
|
|
if err != nil {
|
|
t.Fatalf("2026-W53: %v", err)
|
|
}
|
|
if len(keys) != 7 || keys[0] != "2026-12-28" || keys[6] != "2027-01-03" {
|
|
t.Errorf("2026-W53: got %v, want 2026-12-28 to 2027-01-03", keys)
|
|
}
|
|
// W53 is valid exactly in the long years.
|
|
for year, valid := range map[int]bool{2020: true, 2021: false, 2022: false, 2023: false, 2024: false, 2025: false, 2026: true, 2027: false, 2028: false, 2029: false, 2030: false, 2032: true} {
|
|
_, err := WeekDayKeys(fmt.Sprintf("%d-W53", year))
|
|
if got := err == nil; got != valid {
|
|
t.Errorf("%d-W53: valid is %t, want %t (%v)", year, got, valid, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// requestEvent builds the event of a request without running it through the router.
|
|
func requestEvent(app core.App, method, path string) (*core.RequestEvent, *httptest.ResponseRecorder) {
|
|
rec := httptest.NewRecorder()
|
|
e := &core.RequestEvent{App: app}
|
|
e.Response = rec
|
|
e.Request = httptest.NewRequest(method, path, nil)
|
|
return e, rec
|
|
}
|
|
|
|
func TestWriteErrorHidesServerErrors(t *testing.T) {
|
|
e := setup(t)
|
|
app := loggedApp{App: e.app, logs: &bytes.Buffer{}}
|
|
|
|
// A domain error is answered with its message and is not logged.
|
|
req, rec := requestEvent(app, http.MethodPost, "/api/days/"+dayMon+"/close")
|
|
if err := writeError(req, http.StatusConflict, ErrDayAlreadyClosed); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, want := range []string{`"status":409`, `"message":"day is already closed"`, `"error":"day is already closed"`, `"data":{}`} {
|
|
if body := rec.Body.String(); !strings.Contains(body, want) {
|
|
t.Errorf("body lacks %s: %s", want, body)
|
|
}
|
|
}
|
|
if logs := app.logs.String(); strings.Contains(logs, "level=ERROR") {
|
|
t.Errorf("a domain error was logged as an error:\n%s", logs)
|
|
}
|
|
|
|
// A server error is logged with its cause and answered with a generic message.
|
|
cause := errors.New("SELECT owner FROM entries: no such table: entries")
|
|
req, rec = requestEvent(app, http.MethodPost, "/api/days/"+dayMon+"/mark")
|
|
if err := writeError(req, http.StatusInternalServerError, cause); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
body := rec.Body.String()
|
|
for _, want := range []string{`"status":500`, `"message":"internal server error"`, `"error":"internal server error"`, `"data":{}`} {
|
|
if !strings.Contains(body, want) {
|
|
t.Errorf("body lacks %s: %s", want, body)
|
|
}
|
|
}
|
|
if strings.Contains(body, "SELECT") || strings.Contains(body, "no such table") {
|
|
t.Errorf("body leaks the cause: %s", body)
|
|
}
|
|
logs := app.logs.String()
|
|
for _, want := range []string{"level=ERROR", cause.Error(), "/api/days/" + dayMon + "/mark"} {
|
|
if !strings.Contains(logs, want) {
|
|
t.Errorf("logs lack %s:\n%s", want, logs)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestLocationLogsTheFallback(t *testing.T) {
|
|
e := setup(t)
|
|
app := loggedApp{App: e.app, logs: &bytes.Buffer{}}
|
|
tokyo := e.settings("2026-06-01", 40, 31, "Asia/Tokyo")
|
|
|
|
// Without a settings row there is nothing to look up, so nothing is logged.
|
|
if got := location(app, "someone-else", "2026-07-01"); got != time.UTC {
|
|
t.Errorf("owner without settings: got %s, want UTC", got)
|
|
}
|
|
if logs := app.logs.String(); logs != "" {
|
|
t.Errorf("logs without a failure:\n%s", logs)
|
|
}
|
|
|
|
// An unknown timezone is logged together with the settings row it comes from.
|
|
tokyo.Set("timezone", "Mars/Olympus")
|
|
if err := e.app.Save(tokyo); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := location(app, e.owner.Id, "2026-07-01"); got != time.UTC {
|
|
t.Errorf("invalid timezone: got %s, want UTC", got)
|
|
}
|
|
logs := app.logs.String()
|
|
for _, want := range []string{"level=WARN", "Mars/Olympus", "2026-07-01"} {
|
|
if !strings.Contains(logs, want) {
|
|
t.Errorf("logs lack %s:\n%s", want, logs)
|
|
}
|
|
}
|
|
|
|
// A settings lookup that fails is logged with the error.
|
|
app.logs.Reset()
|
|
if _, err := e.app.DB().NewQuery("DROP TABLE settings_history").Execute(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := location(app, e.owner.Id, "2026-07-01"); got != time.UTC {
|
|
t.Errorf("failed lookup: got %s, want UTC", got)
|
|
}
|
|
logs = app.logs.String()
|
|
for _, want := range []string{"level=WARN", "no such table"} {
|
|
if !strings.Contains(logs, want) {
|
|
t.Errorf("logs lack %s:\n%s", want, logs)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
func TestHealthz(t *testing.T) {
|
|
e := setup(t)
|
|
(&tests.ApiScenario{
|
|
Name: "health check",
|
|
Method: http.MethodGet,
|
|
URL: "/healthz",
|
|
ExpectedStatus: http.StatusOK,
|
|
ExpectedContent: []string{`"status":"ok"`},
|
|
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
|
}).Test(t)
|
|
}
|
|
|
|
type routeCase struct {
|
|
name string
|
|
seed func(e *env)
|
|
as func(e *env) map[string]string
|
|
method string
|
|
url string
|
|
body string
|
|
status int
|
|
// content holds the body fragments that must be in the response.
|
|
content []string
|
|
// absent holds the body fragments that must not be in the response.
|
|
absent []string
|
|
after func(t testing.TB, e *env)
|
|
}
|
|
|
|
func runRoutes(t *testing.T, cases []routeCase) {
|
|
t.Helper()
|
|
for _, c := range cases {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
e := setup(t)
|
|
if c.seed != nil {
|
|
c.seed(e)
|
|
}
|
|
headers := auth(e.token)
|
|
if c.as != nil {
|
|
headers = c.as(e)
|
|
}
|
|
s := tests.ApiScenario{
|
|
Name: c.name,
|
|
Method: c.method,
|
|
URL: c.url,
|
|
Headers: headers,
|
|
ExpectedStatus: c.status,
|
|
ExpectedContent: c.content,
|
|
NotExpectedContent: c.absent,
|
|
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
|
}
|
|
if c.body != "" {
|
|
s.Body = strings.NewReader(c.body)
|
|
}
|
|
if c.after != nil {
|
|
s.AfterTestFunc = func(t testing.TB, _ *tests.TestApp, _ *http.Response) { c.after(t, e) }
|
|
}
|
|
s.Test(t)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestDayRoutes(t *testing.T) {
|
|
const closed = "/api/days/" + dayMon + "/close"
|
|
runRoutes(t, []routeCase{
|
|
{
|
|
name: "close day",
|
|
seed: func(e *env) { e.entry(dayMon, utc(dayMon, 9, 0), utc(dayMon, 10, 30)) },
|
|
method: http.MethodPost, url: closed, status: http.StatusOK,
|
|
content: []string{`"collectionName":"closed_days"`, `"day_key":"2026-05-11"`, `"worked_ms":5400000`, `"kind":"work"`, `"rev":1`, `"deleted":false`},
|
|
},
|
|
{
|
|
name: "close day with a running entry",
|
|
seed: func(e *env) { e.entry(dayMon, utc(dayMon, 9, 0), time.Time{}) },
|
|
method: http.MethodPost, url: closed, status: http.StatusConflict,
|
|
content: []string{`"status":409`, `"error":"a running entry exists for this day; stop it first"`, `"message":"a running entry exists for this day; stop it first"`},
|
|
after: func(t testing.TB, e *env) {
|
|
if e.day(dayMon) != nil {
|
|
t.Error("day got closed despite the running entry")
|
|
}
|
|
},
|
|
},
|
|
{
|
|
name: "close day twice",
|
|
seed: func(e *env) {
|
|
e.entry(dayMon, utc(dayMon, 9, 0), utc(dayMon, 10, 30))
|
|
if _, err := CloseDay(e.app, e.owner.Id, dayMon, testNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
method: http.MethodPost, url: closed, status: http.StatusConflict,
|
|
content: []string{`"status":409`, `"error":"day is already closed"`},
|
|
},
|
|
{
|
|
name: "close day without entries",
|
|
method: http.MethodPost, url: closed, status: http.StatusUnprocessableEntity,
|
|
content: []string{`"status":422`, `"error":"no completed entries found for this day"`},
|
|
},
|
|
{
|
|
name: "close day with an invalid key",
|
|
method: http.MethodPost, url: "/api/days/2026-13-01/close", status: http.StatusBadRequest,
|
|
content: []string{`"status":400`, `"error":"invalid day key, expected YYYY-MM-DD"`},
|
|
},
|
|
{
|
|
name: "mark day as holiday",
|
|
method: http.MethodPost, url: "/api/days/" + dayTue + "/mark", body: `{"kind":"holiday"}`, status: http.StatusOK,
|
|
content: []string{`"collectionName":"closed_days"`, `"day_key":"2026-05-12"`, `"kind":"holiday"`, `"worked_ms":28800000`, `"rev":1`},
|
|
},
|
|
{
|
|
name: "mark day with an invalid kind",
|
|
method: http.MethodPost, url: "/api/days/" + dayTue + "/mark", body: `{"kind":"work"}`, status: http.StatusUnprocessableEntity,
|
|
content: []string{`"status":422`, `"error":"kind must be one of: holiday, vacation, sick"`},
|
|
after: func(t testing.TB, e *env) {
|
|
if e.day(dayTue) != nil {
|
|
t.Error("day got marked despite the invalid kind")
|
|
}
|
|
},
|
|
},
|
|
{
|
|
name: "mark day with an invalid key",
|
|
method: http.MethodPost, url: "/api/days/2026-5-12/mark", body: `{"kind":"holiday"}`, status: http.StatusBadRequest,
|
|
content: []string{`"status":400`, `"error":"invalid day key, expected YYYY-MM-DD"`},
|
|
},
|
|
{
|
|
name: "mark day with an invalid body",
|
|
method: http.MethodPost, url: "/api/days/" + dayTue + "/mark", body: `{"kind":`, status: http.StatusBadRequest,
|
|
content: []string{`"status":400`, `"error":"invalid JSON"`},
|
|
},
|
|
{
|
|
// The settings cannot be read, so this is a server failure and not a
|
|
// validation problem: 500 with a generic message instead of 422 with SQL.
|
|
name: "mark day when the server fails",
|
|
seed: func(e *env) {
|
|
if _, err := e.app.DB().NewQuery("DROP TABLE settings_history").Execute(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
method: http.MethodPost, url: "/api/days/" + dayTue + "/mark", body: `{"kind":"holiday"}`, status: http.StatusInternalServerError,
|
|
content: []string{`"status":500`, `"message":"internal server error"`, `"error":"internal server error"`, `"data":{}`},
|
|
absent: []string{"no such table", "settings_history"},
|
|
},
|
|
{
|
|
name: "close day when the server fails",
|
|
seed: func(e *env) {
|
|
if _, err := e.app.DB().NewQuery("DROP TABLE closed_days").Execute(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
method: http.MethodPost, url: closed, status: http.StatusInternalServerError,
|
|
content: []string{`"status":500`, `"error":"internal server error"`},
|
|
absent: []string{"no such table", "closed_days"},
|
|
},
|
|
{
|
|
name: "reopen day when the server fails",
|
|
seed: func(e *env) {
|
|
if _, err := e.app.DB().NewQuery("DROP TABLE closed_days").Execute(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
method: http.MethodDelete, url: closed, status: http.StatusInternalServerError,
|
|
content: []string{`"status":500`, `"error":"internal server error"`},
|
|
absent: []string{"no such table", "closed_days"},
|
|
},
|
|
{
|
|
name: "reopen day",
|
|
seed: func(e *env) {
|
|
if _, err := MarkDay(e.app, e.owner.Id, dayMon, kindVacation, testNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
method: http.MethodDelete, url: closed, status: http.StatusNoContent,
|
|
after: func(t testing.TB, e *env) {
|
|
if e.day(dayMon) != nil {
|
|
t.Error("day is still closed after reopen")
|
|
}
|
|
},
|
|
},
|
|
{
|
|
name: "reopen an open day",
|
|
method: http.MethodDelete, url: closed, status: http.StatusNotFound,
|
|
content: []string{`"status":404`, `"error":"day is not closed"`},
|
|
},
|
|
{
|
|
name: "requires authentication",
|
|
as: func(e *env) map[string]string { return map[string]string{} },
|
|
method: http.MethodPost, url: closed, status: http.StatusUnauthorized,
|
|
content: []string{`"status":401`, `"data":{}`},
|
|
},
|
|
{
|
|
name: "another owner cannot reopen the day",
|
|
seed: func(e *env) {
|
|
if _, err := MarkDay(e.app, e.owner.Id, dayMon, kindSick, testNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
as: func(e *env) map[string]string {
|
|
other := newUser(t, e.app, "other@example.com")
|
|
token, err := other.NewAuthToken()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return auth(token)
|
|
},
|
|
method: http.MethodDelete, url: closed, status: http.StatusNotFound,
|
|
content: []string{`"status":404`, `"error":"day is not closed"`},
|
|
after: func(t testing.TB, e *env) {
|
|
if e.day(dayMon) == nil {
|
|
t.Error("another owner reopened the day")
|
|
}
|
|
},
|
|
},
|
|
})
|
|
}
|
|
|
|
func TestWeekRoutes(t *testing.T) {
|
|
const week = "2024-W03"
|
|
const closed = "/api/weeks/" + week + "/close"
|
|
markWeek := func(e *env) {
|
|
keys, err := WeekDayKeys(week)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, key := range keys[:5] {
|
|
if _, err := MarkDay(e.app, e.owner.Id, key, kindHoliday, testNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
runRoutes(t, []routeCase{
|
|
{
|
|
name: "close week",
|
|
seed: markWeek,
|
|
method: http.MethodPost, url: closed, status: http.StatusOK,
|
|
content: []string{`"collectionName":"closed_weeks"`, `"week_key":"2024-W03"`, `"expected_ms":144000000`, `"worked_ms":144000000`, `"delta_ms":0`, `"rev":1`},
|
|
},
|
|
{
|
|
name: "close week twice",
|
|
seed: func(e *env) {
|
|
markWeek(e)
|
|
if _, err := CloseWeek(e.app, e.owner.Id, week, testNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
method: http.MethodPost, url: closed, status: http.StatusConflict,
|
|
content: []string{`"status":409`, `"error":"week is already closed"`},
|
|
},
|
|
{
|
|
name: "close week with an unclosed tracked day",
|
|
seed: func(e *env) {
|
|
keys, _ := WeekDayKeys(week)
|
|
for _, key := range keys[:4] {
|
|
if _, err := MarkDay(e.app, e.owner.Id, key, kindHoliday, testNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
friday := keys[4]
|
|
e.entry(friday, utc(friday, 9, 0), utc(friday, 17, 0))
|
|
},
|
|
method: http.MethodPost, url: closed, status: http.StatusUnprocessableEntity,
|
|
content: []string{`"status":422`, `"error":"all workdays in the week must be closed before closing the week: 2024-01-19"`},
|
|
},
|
|
{
|
|
name: "close week without settings",
|
|
seed: func(e *env) {
|
|
for _, r := range e.rows("settings_history", "") {
|
|
if err := e.app.Delete(r); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
markWeek(e)
|
|
},
|
|
method: http.MethodPost, url: closed, status: http.StatusUnprocessableEntity,
|
|
content: []string{`"status":422`, `"error":"no settings found"`},
|
|
},
|
|
{
|
|
name: "close week with an invalid key",
|
|
method: http.MethodPost, url: "/api/weeks/2024-W3/close", status: http.StatusBadRequest,
|
|
content: []string{`"status":400`, `"error":"invalid week key, expected YYYY-Www"`},
|
|
},
|
|
{
|
|
name: "close week when the server fails",
|
|
seed: func(e *env) {
|
|
if _, err := e.app.DB().NewQuery("DROP TABLE closed_weeks").Execute(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
method: http.MethodPost, url: closed, status: http.StatusInternalServerError,
|
|
content: []string{`"status":500`, `"error":"internal server error"`},
|
|
absent: []string{"no such table", "closed_weeks"},
|
|
},
|
|
{
|
|
name: "reopen week when the server fails",
|
|
seed: func(e *env) {
|
|
if _, err := e.app.DB().NewQuery("DROP TABLE closed_weeks").Execute(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
method: http.MethodDelete, url: closed, status: http.StatusInternalServerError,
|
|
content: []string{`"status":500`, `"error":"internal server error"`},
|
|
absent: []string{"no such table", "closed_weeks"},
|
|
},
|
|
{
|
|
name: "reopen week",
|
|
seed: func(e *env) {
|
|
markWeek(e)
|
|
if _, err := CloseWeek(e.app, e.owner.Id, week, testNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
},
|
|
method: http.MethodDelete, url: closed, status: http.StatusNoContent,
|
|
after: func(t testing.TB, e *env) {
|
|
if e.week(week) != nil {
|
|
t.Error("week is still closed after reopen")
|
|
}
|
|
if e.day("2024-01-15") == nil {
|
|
t.Error("reopen week reopened a day")
|
|
}
|
|
},
|
|
},
|
|
{
|
|
name: "reopen an open week",
|
|
method: http.MethodDelete, url: closed, status: http.StatusNotFound,
|
|
content: []string{`"status":404`, `"error":"week is not closed"`},
|
|
},
|
|
})
|
|
}
|
|
|
|
func TestExportRoutes(t *testing.T) {
|
|
type ids struct{ mon, tue, wed string }
|
|
seedAll := func(t testing.TB, e *env) ids {
|
|
mon := e.entryNoted(dayMon, utc(dayMon, 9, 0), utc(dayMon, 10, 30), "a, b")
|
|
tue := e.entry(dayTue, utc(dayTue, 9, 0), utc(dayTue, 13, 30))
|
|
wed := e.seed("entries", map[string]any{
|
|
"start_time": utc(dayWed, 8, 0).UnixMilli(), "end_time": 0, "auto_stopped": true, "note": "", "day_key": dayWed,
|
|
})
|
|
gone := e.entry(daySun, utc(daySun, 1, 0), utc(daySun, 2, 0))
|
|
gone.Set("deleted", true)
|
|
if err := e.app.Save(gone); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := MarkDay(e.app, e.owner.Id, dayMon, kindHoliday, testNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := CloseDay(e.app, e.owner.Id, dayTue, testNow); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
e.seed("closed_weeks", map[string]any{
|
|
"week_key": weekKey, "expected_ms": fortyH, "worked_ms": 12*hourMs + 30*60*1000,
|
|
"delta_ms": -(27*hourMs + 30*60*1000), "closed_at": testNow.UnixMilli(),
|
|
})
|
|
return ids{mon.Id, tue.Id, wed.Id}
|
|
}
|
|
cases := []struct {
|
|
name string
|
|
url string
|
|
file string
|
|
expected func(i ids) string
|
|
}{
|
|
{
|
|
name: "entries csv", url: "/api/export/entries.csv", file: "entries-",
|
|
expected: func(i ids) string {
|
|
return "id,day_key,start_time,end_time,duration_ms,note,auto_stopped\n" +
|
|
i.mon + ",2026-05-11,2026-05-11T09:00:00Z,2026-05-11T10:30:00Z,5400000,\"a, b\",false\n" +
|
|
i.tue + ",2026-05-12,2026-05-12T09:00:00Z,2026-05-12T13:30:00Z,16200000,,false\n" +
|
|
i.wed + ",2026-05-13,2026-05-13T08:00:00Z,,0,,true\n"
|
|
},
|
|
},
|
|
{
|
|
name: "entries csv with a key range", url: "/api/export/entries.csv?from=2026-05-12&to=2026-05-12", file: "entries-",
|
|
expected: func(i ids) string {
|
|
return "id,day_key,start_time,end_time,duration_ms,note,auto_stopped\n" +
|
|
i.tue + ",2026-05-12,2026-05-12T09:00:00Z,2026-05-12T13:30:00Z,16200000,,false\n"
|
|
},
|
|
},
|
|
{
|
|
name: "days csv", url: "/api/export/days.csv", file: "days-",
|
|
expected: func(ids) string {
|
|
return "day_key,kind,worked_ms,worked_hours\n2026-05-11,holiday,28800000,8.00\n2026-05-12,work,16200000,4.50\n"
|
|
},
|
|
},
|
|
{
|
|
name: "weeks csv", url: "/api/export/weeks.csv", file: "weeks-",
|
|
expected: func(ids) string {
|
|
return "week_key,expected_ms,worked_ms,delta_ms,expected_h,worked_h,delta_h\n2026-W20,144000000,45000000,-99000000,40.00,12.50,-27.50\n"
|
|
},
|
|
},
|
|
}
|
|
for _, c := range cases {
|
|
t.Run(c.name, func(t *testing.T) {
|
|
e := setup(t)
|
|
s := tests.ApiScenario{
|
|
Name: c.name,
|
|
Method: http.MethodGet,
|
|
URL: c.url,
|
|
Headers: auth(e.token),
|
|
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
|
}
|
|
s.BeforeTestFunc = func(t testing.TB, _ *tests.TestApp, _ *core.ServeEvent) {
|
|
s.ExpectedContent = []string{c.expected(seedAll(t, e))}
|
|
}
|
|
s.ExpectedStatus = http.StatusOK
|
|
s.AfterTestFunc = disposition(`attachment; filename="` + c.file)
|
|
s.Test(t)
|
|
})
|
|
}
|
|
|
|
t.Run("another owner exports nothing", func(t *testing.T) {
|
|
e := setup(t)
|
|
seedAll(t, e)
|
|
other := newUser(t, e.app, "other@example.com")
|
|
token, err := other.NewAuthToken()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
(&tests.ApiScenario{
|
|
Name: "another owner exports nothing",
|
|
Method: http.MethodGet,
|
|
URL: "/api/export/entries.csv",
|
|
Headers: auth(token),
|
|
ExpectedStatus: http.StatusOK,
|
|
ExpectedContent: []string{"id,day_key,start_time,end_time,duration_ms,note,auto_stopped\n"},
|
|
TestAppFactory: func(testing.TB) *tests.TestApp { return e.app },
|
|
}).Test(t)
|
|
})
|
|
}
|