✨ Seed settings for new users and auto-stop stale entries
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
package tracking
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
)
|
||||
|
||||
// AutoStopStalled stops every running entry whose day lies before today in the
|
||||
// timezone of its owner. The entry ends at 23:59:59.999 of its own day and is
|
||||
// flagged as auto stopped. It returns the number of stopped entries. A single
|
||||
// entry that cannot be saved is logged and skipped.
|
||||
func AutoStopStalled(app core.App, now time.Time) (int, error) {
|
||||
running, err := app.FindRecordsByFilter("entries", "deleted = false && end_time = 0", "start_time", 0, 0)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
byOwner := map[string][]*core.Record{}
|
||||
for _, entry := range running {
|
||||
owner := entry.GetString("owner")
|
||||
byOwner[owner] = append(byOwner[owner], entry)
|
||||
}
|
||||
|
||||
stopped := 0
|
||||
for owner, entries := range byOwner {
|
||||
loc := location(app, owner, now.UTC().Format(dayKeyLayout))
|
||||
today := now.In(loc).Format(dayKeyLayout)
|
||||
for _, entry := range entries {
|
||||
if entry.GetString("day_key") >= today {
|
||||
continue
|
||||
}
|
||||
if stopAtEndOfDay(app, entry, loc, now) {
|
||||
stopped++
|
||||
}
|
||||
}
|
||||
}
|
||||
return stopped, nil
|
||||
}
|
||||
|
||||
func stopAtEndOfDay(app core.App, entry *core.Record, loc *time.Location, now time.Time) bool {
|
||||
endMs, err := endOfDayMs(entry.GetString("day_key"), loc)
|
||||
if err == nil {
|
||||
entry.Set("end_time", endMs)
|
||||
entry.Set("auto_stopped", true)
|
||||
bump(entry, now)
|
||||
err = app.Save(entry)
|
||||
}
|
||||
if err != nil {
|
||||
app.Logger().Error("auto-stop failed for entry", "id", entry.Id, "error", err)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user