oficina / calendar Public

Clone
git clone https://amadan.net/oficina/calendar

Plain git — no account needed to clone.

Download

Download this file

1package calendar
2
3// In-app reminders (spec §7 "In-app reminders", Paul 2026-11-01): a
4// reminder rule's channel, and the notices the drain marks for the in-app
5// half instead of sending anything.
6//
7// A notice is references and times only (ReminderNotice). Its title is
8// opened from the sealed event when a list is drawn, through the same
9// grant join every read takes, so a notice on an event the person no
10// longer reaches, or one deleted or cancelled, is neither shown nor
11// counted.
12
13import (
14 "context"
15 "fmt"
16 "strings"
17
18 "gorm.io/gorm"
19
20 "amadan.net/oficina/calendar/internal/calendar/seal"
21 "amadan.net/oficina/calendar/internal/calendar/teamstate"
22)
23
24// The reminder channels. A rule's channel is fixed when it is made.
25const (
26 ChannelEmail = "email"
27 ChannelInApp = "inapp"
28 ChannelBoth = "both"
29)
30
31// validChannel reports whether c is one of the three channels.
32func validChannel(c string) bool {
33 return c == ChannelEmail || c == ChannelInApp || c == ChannelBoth
34}
35
36// channelInApp reports whether a rule on channel c has an in-app half.
37func channelInApp(c string) bool { return c == ChannelInApp || c == ChannelBoth }
38
39// channelEmail reports whether a rule on channel c has an email half.
40// Anything that is not in-app only is mailed, as every rule was before
41// there was a choice: an unknown value resolves towards sending (ruling 6).
42func channelEmail(c string) bool { return c != ChannelInApp }
43
44// channelFor is the channel p's new rules take: in-app for a Home-only
45// member in team mode, who has no address to mail; otherwise their
46// choice, and email when they never made one.
47func (s *Store) channelFor(p Person) string {
48 if s.team && teamstate.Addressless(p.Address) {
49 return ChannelInApp
50 }
51 if p.ReminderChannel != nil && validChannel(*p.ReminderChannel) {
52 return *p.ReminderChannel
53 }
54 return ChannelEmail
55}
56
57// usesInApp reports whether p's new rules have an in-app half, which is
58// when the chrome shows the Reminders link even with nothing unread.
59func (s *Store) usesInApp(p Person) bool { return channelInApp(s.channelFor(p)) }
60
61// ruleChannel is the channel a rule p asked for gets: their own channel
62// when they named none (or one that does not exist), and ErrNoAddress for
63// an email half asked for by somebody with no address.
64func (s *Store) ruleChannel(p Person, asked string) (string, error) {
65 if !validChannel(asked) {
66 asked = s.channelFor(p)
67 }
68 if channelEmail(asked) && s.team && teamstate.Addressless(p.Address) {
69 return "", ErrNoAddress
70 }
71 return asked, nil
72}
73
74// MarkReminderNotice writes the in-app half of a claimed reminder: the
75// person's notice for this occurrence, unread.
76//
77// One statement, conditional on the claim this worker holds, as every
78// completion is: a reschedule that overtook the claim rewrote the queue
79// row to a time this worker never saw, and must not be announced. The
80// upsert replaces the rule's notice only for a DIFFERENT occurrence, so a
81// second fire of the same one (at least once, ruling 6) changes nothing
82// and a notice already dismissed stays dismissed.
83//
84// The mark and the completion that follows it (CompleteReminder, or the
85// email half first) are two transactions, and the window between them is
86// the one the email path already has: a reschedule landing there leaves a
87// notice naming the time the event just moved from, as the mail would have
88// named it, until the next fire replaces it; a lease that expires there
89// costs nothing, because the next worker's mark is the same-occurrence
90// no-op and it completes. Never a duplicate notice (one row per rule),
91// never a lost reminder (whoever holds the claim completes).
92func (s *Store) MarkReminderNotice(ctx context.Context, due DueReminder, now int64) error {
93 err := s.g.WithContext(ctx).Exec(`INSERT INTO reminder_notices
94 (reminder_id, person_id, event_id, occurrence_key, start_utc, fired_at)
95 SELECT ?, ?, ?, ?, ?, ? WHERE EXISTS
96 (SELECT 1 FROM reminder_queues WHERE id = ? AND claim_id = ?)
97 ON CONFLICT(reminder_id) DO UPDATE SET
98 person_id = excluded.person_id, event_id = excluded.event_id,
99 occurrence_key = excluded.occurrence_key, start_utc = excluded.start_utc,
100 fired_at = excluded.fired_at, dismissed_at = NULL
101 WHERE reminder_notices.occurrence_key <> excluded.occurrence_key`,
102 due.Queue.ReminderID, due.PersonID, due.EventID, due.Queue.OccurrenceKey, due.StartUTC, now,
103 due.Queue.ID, due.ClaimID).Error
104 if err != nil {
105 return fmt.Errorf("calendar: mark reminder notice: %w", err)
106 }
107 return nil
108}
109
110// NoticeView is one unread in-app reminder, opened for drawing.
111type NoticeView struct {
112 ID int64
113 EventID int64
114 Title string
115 StartUTC int64
116 AllDay bool
117 // Local is the occurrence's own local start ("2026-11-02T09:00", or a
118 // date for an all-day event), from the occurrence key.
119 Local string
120 // Href is the occurrence's page on this origin.
121 Href string
122}
123
124// noticeRows is the one read behind the list, the count and the seam: a
125// person's unread notices on live events they reach on this request's
126// standing (grantJoin), newest occurrence first.
127func (s *Store) noticeRows(ctx context.Context, personID int64) *gorm.DB {
128 return s.g.WithContext(ctx).
129 Table("reminder_notices").
130 Joins("JOIN events ON events.id = reminder_notices.event_id AND events.deleted_at IS NULL AND events.status <> ?", StatusCancelled).
131 Joins(grantJoin("events.calendar_id", s.reaches(ctx)), personID).
132 Where("reminder_notices.person_id = ? AND reminder_notices.dismissed_at IS NULL", personID)
133}
134
135// UnreadNoticeCount is how many unread in-app reminders the person has.
136func (s *Store) UnreadNoticeCount(ctx context.Context, personID int64) (int64, error) {
137 var n int64
138 if err := s.noticeRows(ctx, personID).Count(&n).Error; err != nil {
139 return 0, fmt.Errorf("calendar: count reminder notices: %w", err)
140 }
141 return n, nil
142}
143
144// UnreadNotices lists up to limit unread in-app reminders, newest
145// occurrence first.
146func (s *Store) UnreadNotices(ctx context.Context, personID int64, limit int) ([]NoticeView, error) {
147 // Every column named: gorm's default for RRule is r_rule.
148 type row struct {
149 ID int64 `gorm:"column:id"`
150 EventID int64 `gorm:"column:event_id"`
151 OccurrenceKey string `gorm:"column:occurrence_key"`
152 StartUTC int64 `gorm:"column:start_utc"`
153 TitleSealed []byte `gorm:"column:title_sealed"`
154 RRule string `gorm:"column:rrule"`
155 AllDay bool `gorm:"column:all_day"`
156 }
157 var rows []row
158 err := s.noticeRows(ctx, personID).
159 Select("reminder_notices.id, reminder_notices.event_id, reminder_notices.occurrence_key, reminder_notices.start_utc, events.title_sealed, events.rrule, events.all_day").
160 Order("reminder_notices.start_utc DESC, reminder_notices.id DESC").
161 Limit(limit).
162 Scan(&rows).Error
163 if err != nil {
164 return nil, fmt.Errorf("calendar: list reminder notices: %w", err)
165 }
166 out := make([]NoticeView, 0, len(rows))
167 for _, r := range rows {
168 title, err := s.seal.OpenString(seal.PurposeEventTitle, r.TitleSealed)
169 if err != nil {
170 return nil, fmt.Errorf("calendar: open title (notice %d): %w", r.ID, err)
171 }
172 _, local, _ := strings.Cut(r.OccurrenceKey, "/")
173 href := fmt.Sprintf("/events/%d", r.EventID)
174 if r.RRule != "" && local != "" {
175 href += "/" + compactLocal(local)
176 }
177 out = append(out, NoticeView{ID: r.ID, EventID: r.EventID, Title: title, StartUTC: r.StartUTC,
178 AllDay: r.AllDay, Local: local, Href: href})
179 }
180 return out, nil
181}
182
183// DismissNotice marks one of the person's own notices read. Somebody
184// else's, or one already dismissed, changes nothing and is not an error:
185// the answer is the same redirect either way, so it cannot be used to
186// enumerate anybody's reminders.
187func (s *Store) DismissNotice(ctx context.Context, personID, noticeID, now int64) error {
188 return s.guarded(ctx, func(db *gorm.DB) error {
189 return db.Model(&ReminderNotice{}).
190 Where("id = ? AND person_id = ? AND dismissed_at IS NULL", noticeID, personID).
191 Update("dismissed_at", now).Error
192 })
193}
194
195// DismissAllNotices marks every one of the person's notices read.
196func (s *Store) DismissAllNotices(ctx context.Context, personID, now int64) error {
197 return s.guarded(ctx, func(db *gorm.DB) error {
198 return db.Model(&ReminderNotice{}).
199 Where("person_id = ? AND dismissed_at IS NULL", personID).
200 Update("dismissed_at", now).Error
201 })
202}
203