65 lines
2.6 KiB
Go
65 lines
2.6 KiB
Go
// Package tracking implements the day and week closing rules, the CSV export and
|
|
// the default settings of the wotra time tracking on top of PocketBase records.
|
|
package tracking
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/pocketbase/pocketbase/apis"
|
|
"github.com/pocketbase/pocketbase/core"
|
|
)
|
|
|
|
// Sentinel errors returned by the tracking functions.
|
|
var (
|
|
ErrDayAlreadyClosed = errors.New("day is already closed")
|
|
ErrDayNotClosed = errors.New("day is not closed")
|
|
ErrRunningEntryOnDay = errors.New("a running entry exists for this day; stop it first")
|
|
ErrDayHasNoEntries = errors.New("no completed entries found for this day")
|
|
ErrWeekAlreadyClosed = errors.New("week is already closed")
|
|
ErrWeekNotClosed = errors.New("week is not closed")
|
|
ErrWeekHasUnclosedDays = errors.New("all workdays in the week must be closed before closing the week")
|
|
ErrNoSettings = errors.New("no settings found")
|
|
ErrInvalidKind = errors.New("kind must be one of: holiday, vacation, sick")
|
|
ErrInvalidDayKey = errors.New("invalid day key, expected YYYY-MM-DD")
|
|
ErrInvalidWeekKey = errors.New("invalid week key, expected YYYY-Www")
|
|
)
|
|
|
|
// Register wires the tracking routes, the default settings hook and the midnight cron.
|
|
func Register(app core.App) {
|
|
app.OnServe().BindFunc(func(se *core.ServeEvent) error {
|
|
se.Router.GET("/healthz", func(e *core.RequestEvent) error {
|
|
return e.JSON(http.StatusOK, map[string]string{"status": "ok"})
|
|
})
|
|
g := se.Router.Group("/api")
|
|
g.Bind(apis.RequireAuth("users"))
|
|
g.POST("/days/{dayKey}/close", handleCloseDay)
|
|
g.POST("/days/{dayKey}/mark", handleMarkDay)
|
|
g.DELETE("/days/{dayKey}/close", handleReopenDay)
|
|
g.POST("/weeks/{weekKey}/close", handleCloseWeek)
|
|
g.DELETE("/weeks/{weekKey}/close", handleReopenWeek)
|
|
g.GET("/export/entries.csv", handleExportEntries)
|
|
g.GET("/export/days.csv", handleExportDays)
|
|
g.GET("/export/weeks.csv", handleExportWeeks)
|
|
return se.Next()
|
|
})
|
|
app.OnRecordAfterCreateSuccess("users").BindFunc(seedDefaultSettings)
|
|
app.Cron().MustAdd("wotra_midnight", "* * * * *", func() {
|
|
if _, err := AutoStopStalled(app, time.Now()); err != nil {
|
|
app.Logger().Error("midnight auto-stop failed", "error", err)
|
|
}
|
|
})
|
|
}
|
|
|
|
func writeError(e *core.RequestEvent, status int, err error) error {
|
|
// The body carries the PocketBase error envelope plus the legacy "error" key so
|
|
// that both the old and the new client read the unchanged message.
|
|
return e.JSON(status, map[string]any{
|
|
"status": status,
|
|
"message": err.Error(),
|
|
"data": map[string]any{},
|
|
"error": err.Error(),
|
|
})
|
|
}
|