Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -776,7 +776,11 @@ as the desired state:
bordered header cell). Public-page CSP `img-src` allows `https:`/`data:` so the
logo/banner load (`strictPublicCSP`). Brand is threaded into every send site
(booking/cancel/reschedule/reassign + worker reminder).
- Reminders: scheduled as `jobs` and sent by the worker (§13).
- Reminders: scheduled as `jobs` and sent by the worker (§13). One job per
`hours_before` entry, at `start_at - hours_before`, on create and again on
reschedule (`replaceReminderJobs`). A reminder whose moment passed more than
`reminderGrace` (5 min) ago is **skipped**, not sent at once: a booking made 5 h out
with `[24, 2]` gets only the 2 h reminder, since the confirmation covers the rest.
- **Deliverability note (ops):** prod sends via **Resend** SMTP
(`smtp.resend.com`, user `resend`, password = API key, STARTTLS); `orchestratr.ai`
verified so any `@orchestratr.ai` From works. Email settings are **per-instance in
Expand Down
41 changes: 33 additions & 8 deletions internal/handler/booking_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2164,14 +2164,36 @@ func (h *Handler) loadHostPrefs(ctx context.Context, hostID string) (hostPrefs,
return p, nil
}

// enqueueReminder inserts a reminder.send job scheduled hoursBefore hours before startAt.
// If the computed run_at has already passed, the job fires on the next poll cycle.
func (h *Handler) enqueueReminder(ctx context.Context, bookingID string, startAt time.Time, hoursBefore int) error {
// reminderGrace is how far in the past a reminder's moment may be and still be sent.
// It absorbs clock skew and job timing: a reminder due two minutes ago still goes out
// on the next poll. Anything older is skipped, see reminderRunAt.
const reminderGrace = 5 * time.Minute

// reminderRunAt returns when the reminder hoursBefore hours before startAt should run,
// and false when that moment passed more than reminderGrace ago. Such a reminder is
// skipped, never sent late: a booking made five hours out with reminders [24, 2] would
// otherwise get the 24-hour reminder ("tomorrow") right next to the confirmation email.
// The confirmation already covers that window. A run_at inside the grace window is
// clamped to now.
func reminderRunAt(startAt time.Time, hoursBefore int, now time.Time) (time.Time, bool) {
runAt := startAt.UTC().Add(-time.Duration(hoursBefore) * time.Hour)
now := time.Now().UTC()
now = now.UTC()
if runAt.Before(now.Add(-reminderGrace)) {
return time.Time{}, false
}
if runAt.Before(now) {
runAt = now
}
return runAt, true
}

// enqueueReminder inserts a reminder.send job scheduled hoursBefore hours before startAt.
// A reminder whose moment has already passed is skipped (reminderRunAt).
func (h *Handler) enqueueReminder(ctx context.Context, bookingID string, startAt time.Time, hoursBefore int) error {
runAt, ok := reminderRunAt(startAt, hoursBefore, time.Now())
if !ok {
return nil
}

payload, err := json.Marshal(map[string]any{"booking_id": bookingID, "hours_before": hoursBefore})
if err != nil {
Expand Down Expand Up @@ -2221,6 +2243,7 @@ func (h *Handler) enqueueBookingReminders(ctx context.Context, etID, bookingID s
// replaceReminderJobs atomically deletes all non-running reminder jobs for a
// booking and inserts fresh ones based on the event type's configured reminder
// list. Falls back to a single 24-hour reminder when no explicit list is set.
// Reminders whose moment has already passed are skipped.
func (h *Handler) replaceReminderJobs(ctx context.Context, bookingID, etID string, newStart time.Time) error {
// Load the hours list first (read-only, outside the write transaction).
rows, err := h.db.QueryContext(ctx,
Expand Down Expand Up @@ -2258,11 +2281,13 @@ func (h *Handler) replaceReminderJobs(ctx context.Context, bookingID, etID strin
return fmt.Errorf("replace reminder jobs: delete: %w", err)
}

now := time.Now().UTC()
// A reschedule onto a nearer slot must not fire reminders whose moment has
// already passed, same as on create (reminderRunAt).
now := time.Now()
for _, hb := range hours {
runAt := newStart.UTC().Add(-time.Duration(hb) * time.Hour)
if runAt.Before(now) {
runAt = now
runAt, ok := reminderRunAt(newStart, hb, now)
if !ok {
continue
}
payload, err := json.Marshal(map[string]any{"booking_id": bookingID, "hours_before": hb})
if err != nil {
Expand Down
35 changes: 35 additions & 0 deletions internal/handler/reminder_runat_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package handler

import (
"testing"
"time"
)

func TestReminderRunAt(t *testing.T) {
now := time.Date(2026, 11, 26, 10, 0, 0, 0, time.UTC)
cases := []struct {
name string
startAt time.Time
hoursBefore int
wantOK bool
wantRunAt time.Time
}{
{"future reminder keeps its time", now.Add(48 * time.Hour), 24, true, now.Add(24 * time.Hour)},
{"booking inside the window skips it", now.Add(5 * time.Hour), 24, false, time.Time{}},
{"shorter reminder in the same booking still runs", now.Add(5 * time.Hour), 2, true, now.Add(3 * time.Hour)},
{"just late, inside grace, runs now", now.Add(2*time.Hour - 2*time.Minute), 2, true, now},
{"exactly at the grace edge runs now", now.Add(2*time.Hour - reminderGrace), 2, true, now},
{"past the grace window is skipped", now.Add(2*time.Hour - reminderGrace - time.Second), 2, false, time.Time{}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, ok := reminderRunAt(tc.startAt, tc.hoursBefore, now)
if ok != tc.wantOK {
t.Fatalf("ok = %v; want %v", ok, tc.wantOK)
}
if ok && !got.Equal(tc.wantRunAt) {
t.Errorf("run_at = %s; want %s", got, tc.wantRunAt)
}
})
}
}
88 changes: 88 additions & 0 deletions internal/handler/reminder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package handler_test

import (
"context"
"database/sql"
"fmt"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -90,3 +91,90 @@ func TestCreateBooking_enqueuedReminderJob(t *testing.T) {
t.Errorf("run_at = %s; want ~%s (±1m)", runAt, wantRunAt.Format(time.RFC3339))
}
}

// ---------------------------------------------------------------------------
// A reminder whose moment has already passed is skipped, not sent at once
// ---------------------------------------------------------------------------

// reminderHours returns the hours_before of the pending reminder jobs for a booking.
func reminderHours(t *testing.T, database *sql.DB, bookingID string) map[int]bool {
t.Helper()
rows, err := database.Query(`
SELECT json_extract(payload, '$.hours_before') FROM jobs
WHERE type = 'reminder.send'
AND json_extract(payload, '$.booking_id') = ?
AND status = 'pending'`, bookingID)
if err != nil {
t.Fatalf("query reminder jobs: %v", err)
}
defer rows.Close()
got := map[int]bool{}
for rows.Next() {
var hb int
if err := rows.Scan(&hb); err != nil {
t.Fatalf("scan: %v", err)
}
got[hb] = true
}
return got
}

// waitReminderHours polls until the booking's pending reminders equal want (the jobs
// are enqueued by a goroutine) and fails with what it last saw otherwise.
func waitReminderHours(t *testing.T, database *sql.DB, bookingID string, want ...int) {
t.Helper()
var got map[int]bool
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
got = reminderHours(t, database, bookingID)
if len(got) == len(want) {
match := true
for _, hb := range want {
match = match && got[hb]
}
if match {
return
}
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("pending reminders (hours_before) = %v; want %v", got, want)
}

func TestCreateBooking_skipsReminderAlreadyPast(t *testing.T) {
h, database, key, _ := setupWorkspaceWithDB(t)
slug, etID := seedEventTypeHTTP(t, h, key)
if _, err := database.Exec(`
INSERT INTO event_type_reminders (id, event_type_id, hours_before)
VALUES ('rem-24', ?, 24), ('rem-2', ?, 2)`, etID, etID); err != nil {
t.Fatalf("seed reminders: %v", err)
}

// Booked 5-6 hours ahead: the 24-hour mark is long gone, the 2-hour one is not.
start := time.Now().UTC().Truncate(time.Hour).Add(6 * time.Hour)
bookingID := createBookingViaHTTP(t, h, slug, start.Format(time.RFC3339))

waitReminderHours(t, database, bookingID, 2)
}

func TestRescheduleBooking_skipsReminderAlreadyPast(t *testing.T) {
h, database, key, _ := setupWorkspaceWithDB(t)
slug, etID := seedEventTypeHTTP(t, h, key)
if _, err := database.Exec(`
INSERT INTO event_type_reminders (id, event_type_id, hours_before)
VALUES ('rem-24', ?, 24), ('rem-2', ?, 2)`, etID, etID); err != nil {
t.Fatalf("seed reminders: %v", err)
}

bookingID := createBookingViaHTTP(t, h, slug, futureAt(10, 10, 0).Format(time.RFC3339))
waitReminderHours(t, database, bookingID, 24, 2)

// Moving the booking onto a slot 5-6 hours away must drop the 24-hour reminder
// instead of firing it straight away.
start := time.Now().UTC().Truncate(time.Hour).Add(6 * time.Hour)
rec := patchReschedule(t, h, bookingID, start.Format(time.RFC3339), key)
if rec.Code != http.StatusOK {
t.Fatalf("reschedule: got %d — %s", rec.Code, rec.Body.String())
}
waitReminderHours(t, database, bookingID, 2)
}
Loading