diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0856972d..75222399 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -800,7 +800,15 @@ as the desired state: - `internal/webhook`: enqueues `booking.created` / `.cancelled` / `.rescheduled` plus the notetaker events `recording.completed` / `transcript.ready` / `notes.ready` (reference payloads — booking-shaped, keyed by id; consumers fetch the artifact body - via REST/MCP). There is **no** `booking.reminder` webhook event. Deliveries are signed + via REST/MCP). **`booking.reminder`** fires from the `reminder.send` job, once per + configured `hours_before`, so an external SMS/push sender stays stateless: Calnode keeps + owning scheduling, reschedules and cancellations, the receiver only delivers. It passes + the same gates as the reminder email (booking still `confirmed`, host's + `notify_reminder` on) and carries `hours_before` in `data` whatever the webhook's field + selection. It is enqueued **before** the email with `EnqueueOnce`: the delivery ID is + derived from (webhook, booking, `hours_before`, `start_at`) and inserted with + `INSERT OR IGNORE`, so a job retried after a failed email collapses instead of + delivering twice, while a reschedule (new `start_at`) gets its own event. Deliveries are signed **HMAC-SHA256**, header `X-Calnode-Signature` (+ `X-Calnode-Event`/`-Delivery`), secret stored encrypted. The worker's HTTP client is **SSRF-guarded** (resolves DNS, blocks private/loopback/CGNAT/ULA IPs, dials the resolved IP to avoid diff --git a/frontend/src/routes/webhooks/+page.svelte b/frontend/src/routes/webhooks/+page.svelte index 46441530..43a9b649 100644 --- a/frontend/src/routes/webhooks/+page.svelte +++ b/frontend/src/routes/webhooks/+page.svelte @@ -20,6 +20,7 @@ 'booking.cancelled', 'booking.rescheduled', 'booking.rsvp', + 'booking.reminder', 'recording.completed', 'transcript.ready', 'notes.ready' diff --git a/internal/handler/webhook_handler.go b/internal/handler/webhook_handler.go index 829cbaeb..20e6f785 100644 --- a/internal/handler/webhook_handler.go +++ b/internal/handler/webhook_handler.go @@ -15,7 +15,7 @@ import ( ) var validWebhookEvents = []string{ - "booking.created", "booking.cancelled", "booking.rescheduled", "booking.rsvp", + "booking.created", "booking.cancelled", "booking.rescheduled", "booking.rsvp", "booking.reminder", "recording.completed", "transcript.ready", "notes.ready", } diff --git a/internal/handler/webhook_test.go b/internal/handler/webhook_test.go index 9e1f3ce3..df27a2a8 100644 --- a/internal/handler/webhook_test.go +++ b/internal/handler/webhook_test.go @@ -54,6 +54,19 @@ func TestCreateWebhook_bothEvents(t *testing.T) { } } +func TestCreateWebhook_bookingReminderEvent(t *testing.T) { + h, apiKey, _ := setupWorkspace(t) + + req := authReq(http.MethodPost, "/v1/webhooks", + `{"url":"https://example.com/hook","events":["booking.reminder"]}`, apiKey) + rec := httptest.NewRecorder() + h.RequireAuth(h.CreateWebhook)(rec, req) + + if rec.Code != http.StatusCreated { + t.Fatalf("status = %d; want 201 — %s", rec.Code, rec.Body.String()) + } +} + func TestCreateWebhook_missingURL_returns400(t *testing.T) { h, apiKey, _ := setupWorkspace(t) diff --git a/internal/webhook/enqueue_once_test.go b/internal/webhook/enqueue_once_test.go new file mode 100644 index 00000000..5248caa5 --- /dev/null +++ b/internal/webhook/enqueue_once_test.go @@ -0,0 +1,144 @@ +package webhook_test + +import ( + "context" + "encoding/json" + "regexp" + "testing" + + "github.com/calnode/calnode/internal/webhook" +) + +func reminderPayload() webhook.BookingPayload { + return webhook.BookingPayload{ + EventTypeSlug: "30-min", + HostID: testUserID, + StartAt: "2026-06-15T09:00:00Z", + EndAt: "2026-06-15T09:30:00Z", + Status: "confirmed", + CreatedAt: "2026-06-14T15:00:00Z", + HoursBefore: 2, + } +} + +func countRows(t *testing.T, e *env, query string, args ...any) int { + t.Helper() + var n int + if err := e.db.QueryRowContext(context.Background(), query, args...).Scan(&n); err != nil { + t.Fatalf("count: %v", err) + } + return n +} + +// A retried reminder job calls EnqueueOnce again with the same key: it must not +// produce a second delivery or a second webhook.deliver job. +func TestEnqueueOnce_sameKeyCollapses(t *testing.T) { + e := newEnv(t) + ctx := context.Background() + wh, _, _ := e.svc.Create(ctx, testUserID, "https://example.com/hook", []string{"booking.reminder"}) + + for i := 0; i < 3; i++ { + if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k1"); err != nil { + t.Fatalf("EnqueueOnce #%d: %v", i+1, err) + } + } + if n := countRows(t, e, `SELECT COUNT(*) FROM webhook_deliveries WHERE webhook_id = ?`, wh.ID); n != 1 { + t.Errorf("deliveries = %d; want 1", n) + } + if n := countRows(t, e, `SELECT COUNT(*) FROM jobs WHERE type = 'webhook.deliver'`); n != 1 { + t.Errorf("webhook.deliver jobs = %d; want 1", n) + } + + // Still collapsed after the delivery finished and its job is no longer live, + // which is where the jobs table's own (type, payload) guard stops helping. + e.db.ExecContext(ctx, `UPDATE jobs SET status = 'done' WHERE type = 'webhook.deliver'`) + e.db.ExecContext(ctx, `UPDATE webhook_deliveries SET status = 'success'`) + if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k1"); err != nil { + t.Fatalf("EnqueueOnce after success: %v", err) + } + if n := countRows(t, e, `SELECT COUNT(*) FROM webhook_deliveries`); n != 1 { + t.Errorf("deliveries after success = %d; want 1", n) + } + if n := countRows(t, e, `SELECT COUNT(*) FROM jobs WHERE type = 'webhook.deliver'`); n != 1 { + t.Errorf("jobs after success = %d; want 1", n) + } +} + +func TestEnqueueOnce_differentKeyOrWebhookGetsOwnDelivery(t *testing.T) { + e := newEnv(t) + ctx := context.Background() + e.svc.Create(ctx, testUserID, "https://example.com/a", []string{"booking.reminder"}) + e.svc.Create(ctx, testUserID, "https://example.com/b", []string{"booking.reminder"}) + + if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k1"); err != nil { + t.Fatal(err) + } + if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k2"); err != nil { + t.Fatal(err) + } + // Two webhooks × two keys. + if n := countRows(t, e, `SELECT COUNT(*) FROM webhook_deliveries`); n != 4 { + t.Errorf("deliveries = %d; want 4", n) + } + + uuid := regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) + rows, _ := e.db.QueryContext(ctx, `SELECT id FROM webhook_deliveries`) + defer rows.Close() + for rows.Next() { + var id string + rows.Scan(&id) + if !uuid.MatchString(id) { + t.Errorf("delivery id %q is not UUID-shaped", id) + } + } +} + +func TestEnqueueOnce_requiresKey(t *testing.T) { + e := newEnv(t) + if err := e.svc.EnqueueOnce(context.Background(), "booking.reminder", reminderPayload(), ""); err == nil { + t.Fatal("EnqueueOnce with empty key: want error") + } +} + +// hours_before is part of the event, not a selectable booking field: it is sent even +// when the webhook narrowed its fields, and never on other events. +func TestEnqueue_hoursBeforeAlwaysSentWithReminder(t *testing.T) { + e := newEnv(t) + ctx := context.Background() + wh, _, _ := e.svc.Create(ctx, testUserID, "https://example.com/hook", + []string{"booking.reminder", "booking.created"}) + e.db.ExecContext(ctx, `UPDATE webhooks SET fields = '["id"]' WHERE id = ?`, wh.ID) + + if err := e.svc.EnqueueOnce(ctx, "booking.reminder", reminderPayload(), "k1"); err != nil { + t.Fatal(err) + } + created := reminderPayload() + created.HoursBefore = 0 + if err := e.svc.Enqueue(ctx, "booking.created", created); err != nil { + t.Fatal(err) + } + + data := map[string]map[string]any{} + rows, _ := e.db.QueryContext(ctx, `SELECT event, payload FROM webhook_deliveries`) + defer rows.Close() + for rows.Next() { + var event, payload string + rows.Scan(&event, &payload) + var env struct { + Data map[string]any `json:"data"` + } + if err := json.Unmarshal([]byte(payload), &env); err != nil { + t.Fatalf("payload: %v", err) + } + data[event] = env.Data + } + if got := data["booking.reminder"]["hours_before"]; got != float64(2) { + t.Errorf("booking.reminder hours_before = %v; want 2", got) + } + if _, ok := data["booking.reminder"]["start_at"]; ok { + t.Error("booking.reminder carries start_at although the webhook selected only id") + } + if _, ok := data["booking.created"]["hours_before"]; ok { + t.Error("booking.created carries hours_before") + } +} diff --git a/internal/webhook/webhook.go b/internal/webhook/webhook.go index 2b90d433..f756f652 100644 --- a/internal/webhook/webhook.go +++ b/internal/webhook/webhook.go @@ -59,6 +59,10 @@ const ( FieldInviteDelivery = "invite_delivery" ) +// FieldHoursBefore is not selectable: it describes the event (which reminder fired) +// rather than the booking, so booking.reminder always carries it and nothing else does. +const FieldHoursBefore = "hours_before" + // AllFields is every selectable field, in payload order. Used to validate config // and (UI) to render the checkbox list. var AllFields = []string{ @@ -133,6 +137,10 @@ type BookingPayload struct { // RSVPStatus is the booker's answer to a Calnode-sent invite (accepted, declined, // tentative); set on booking.rsvp only. RSVPStatus string `json:"rsvp_status,omitempty"` + // HoursBefore is which configured reminder fired (the event type's hours_before); + // set on booking.reminder only, and always sent with it whatever the webhook's field + // selection, since a sender that fires at 24h and 2h has to tell them apart. + HoursBefore int `json:"hours_before,omitempty"` } type Service struct { @@ -370,6 +378,9 @@ func buildData(bd enrichedBooking, fields []string) map[string]any { out[f] = bd.core.AmountPaidCents } } + if bd.core.HoursBefore > 0 { + out[FieldHoursBefore] = bd.core.HoursBefore + } return out } @@ -377,6 +388,32 @@ func buildData(bd enrichedBooking, fields []string) map[string]any { // and creates a webhook_deliveries + jobs row pair for each. Failures are // soft-errors (caller logs; a booking is already committed). func (s *Service) Enqueue(ctx context.Context, event string, p BookingPayload) error { + return s.enqueue(ctx, event, p, "") +} + +// EnqueueOnce is Enqueue for an event that a retried job may raise more than once. +// Each delivery's ID is derived from the webhook ID and key instead of being random, and +// is inserted with INSERT OR IGNORE, so a second call with the same key creates neither +// a delivery nor a job for a webhook that already has one. The ID is also what receivers +// see in X-Calnode-Delivery, so it stays stable for them too. +func (s *Service) EnqueueOnce(ctx context.Context, event string, p BookingPayload, key string) error { + if key == "" { + return errors.New("webhook: EnqueueOnce needs a key") + } + return s.enqueue(ctx, event, p, key) +} + +// deliveryIDFor derives a UUID-shaped delivery ID (version 5 bits, SHA-256 based) from +// the webhook and the caller's key, so it fits wherever a random delivery ID does. +func deliveryIDFor(webhookID, key string) string { + sum := sha256.Sum256([]byte(webhookID + "\x00" + key)) + b := sum[:16] + b[6] = (b[6] & 0x0f) | 0x50 + b[8] = (b[8] & 0x3f) | 0x80 + return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]) +} + +func (s *Service) enqueue(ctx context.Context, event string, p BookingPayload, key string) error { rows, err := s.db.QueryContext(ctx, ` SELECT id, events, fields FROM webhooks WHERE user_id = ? AND is_active = 1`, p.HostID) @@ -456,13 +493,21 @@ func (s *Service) Enqueue(ctx context.Context, event string, p BookingPayload) e } deliveryID := uid.New() + insert := `INSERT INTO webhook_deliveries (id, webhook_id, booking_id, event, payload, status) + VALUES (?, ?, ?, ?, ?, 'pending')` + if key != "" { + deliveryID = deliveryIDFor(wh.id, key) + insert = `INSERT OR IGNORE INTO webhook_deliveries (id, webhook_id, booking_id, event, payload, status) + VALUES (?, ?, ?, ?, ?, 'pending')` + } jobID := uid.New() - if _, err := tx.ExecContext(ctx, ` - INSERT INTO webhook_deliveries (id, webhook_id, booking_id, event, payload, status) - VALUES (?, ?, ?, ?, ?, 'pending')`, - deliveryID, wh.id, bookingIDArg, event, string(payloadBytes)); err != nil { + res, err := tx.ExecContext(ctx, insert, deliveryID, wh.id, bookingIDArg, event, string(payloadBytes)) + if err != nil { return fmt.Errorf("webhook: insert delivery: %w", err) } + if n, err := res.RowsAffected(); err == nil && n == 0 { + continue // EnqueueOnce: this webhook already has the delivery for key + } jobPayload, _ := json.Marshal(map[string]string{"webhook_delivery_id": deliveryID}) if _, err := tx.ExecContext(ctx, ` INSERT INTO jobs (id, type, payload, run_at) diff --git a/internal/worker/reminder_webhook_test.go b/internal/worker/reminder_webhook_test.go new file mode 100644 index 00000000..a9d39ab3 --- /dev/null +++ b/internal/worker/reminder_webhook_test.go @@ -0,0 +1,235 @@ +package worker_test + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/calnode/calnode/internal/mailer" + "github.com/calnode/calnode/internal/webhook" + "github.com/calnode/calnode/internal/worker" +) + +// flakyMailer fails the first `fail` sends, then records like captureMailer. +type flakyMailer struct { + fail int + sent []mailer.Message +} + +func (m *flakyMailer) Send(_ context.Context, msg mailer.Message) error { + if m.fail > 0 { + m.fail-- + return errors.New("smtp: temporary failure") + } + m.sent = append(m.sent, msg) + return nil +} + +// seedReminderBooking creates a confirmed booking for host-01, a webhook subscribed to +// booking.reminder pointing at a local receiver, and one due reminder.send job. +func seedReminderBooking(t *testing.T, database *sql.DB, svc *webhook.Service, hoursBefore int) (start string) { + t.Helper() + ctx := context.Background() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(srv.Close) + + start = time.Now().UTC().Add(time.Duration(hoursBefore)*time.Hour + 30*time.Minute).Truncate(time.Second).Format(time.RFC3339) + end := time.Now().UTC().Add(time.Duration(hoursBefore)*time.Hour + time.Hour).Truncate(time.Second).Format(time.RFC3339) + database.ExecContext(ctx, + `INSERT INTO event_types (id, user_id, slug, name, duration_minutes) + VALUES ('et-rw','host-01','rem-wh','Reminder Webhook',30)`) + database.ExecContext(ctx, + `INSERT INTO bookings (id, event_type_id, host_id, start_at, end_at, status, location_value) + VALUES ('bk-rw','et-rw','host-01',?,?,'confirmed','+48 500 000 000')`, start, end) + database.ExecContext(ctx, + `INSERT INTO booking_attendees (id, booking_id, name, email, iana_timezone, is_organizer) + VALUES ('att-rw','bk-rw','Alice','alice@example.com','Europe/Warsaw',1)`) + if _, _, err := svc.Create(ctx, "host-01", srv.URL, []string{"booking.reminder"}); err != nil { + t.Fatalf("create webhook: %v", err) + } + queueReminderJob(t, database, "job-rw-1", hoursBefore) + return start +} + +func queueReminderJob(t *testing.T, database *sql.DB, id string, hoursBefore int) { + t.Helper() + payload, _ := json.Marshal(map[string]any{"booking_id": "bk-rw", "hours_before": hoursBefore}) + if _, err := database.ExecContext(context.Background(), ` + INSERT INTO jobs (id, type, payload, run_at, status, attempts, max_attempts) + VALUES (?, 'reminder.send', ?, ?, 'pending', 0, 3)`, + id, string(payload), time.Now().UTC().Add(-time.Second).Format(time.RFC3339)); err != nil { + t.Fatalf("queue reminder job: %v", err) + } +} + +type reminderDelivery struct { + id string + data map[string]any +} + +func reminderDeliveries(t *testing.T, database *sql.DB) []reminderDelivery { + t.Helper() + rows, err := database.QueryContext(context.Background(), + `SELECT id, payload FROM webhook_deliveries WHERE event = 'booking.reminder' ORDER BY rowid`) + if err != nil { + t.Fatalf("query deliveries: %v", err) + } + defer rows.Close() + var out []reminderDelivery + for rows.Next() { + var id, payload string + rows.Scan(&id, &payload) + var env struct { + Event string `json:"event"` + Data map[string]any `json:"data"` + } + if err := json.Unmarshal([]byte(payload), &env); err != nil { + t.Fatalf("payload: %v", err) + } + if env.Event != "booking.reminder" { + t.Errorf("envelope event = %q; want booking.reminder", env.Event) + } + out = append(out, reminderDelivery{id: id, data: env.Data}) + } + return out +} + +func reminderWorker(database *sql.DB, svc *webhook.Service, m mailer.Mailer) *worker.Worker { + return worker.New(database, svc, slog.Default(), + worker.WithMailer(m), + worker.WithHTTPClient(&http.Client{Timeout: 10 * time.Second})) +} + +func TestWorker_reminderFiresBookingReminderWebhook(t *testing.T) { + database, svc := setup(t) + start := seedReminderBooking(t, database, svc, 2) + m := &captureMailer{} + reminderWorker(database, svc, m).Poll(context.Background()) + + if len(m.sent) != 1 { + t.Fatalf("emails = %d; want 1 (the webhook is in addition to the email)", len(m.sent)) + } + ds := reminderDeliveries(t, database) + if len(ds) != 1 { + t.Fatalf("booking.reminder deliveries = %d; want 1", len(ds)) + } + d := ds[0].data + for k, want := range map[string]any{ + "id": "bk-rw", + "host_id": "host-01", + "event_type_slug": "rem-wh", + "status": "confirmed", + "start_at": start, + "location_value": "+48 500 000 000", + "hours_before": float64(2), + } { + if d[k] != want { + t.Errorf("data[%q] = %v; want %v", k, d[k], want) + } + } +} + +// The webhook is gated by the same preference as the reminder email. +func TestWorker_reminderWebhookRespectsNotifyReminder(t *testing.T) { + database, svc := setup(t) + seedReminderBooking(t, database, svc, 2) + database.Exec(`UPDATE users SET notify_reminder = 0 WHERE id = 'host-01'`) + m := &captureMailer{} + reminderWorker(database, svc, m).Poll(context.Background()) + + if len(m.sent) != 0 { + t.Errorf("emails = %d; want 0", len(m.sent)) + } + if ds := reminderDeliveries(t, database); len(ds) != 0 { + t.Errorf("booking.reminder deliveries = %d; want 0 with reminders turned off", len(ds)) + } +} + +func TestWorker_reminderWebhookSkipsCancelledBooking(t *testing.T) { + database, svc := setup(t) + seedReminderBooking(t, database, svc, 2) + database.Exec(`UPDATE bookings SET status = 'cancelled' WHERE id = 'bk-rw'`) + reminderWorker(database, svc, &captureMailer{}).Poll(context.Background()) + + if ds := reminderDeliveries(t, database); len(ds) != 0 { + t.Errorf("booking.reminder deliveries = %d; want 0 for a cancelled booking", len(ds)) + } +} + +// The email failing after the webhook was enqueued makes the job retry; the retry must +// not enqueue the same reminder again (the "08:00 and 08:01" case). +func TestWorker_reminderRetryDoesNotDuplicateWebhook(t *testing.T) { + database, svc := setup(t) + seedReminderBooking(t, database, svc, 2) + m := &flakyMailer{fail: 1} + w := reminderWorker(database, svc, m) + ctx := context.Background() + + w.Poll(ctx) + var status string + var attempts int + database.QueryRow(`SELECT status, attempts FROM jobs WHERE id = 'job-rw-1'`).Scan(&status, &attempts) + if status != "pending" || attempts != 1 { + t.Fatalf("after failed email: job status=%q attempts=%d; want pending/1", status, attempts) + } + + // Skip the backoff and retry. + database.Exec(`UPDATE jobs SET run_at = ? WHERE id = 'job-rw-1'`, + time.Now().UTC().Add(-time.Second).Format(time.RFC3339)) + w.Poll(ctx) + + if len(m.sent) != 1 { + t.Fatalf("emails = %d; want 1 after the retry", len(m.sent)) + } + if ds := reminderDeliveries(t, database); len(ds) != 1 { + t.Errorf("booking.reminder deliveries = %d; want 1 across the retry", len(ds)) + } + var jobs int + database.QueryRow(`SELECT COUNT(*) FROM jobs WHERE type = 'webhook.deliver'`).Scan(&jobs) + if jobs != 1 { + t.Errorf("webhook.deliver jobs = %d; want 1", jobs) + } +} + +// Each configured reminder, and each new time after a reschedule, gets its own event; +// running the same reminder for the same time again does not. +func TestWorker_reminderWebhookKeyedByHoursAndStart(t *testing.T) { + database, svc := setup(t) + start := seedReminderBooking(t, database, svc, 2) + w := reminderWorker(database, svc, &captureMailer{}) + ctx := context.Background() + w.Poll(ctx) + + queueReminderJob(t, database, "job-rw-24", 24) // a second configured reminder + w.Poll(ctx) + queueReminderJob(t, database, "job-rw-dup", 2) // same reminder, same time again + w.Poll(ctx) + + newStart := time.Now().UTC().Add(5 * time.Hour).Truncate(time.Second).Format(time.RFC3339) + database.Exec(`UPDATE bookings SET start_at = ? WHERE id = 'bk-rw'`, newStart) + queueReminderJob(t, database, "job-rw-moved", 2) // rescheduled + w.Poll(ctx) + + ds := reminderDeliveries(t, database) + if len(ds) != 3 { + t.Fatalf("booking.reminder deliveries = %d; want 3 (2h, 24h, 2h after reschedule)", len(ds)) + } + got := [][2]any{} + for _, d := range ds { + got = append(got, [2]any{d.data["hours_before"], d.data["start_at"]}) + } + want := [][2]any{{float64(2), start}, {float64(24), start}, {float64(2), newStart}} + for i := range want { + if got[i] != want[i] { + t.Errorf("delivery %d = %v; want %v", i, got[i], want[i]) + } + } +} diff --git a/internal/worker/worker.go b/internal/worker/worker.go index 68bedbb2..4b752e2f 100644 --- a/internal/worker/worker.go +++ b/internal/worker/worker.go @@ -289,7 +289,8 @@ func (w *Worker) processJob(ctx context.Context, typ, payload string) error { func (w *Worker) sendReminder(ctx context.Context, payload string) error { var p struct { - BookingID string `json:"booking_id"` + BookingID string `json:"booking_id"` + HoursBefore int `json:"hours_before"` } if err := json.Unmarshal([]byte(payload), &p); err != nil { return fmt.Errorf("worker: reminder: parse payload: %w", err) @@ -300,18 +301,18 @@ func (w *Worker) sendReminder(ctx context.Context, payload string) error { // Skip if booking is deleted or no longer confirmed. var d mailer.BookingData d.BookingID = p.BookingID - var startAt, endAt, status string + var startAt, endAt, status, hostID, createdAt string var locVal, msgReminder, subjReminder sql.NullString var notifyReminder int err := w.db.QueryRowContext(ctx, ` - SELECT b.status, b.start_at, b.end_at, b.location_value, + SELECT b.status, b.start_at, b.end_at, b.location_value, b.host_id, b.created_at, et.name, et.slug, et.msg_reminder, et.subj_reminder, u.name, u.email, COALESCE(u.notify_reminder, 1) FROM bookings b JOIN event_types et ON et.id = b.event_type_id JOIN users u ON u.id = b.host_id WHERE b.id = ?`, p.BookingID). - Scan(&status, &startAt, &endAt, &locVal, + Scan(&status, &startAt, &endAt, &locVal, &hostID, &createdAt, &d.EventTypeName, &d.EventTypeSlug, &msgReminder, &subjReminder, &d.HostName, &d.HostEmail, ¬ifyReminder) if err == sql.ErrNoRows { @@ -344,6 +345,10 @@ func (w *Worker) sendReminder(ctx context.Context, payload string) error { d.SubjectOverride = subjReminder.String } + if err := w.enqueueReminderWebhook(ctx, p.BookingID, p.HoursBefore, hostID, status, createdAt, d); err != nil { + return err + } + // Load organizer attendee. var locale string orgErr := w.db.QueryRowContext(ctx, ` @@ -371,6 +376,37 @@ func (w *Worker) sendReminder(ctx context.Context, payload string) error { return nil } +// enqueueReminderWebhook raises booking.reminder for the reminder being sent. It runs +// after the same checks that gate the email (booking still confirmed, host's +// notify_reminder on), so an external SMS/push sender stays off whenever the email +// would. It runs before the email: if sending the email fails the job retries, and the +// delivery key (booking, hours_before, start) collapses the second enqueue, so the +// receiver never gets the same reminder twice. A reschedule changes start_at and +// therefore the key, so the new time gets its own reminder. +func (w *Worker) enqueueReminderWebhook(ctx context.Context, bookingID string, hoursBefore int, + hostID, status, createdAt string, d mailer.BookingData) error { + start := d.StartAt.UTC().Format(time.RFC3339) + created := createdAt + if t, err := time.Parse(time.RFC3339Nano, createdAt); err == nil { + created = t.UTC().Format(time.RFC3339) + } + key := fmt.Sprintf("booking.reminder|%s|%d|%s", bookingID, hoursBefore, start) + if err := w.svc.EnqueueOnce(ctx, "booking.reminder", webhook.BookingPayload{ + ID: bookingID, + EventTypeSlug: d.EventTypeSlug, + HostID: hostID, + StartAt: start, + EndAt: d.EndAt.UTC().Format(time.RFC3339), + Status: status, + LocationValue: d.LocationValue, + CreatedAt: created, + HoursBefore: hoursBefore, + }, key); err != nil { + return fmt.Errorf("worker: reminder: enqueue booking.reminder webhook: %w", err) + } + return nil +} + func (w *Worker) deliverWebhook(ctx context.Context, jobPayload string) error { var p struct { WebhookDeliveryID string `json:"webhook_delivery_id"`