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
3import (
4 "context"
5 "errors"
6 "fmt"
7 "time"
8
9 "gorm.io/gorm"
10)
11
12// EnsureDefaultReminder gives a newly created event the person's own
13// default warning, using the preference that matches what kind of thing
14// it is.
15//
16// A default rather than nothing, because a reminder somebody has to
17// remember to set is a reminder that exists for the events they were
18// already thinking about. A note gets none: a birthday does not need a
19// ten-minute warning, and the all-day default is the evening before.
20func (s *Store) EnsureDefaultReminder(ctx context.Context, p Person, e Event) error {
21 offset := p.DefaultReminderMin
22 if e.AllDay {
23 offset = p.DefaultAllDayMin
24 }
25 if offset == 0 {
26 return nil
27 }
28 // The person's own channel: email unless they chose otherwise, and
29 // in-app for a Home-only member, who has no address to mail (spec §7
30 // "In-app reminders").
31 r := Reminder{
32 EventID: e.ID,
33 PersonID: p.ID,
34 OffsetMin: offset,
35 Channel: s.channelFor(p),
36 CreatedAt: time.Now().UTC(),
37 }
38 return s.guarded(ctx, func(db *gorm.DB) error {
39 if err := db.Create(&r).Error; err != nil {
40 return fmt.Errorf("calendar: create reminder: %w", err)
41 }
42 return s.rescheduleAfterTx(db, r.ID, 0)
43 })
44}
45
46// RemindersFor lists a person's own reminders on an event. Only their
47// own: a reminder is a fact about a person, and whether a colleague
48// wants a warning is not information the event's page should carry.
49func (s *Store) RemindersFor(ctx context.Context, personID, eventID int64) ([]Reminder, error) {
50 var out []Reminder
51 err := s.g.WithContext(ctx).
52 Where("event_id = ? AND person_id = ?", eventID, personID).
53 Order("offset_min DESC").
54 Find(&out).Error
55 if err != nil {
56 return nil, fmt.Errorf("calendar: list reminders: %w", err)
57 }
58 return out, nil
59}
60
61// AddReminder attaches a warning to an event the person can see, on the
62// person's own channel.
63func (s *Store) AddReminder(ctx context.Context, personID, eventID, offsetMin int64) error {
64 return s.AddReminderOn(ctx, personID, eventID, offsetMin, "")
65}
66
67// AddReminderOn is AddReminder on a channel the person chose; "" (or a
68// channel that does not exist) is their own. An email half asked for by a
69// Home-only member is ErrNoAddress: they have no address to mail.
70func (s *Store) AddReminderOn(ctx context.Context, personID, eventID, offsetMin int64, channel string) error {
71 if _, err := s.Event(ctx, personID, eventID); err != nil {
72 return err
73 }
74 var p Person
75 if err := s.g.WithContext(ctx).First(&p, personID).Error; err != nil {
76 return fmt.Errorf("calendar: read person for reminder: %w", err)
77 }
78 channel, err := s.ruleChannel(p, channel)
79 if err != nil {
80 return err
81 }
82 r := Reminder{
83 EventID: eventID,
84 PersonID: personID,
85 OffsetMin: int(offsetMin),
86 Channel: channel,
87 CreatedAt: time.Now().UTC(),
88 }
89 return s.guarded(ctx, func(db *gorm.DB) error {
90 if err := db.Create(&r).Error; err != nil {
91 return fmt.Errorf("calendar: add reminder: %w", err)
92 }
93 return s.rescheduleAfterTx(db, r.ID, 0)
94 })
95}
96
97// RemoveReminder deletes one of the person's own reminders, and the
98// queued row with it.
99func (s *Store) RemoveReminder(ctx context.Context, personID, reminderID int64) error {
100 return s.g.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
101 return s.guard(ctx, func() error { return removeReminderOn(tx, personID, reminderID) })
102 })
103}
104
105// removeReminderOn is RemoveReminder's write, on its transaction.
106func removeReminderOn(tx *gorm.DB, personID, reminderID int64) error {
107 res := tx.Where("id = ? AND person_id = ?", reminderID, personID).Delete(&Reminder{})
108 if res.Error != nil {
109 return fmt.Errorf("calendar: remove reminder: %w", res.Error)
110 }
111 if res.RowsAffected == 0 {
112 // Somebody else's reminder, or none. Not found, never
113 // forbidden.
114 return ErrNotFound
115 }
116 if err := tx.Where("reminder_id = ?", reminderID).Delete(&ReminderQueue{}).Error; err != nil {
117 return err
118 }
119 // Its in-app notice goes with it: a reminder somebody removed is not
120 // one they are still waiting to read.
121 return tx.Where("reminder_id = ?", reminderID).Delete(&ReminderNotice{}).Error
122}
123
124// RescheduleReminder recomputes when a rule next fires and writes the
125// single pending queue row for it.
126//
127// One row per rule, always — never one per occurrence. A daily standup
128// that repeats forever has exactly one queued row at any moment, and
129// firing it computes the next. Materialising a series' reminders is how
130// a queue becomes unbounded.
131func (s *Store) RescheduleReminder(ctx context.Context, reminderID int64) error {
132 return s.rescheduleAfter(ctx, reminderID, 0)
133}
134
135// rescheduleAfter queues the first occurrence starting strictly after
136// `after`, or after now when `after` is zero.
137func (s *Store) rescheduleAfter(ctx context.Context, reminderID, after int64) error {
138 return s.rescheduleAfterTx(s.g.WithContext(ctx), reminderID, after)
139}
140
141// rescheduleAfterTx is rescheduleAfter on a caller's transaction, so a
142// reschedule of a booked meeting can rebuild its reminder rows in the
143// SAME transaction as the move (booking spec B24): a crash between the
144// two would otherwise leave a row that sends a reminder for a time the
145// meeting no longer has.
146//
147// Any rewrite of a queue row clears its claim and its retry: whoever
148// held it was announcing a time that is gone, and must find zero rows
149// when they try to complete.
150func (s *Store) rescheduleAfterTx(tx *gorm.DB, reminderID, after int64) error {
151 var rem Reminder
152 if err := tx.First(&rem, reminderID).Error; err != nil {
153 if errors.Is(err, gorm.ErrRecordNotFound) {
154 return nil
155 }
156 return fmt.Errorf("calendar: read reminder: %w", err)
157 }
158 var e Event
159 if err := tx.Where("id = ? AND deleted_at IS NULL AND status <> ?", rem.EventID, StatusCancelled).
160 First(&e).Error; err != nil {
161 if errors.Is(err, gorm.ErrRecordNotFound) {
162 // The event is gone, or cancelled; so is any reason to
163 // warn about it.
164 return tx.Where("reminder_id = ?", reminderID).Delete(&ReminderQueue{}).Error
165 }
166 return fmt.Errorf("calendar: read event for reminder: %w", err)
167 }
168
169 // The floor for the search: whichever is later of "now" and the
170 // occurrence just fired. Zero means nothing has fired, so now.
171 floor := time.Now().Unix()
172 if after > floor {
173 floor = after
174 }
175 occStart, occLocal, ok := s.nextOccurrenceAfter(e, floor, rem.OffsetMin)
176 if !ok {
177 // Nothing left to warn about: a finished series, or a single
178 // event already past. Drop the queue row rather than leave a
179 // due time in the past that every drain re-examines.
180 return tx.Where("reminder_id = ?", reminderID).Delete(&ReminderQueue{}).Error
181 }
182
183 q := ReminderQueue{
184 ReminderID: reminderID,
185 OccurrenceKey: fmt.Sprintf("%d/%s", e.ID, occLocal),
186 DueAt: occStart - int64(rem.OffsetMin)*60,
187 }
188 // Upsert on the unique reminder_id, so rescheduling is idempotent
189 // and two callers cannot leave two pending rows for one rule.
190 err := tx.
191 Where(ReminderQueue{ReminderID: reminderID}).
192 Assign(map[string]any{
193 "occurrence_key": q.OccurrenceKey,
194 "due_at": q.DueAt,
195 "claimed_at": nil,
196 "claim_id": nil,
197 "retry_at": nil,
198 "fired_at": nil,
199 "attempts": 0,
200 "late_by_sec": 0,
201 }).
202 FirstOrCreate(&q).Error
203 if err != nil {
204 return fmt.Errorf("calendar: queue reminder: %w", err)
205 }
206 return nil
207}
208
209// ExcludeOccurrence deletes one occurrence of a series by adding an
210// EXDATE, and reschedules any reminder that pointed at it.
211func (s *Store) ExcludeOccurrence(ctx context.Context, personID, eventID int64, local string) error {
212 e, err := s.Event(ctx, personID, eventID)
213 if err != nil {
214 return err
215 }
216 if !e.Writable() {
217 return ErrReadOnly
218 }
219 set := exdateSet(e.Exdates)
220 if set[local] {
221 return nil
222 }
223 next := e.Exdates
224 if next != "" {
225 next += ","
226 }
227 next += local
228 return s.guarded(ctx, func(db *gorm.DB) error {
229 if err := db.Model(&Event{}).Where("id = ?", eventID).
230 Updates(map[string]any{"exdates": next, "updated_at": time.Now().UTC()}).Error; err != nil {
231 return fmt.Errorf("calendar: exclude occurrence: %w", err)
232 }
233 return s.rescheduleAllForTx(db, eventID)
234 })
235}
236
237// rescheduleAllFor recomputes every reminder on an event, after the
238// event's own times or rule changed.
239func (s *Store) rescheduleAllFor(ctx context.Context, eventID int64) error {
240 return s.rescheduleAllForTx(s.g.WithContext(ctx), eventID)
241}
242
243// rescheduleAllForTx enumerates the event's reminder RULES — not its
244// queue rows, because a reminder that already fired has none — and
245// upserts one queue row per rule from the event's current times
246// (booking spec B26).
247func (s *Store) rescheduleAllForTx(tx *gorm.DB, eventID int64) error {
248 var ids []int64
249 if err := tx.Model(&Reminder{}).
250 Where("event_id = ?", eventID).Pluck("id", &ids).Error; err != nil {
251 return fmt.Errorf("calendar: list reminders to reschedule: %w", err)
252 }
253 for _, id := range ids {
254 if err := s.rescheduleAfterTx(tx, id, 0); err != nil {
255 return err
256 }
257 }
258 return nil
259}
260
261// CountOccurrences reports how many times a series happens, for the
262// delete confirmation — "All 52 of them" is a warning that a bare
263// "Delete all" is not.
264//
265// forever is true for a series with no end, where no count exists and
266// the confirmation says so instead of inventing a number.
267func (s *Store) CountOccurrences(e EventView) (int, bool) {
268 if e.RRule == "" {
269 return 1, false
270 }
271 rule, err := ParseRule(e.RRule)
272 if err != nil {
273 return 0, true
274 }
275 if rule.Count > 0 {
276 return rule.Count, false
277 }
278 if !rule.HasUntil {
279 return 0, true
280 }
281 occs := Expand(e.StartLocal, e.EndLocal, e.TZ, e.AllDay, rule, e.Exdates,
282 e.StartUTC-1, untilBound(rule))
283 return len(occs), false
284}
285
286func untilBound(r Rule) int64 {
287 if r.HasUntil {
288 return r.Until.Unix() + 24*3600
289 }
290 return time.Now().AddDate(2, 0, 0).Unix()
291}
292