Files
Docwell/Server/internal/directory/reminders.go
T
tajniak81andClaude Opus 5.5 84043ba05b Add date mentions with reminders
- "@today", "@friday", "@2026-12-01" insert a date; "@remind friday"
  or the date's popover adds a reminder for the person who set it.
- docwell-server keeps a reminders row per person, date and time zone
  in step with each page and sends a "reminder" notification at 9:00
  on the day in that time zone (job notify.reminders). Dates already
  past when added do not notify.
- Exports write dates out; the web and phone inboxes show reminders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 14:55:46 +01:00

230 lines
6.8 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package directory
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"sort"
"strings"
"time"
// Time zones for reminders also in images without a zoneinfo database.
_ "time/tzdata"
"docwell/server/internal/store/pocketbase"
)
// ---- Date reminders --------------------------------------------------------
//
// A date in a page (a dateMention node) can carry "remind me": the id of the
// person to remind and their time zone. Each save brings the page's
// reminders rows in step with its content, and a background job sends a
// "reminder" notification at reminderHour on the date. A date already past
// when it is added does not notify.
// NotifyReminder is the notification type of a due reminder.
const NotifyReminder = "reminder"
// reminderHour is when, in the person's time zone, a reminder is sent.
const reminderHour = 9
// maxReminders caps the reminders one page can hold.
const maxReminders = 100
type reminderRecord struct {
ID string `json:"id"`
Page string `json:"page"`
User string `json:"user"`
Workspace string `json:"workspace"`
Date string `json:"date"`
TZ string `json:"tz"`
Excerpt string `json:"excerpt"`
DueAt string `json:"due_at"`
SentAt string `json:"sent_at"`
Created string `json:"created"`
}
// reminder is one "remind me" date found in a document.
type reminder struct {
User, Date, TZ, Excerpt string
}
func (r reminder) key() string { return r.User + "|" + r.Date + "|" + r.TZ }
// dueAt is when a reminder for date (YYYY-MM-DD) in time zone tz is sent.
// An unknown or empty time zone counts as UTC.
func dueAt(date, tz string) (time.Time, bool) {
loc := time.UTC
if tz != "" {
if l, err := time.LoadLocation(tz); err == nil {
loc = l
}
}
d, err := time.ParseInLocation("2006-01-02", date, loc)
if err != nil {
return time.Time{}, false
}
return d.Add(reminderHour * time.Hour), true
}
// docReminders collects the reminders in a Tiptap document, one per person,
// date and time zone, with the text of the block each is in.
func docReminders(doc json.RawMessage) []reminder {
var root any
if json.Unmarshal(doc, &root) != nil {
return nil
}
seen := map[string]bool{}
var out []reminder
var walk func(n, parent map[string]any)
walk = func(n, parent map[string]any) {
if n["type"] == "dateMention" && parent != nil {
attrs, _ := n["attrs"].(map[string]any)
user, _ := attrs["remind"].(string)
date, _ := attrs["date"].(string)
tz, _ := attrs["tz"].(string)
if len(tz) > 64 {
tz = ""
} else if _, err := time.LoadLocation(tz); err != nil {
tz = ""
}
if _, ok := dueAt(date, tz); ok && validID(user) {
r := reminder{User: user, Date: date, TZ: tz, Excerpt: excerpt(inlineText(parent))}
if !seen[r.key()] && len(out) < maxReminders {
seen[r.key()] = true
out = append(out, r)
}
}
}
kids, _ := n["content"].([]any)
for _, k := range kids {
if m, ok := k.(map[string]any); ok {
walk(m, n)
}
}
}
if m, ok := root.(map[string]any); ok {
walk(m, nil)
}
sort.Slice(out, func(i, j int) bool { return out[i].key() < out[j].key() })
return out
}
// inlineText is the text of a block's inline content, with mentions and
// dates written out.
func inlineText(block map[string]any) string {
var b strings.Builder
kids, _ := block["content"].([]any)
for _, k := range kids {
m, _ := k.(map[string]any)
attrs, _ := m["attrs"].(map[string]any)
switch m["type"] {
case "text":
s, _ := m["text"].(string)
b.WriteString(s)
case "mention":
label, _ := attrs["label"].(string)
b.WriteString("@" + label)
case "dateMention":
date, _ := attrs["date"].(string)
b.WriteString(date)
case "hardBreak":
b.WriteString(" ")
}
}
return b.String()
}
// syncReminders brings a page's reminders rows in step with its content:
// new ones are added, unsent ones no longer in the page are dropped, and
// sent ones are kept so they do not fire again (best effort).
func (s *Service) syncReminders(ctx context.Context, p pageRecord, doc json.RawMessage) {
want := map[string]reminder{}
for _, r := range docReminders(doc) {
want[r.key()] = r
}
have, err := listAll[reminderRecord](ctx, s, "reminders", pocketbase.ListOptions{
Filter: fmt.Sprintf("page = '%s'", p.ID),
})
if err != nil {
slog.Default().Warn("reminders: list", "page", p.ID, "err", err)
return
}
for _, row := range have {
k := reminder{User: row.User, Date: row.Date, TZ: row.TZ}.key()
w, ok := want[k]
delete(want, k)
switch {
case ok && row.SentAt == "" && row.Excerpt != w.Excerpt:
_, _ = pocketbase.Update[struct{}](ctx, s.pb, "reminders", row.ID, map[string]any{"excerpt": w.Excerpt})
case !ok && row.SentAt == "":
_ = s.pb.Delete(ctx, "reminders", row.ID)
}
}
keys := make([]string, 0, len(want))
for k := range want {
keys = append(keys, k)
}
sort.Strings(keys)
now := time.Now()
for _, k := range keys {
r := want[k]
due, _ := dueAt(r.Date, r.TZ)
body := map[string]any{
"page": p.ID, "user": r.User, "workspace": p.Workspace, "date": r.Date, "tz": r.TZ,
"excerpt": r.Excerpt, "due_at": pbTime(due),
}
if !due.After(now) {
body["sent_at"] = pbTime(now) // already past: nothing to remind of
}
if _, err := pocketbase.Create[struct{}](ctx, s.pb, "reminders", body); err != nil {
slog.Default().Warn("reminders: create", "page", p.ID, "err", err)
}
}
}
// SendReminders sends the reminders that are due. Each is marked sent first,
// so a failure loses a reminder rather than sending it twice. It is a
// background job.
func (s *Service) SendReminders(ctx context.Context) error {
rows, err := listAll[reminderRecord](ctx, s, "reminders", pocketbase.ListOptions{
Filter: fmt.Sprintf("sent_at = '' && due_at <= '%s'", pbTime(time.Now())), Sort: "due_at",
})
if err != nil {
return err
}
for _, r := range rows {
if _, err := pocketbase.Update[struct{}](ctx, s.pb, "reminders", r.ID, map[string]any{"sent_at": pbTime(time.Now())}); err != nil {
return err
}
p, err := s.getPage(ctx, r.Page)
if err != nil || p.DeletedAt != "" {
continue
}
e := event{page: p, excerpt: r.Excerpt, to: map[string]string{}}
e.add(r.User, NotifyReminder)
s.send(ctx, e)
}
return nil
}
// pruneReminders deletes reminders sent more than 90 days ago. One still in
// its page comes back on the next save, already marked sent.
func (s *Service) pruneReminders(ctx context.Context) error {
cutoff := pbTime(time.Now().Add(-90 * 24 * time.Hour))
rows, err := listAll[reminderRecord](ctx, s, "reminders", pocketbase.ListOptions{
Filter: fmt.Sprintf("sent_at != '' && sent_at < '%s'", cutoff), Fields: "id",
})
if err != nil {
return err
}
for _, r := range rows {
if err := s.pb.Delete(ctx, "reminders", r.ID); err != nil && !pocketbase.IsNotFound(err) {
return err
}
}
return nil
}