planner/sync/service/recur.go

68 lines
1.5 KiB
Go
Raw Normal View History

2024-12-01 10:22:47 +01:00
package main
import (
"log/slog"
"time"
"github.com/google/uuid"
"go-mod.ewintr.nl/planner/item"
)
type Recur struct {
repoSync Syncer
repoRecur Recurrer
logger *slog.Logger
}
func NewRecur(repoRecur Recurrer, repoSync Syncer, logger *slog.Logger) *Recur {
r := &Recur{
repoRecur: repoRecur,
repoSync: repoSync,
logger: logger,
}
return r
}
func (r *Recur) Run(interval time.Duration) {
ticker := time.NewTicker(interval)
for range ticker.C {
if err := r.Recur(); err != nil {
r.logger.Error("could not recur", "error", err)
}
}
}
func (r *Recur) Recur() error {
2024-12-19 12:06:03 +01:00
r.logger.Info("start looking for recurring items")
today := item.NewDateFromString(time.Now().Format(item.DateFormat))
items, err := r.repoRecur.ShouldRecur(today)
2024-12-01 10:22:47 +01:00
if err != nil {
return err
}
2024-12-19 12:06:03 +01:00
r.logger.Info("found recurring items", "count", len(items))
2024-12-01 10:22:47 +01:00
for _, i := range items {
2024-12-19 12:06:03 +01:00
r.logger.Info("processing recurring item", "id", i.ID)
2024-12-01 10:22:47 +01:00
// spawn instance
2024-12-19 12:06:03 +01:00
newItem := i
newItem.ID = uuid.New().String()
newItem.Date = i.RecurNext
newItem.Recurrer = nil
newItem.RecurNext = item.Date{}
if err := r.repoSync.Update(newItem, time.Now()); err != nil {
2024-12-01 10:22:47 +01:00
return err
}
2024-12-19 12:06:03 +01:00
// update recurrer
i.RecurNext = item.FirstRecurAfter(i.Recurrer, i.RecurNext)
if err := r.repoSync.Update(i, time.Now()); err != nil {
2024-12-01 10:22:47 +01:00
return err
}
2024-12-19 12:06:03 +01:00
r.logger.Info("recurring item processed", "id", i.ID, "recurNext", i.RecurNext.String())
2024-12-01 10:22:47 +01:00
}
r.logger.Info("processed recurring items", "count", len(items))
return nil
}