✨ Add day and week closing on PocketBase records

This commit is contained in:
2026-11-29 20:24:40 +00:00
parent 39e0f69342
commit 31b404e27a
5 changed files with 602 additions and 3 deletions
+72
View File
@@ -0,0 +1,72 @@
package tracking
import (
"fmt"
"regexp"
"strconv"
"time"
)
const (
dayKeyLayout = "2006-01-02"
weekKeyFmt = "%d-W%02d"
)
var weekKeyPattern = regexp.MustCompile(`^(\d{4})-W(\d{2})$`)
// WeekKeyForDayKey returns the ISO week key (YYYY-Www) of a day key (YYYY-MM-DD).
// It returns an empty string when the day key is invalid.
func WeekKeyForDayKey(dayKey string) string {
t, err := time.Parse(dayKeyLayout, dayKey)
if err != nil {
return ""
}
year, week := t.ISOWeek()
return fmt.Sprintf(weekKeyFmt, year, week)
}
// WeekDayKeys returns the day keys (YYYY-MM-DD) of Monday to Sunday of the ISO week
// weekKey (YYYY-Www). It returns ErrInvalidWeekKey for a malformed week key.
func WeekDayKeys(weekKey string) ([]string, error) {
m := weekKeyPattern.FindStringSubmatch(weekKey)
if m == nil {
return nil, ErrInvalidWeekKey
}
year, _ := strconv.Atoi(m[1])
week, _ := strconv.Atoi(m[2])
if week < 1 || week > 53 {
return nil, ErrInvalidWeekKey
}
// Jan 4 is always in week 1 of its year.
jan4 := time.Date(year, time.January, 4, 0, 0, 0, 0, time.UTC)
_, jan4Week := jan4.ISOWeek()
// (weekday+6)%7 counts the days since Monday (Mon=0, Sun=6).
daysSinceMonday := int(jan4.Weekday()+6) % 7
monday := jan4.AddDate(0, 0, -daysSinceMonday+(week-jan4Week)*7)
keys := make([]string, 7)
for i := range keys {
keys[i] = monday.AddDate(0, 0, i).Format(dayKeyLayout)
}
return keys, nil
}
func validDayKey(dayKey string) bool {
_, err := time.Parse(dayKeyLayout, dayKey)
return err == nil
}
func parseDayKey(dayKey string) time.Time {
t, _ := time.Parse(dayKeyLayout, dayKey)
return t
}
func endOfDayMs(dayKey string, loc *time.Location) (int64, error) {
t, err := time.Parse(dayKeyLayout, dayKey)
if err != nil {
return 0, err
}
end := time.Date(t.Year(), t.Month(), t.Day(), 23, 59, 59, 999_000_000, loc)
return end.UnixMilli(), nil
}