feat(tier2): reminders + broadcasts pipeline — Block F

The Communications surface. Hosts can schedule custom broadcasts to a
chosen audience (everyone / attending / pending / declined / maybe),
edit or cancel anything that hasn't fired, and review delivery
outcomes. Four auto-reminders are pre-seeded on every new event:
7-day, 3-day last call, 1-day, and day-of.

Schema (migration 0012)
- scheduled_messages — one row per message envelope, with status
  walking draft -> scheduled -> sending -> sent (or cancelled/failed).
  Partial index on (send_at) WHERE status='scheduled' for the
  scheduler poll; per-event index for the Communications tab list.
- message_deliveries — per-recipient outcomes so a partial-failure
  batch doesn't lose the rows that did succeed.

Domain
- MessageAudience / MessageChannel / MessageStatus enums
- SeedAutoReminders helper that returns four canonical reminder rows
  for a given event_date, skipping any whose send_at would land in
  the past (events created close to the date)

Storage
- MessageRepo: Create / CreateBatch / Get / ListByEvent / Update
  (locks the row and refuses unless status is draft|scheduled) /
  Cancel / PromoteToScheduled (the send-now path) / ListDue /
  ClaimForSending (atomic guard against two replicas double-sending) /
  MarkSent / MarkFailed / RecordDelivery / DeliveryStats /
  LoadRecipients (audience-filtered guest list) / CountRecipients
- EventRepo.Create now seeds auto-reminders in the same transaction
  that inserts the event and its owner collaborator row

API (all editor+, except recipient-count which is viewer+)
- GET    /events/{id}/messages
- GET    /events/{id}/messages/recipient-count?audience=...
- POST   /events/{id}/messages   (draft / schedule / send-now)
- PATCH  /events/{id}/messages/{message_id}
- POST   /events/{id}/messages/{message_id}/send-now
- DELETE /events/{id}/messages/{message_id}

Scheduler worker (cmd/notifier)
- New file scheduler.go: polls ListDue every 30s, claims each row
  atomically (ClaimForSending uses a status=scheduled guard so two
  notifier replicas don't double-send), renders subject and body
  per recipient with the {{guest_name}} / {{event_name}} /
  {{event_date}} / {{venue}} / {{rsvp_link}} placeholders, sends via
  the existing GuestEmailDispatcher (Resend > SMTP > SES > log
  stub, same picker as the API), records each delivery row.

Frontend
- New CommunicationsCard.vue with compose form (audience + channel +
  subject + body + send-mode radios), live "X guests will receive
  this" recipient-count preview, and three sub-tabs for Scheduled /
  Sent / Cancelled. Per-message Send-now and Cancel actions for
  draft/scheduled rows. Friendly labels for auto-seeded reminders
  ("1-day reminder", "Day-of reminder") so the slugs never leak.
- New top-level tab "Communications" on the event-detail page,
  between Collaborators and Branding.

Tests
- TestAutoReminderSeeding confirms a future-dated event lands the
  four canonical reminders in scheduled state.
- TestComposeAndEditMessage walks draft -> patch -> send-now ->
  cancel and asserts the conflict on PATCH-after-cancel.
- TestRecipientCountAudienceFilter seeds a known guest mix and
  checks every audience preset returns the right count.
- Full integration suite passes (~177s).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Kwaku Danso
2026-05-20 16:56:37 +01:00
parent dbddf17e3b
commit dc840bfc14
12 changed files with 1859 additions and 7 deletions
@@ -0,0 +1,72 @@
-- Tier 2 Block F — reminders + broadcasts.
--
-- The Tier 2 plan called this the messages pipeline. Two tables:
--
-- scheduled_messages — one row per message envelope. Status moves
-- scheduled -> sending -> sent (or cancelled / failed).
-- message_deliveries — one row per recipient. Lets a partial-failure
-- batch keep the rows that did succeed and surface
-- the rest in the UI.
--
-- The scheduler worker (cmd/notifier) polls scheduled_messages by
-- send_at; the index supports that without a sequential scan even on
-- thousands of pending rows.
DO $$ BEGIN
CREATE TYPE message_audience AS ENUM ('all', 'attending', 'pending', 'declined', 'maybe');
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
DO $$ BEGIN
CREATE TYPE message_channel AS ENUM ('email', 'sms', 'both');
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
DO $$ BEGIN
CREATE TYPE message_status AS ENUM ('draft', 'scheduled', 'sending', 'sent', 'cancelled', 'failed');
EXCEPTION WHEN duplicate_object THEN NULL; END $$;
CREATE TABLE IF NOT EXISTS scheduled_messages (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE,
send_at TIMESTAMPTZ NOT NULL,
audience message_audience NOT NULL,
channel message_channel NOT NULL,
-- template_key tags the auto-seeded reminders ('reminder_7d',
-- 'reminder_1d', 'reminder_dayof', 'last_call'). NULL for hand-
-- composed broadcasts.
template_key TEXT,
subject TEXT,
body TEXT NOT NULL,
status message_status NOT NULL DEFAULT 'draft',
sent_at TIMESTAMPTZ,
recipient_count INTEGER,
-- created_by is the user who scheduled or composed the message.
-- NULL for system-seeded auto-reminders.
created_by UUID REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- The scheduler's hot query: "what's due right now?" Partial index keeps
-- it small even on events with hundreds of historical sent messages.
CREATE INDEX IF NOT EXISTS idx_messages_due
ON scheduled_messages (send_at)
WHERE status = 'scheduled';
-- "Show me this event's communications history" — used by the
-- Communications tab. Sorted newest-first so the index covers ORDER BY.
CREATE INDEX IF NOT EXISTS idx_messages_event
ON scheduled_messages (event_id, created_at DESC);
CREATE TABLE IF NOT EXISTS message_deliveries (
message_id UUID NOT NULL REFERENCES scheduled_messages(id) ON DELETE CASCADE,
guest_id UUID NOT NULL REFERENCES guests(id) ON DELETE CASCADE,
status TEXT NOT NULL, -- 'pending' | 'sent' | 'bounced' | 'skipped' | 'failed'
sent_at TIMESTAMPTZ,
error TEXT,
PRIMARY KEY (message_id, guest_id)
);
-- "Which delivers succeeded for this message?" — used by the per-message
-- drill-down in the UI.
CREATE INDEX IF NOT EXISTS idx_deliveries_message
ON message_deliveries (message_id, status);