Skip to content

feat(hosted-events): HostedEventService + email + reminder (Phase C + F)#44

Closed
Ceesaxp wants to merge 1 commit into
claude/refine-local-plan-9weBMfrom
feature/hosted-event-service
Closed

feat(hosted-events): HostedEventService + email + reminder (Phase C + F)#44
Ceesaxp wants to merge 1 commit into
claude/refine-local-plan-9weBMfrom
feature/hosted-event-service

Conversation

@Ceesaxp

@Ceesaxp Ceesaxp commented May 6, 2026

Copy link
Copy Markdown
Owner

Summary

Phase C + F of the host-driven event scheduling work. Builds on the syncer + schema/repos already in #43 (this PR is targeted at #43's branch so the diff shows only the new work; once #43 merges to main, this PR will auto-rebase).

This PR is service + tests only — no handlers, no UI, no migrations. The next PR adds Phase D + E (routes/handlers + the dashboard UI via the `frontend-design` skill).

What's new

`HostedEventService` (`internal/services/hosted_event.go`)

Public surface: `Create`, `Update`, `Cancel`, `Get`, `List`, `Archive`, `Unarchive`, `RetryCalendarEvent`, `DetectBusyConflicts`.

Behavioural notes worth highlighting in review:

  • Calendar resolution priority: explicit `CalendarID` input → template default → host `DefaultCalendarID` → first writable (the last fallback comes free from the syncer).
  • Two-write conferencing-link sequencing: Zoom path persists the link first, then `syncer.Create` may surface a Google Meet link from the calendar create response, which is persisted with a second write.
  • `ErrConferencingReauthRequired` on `Create` is logged and swallowed — the event still goes out without a link, matching booking-flow parity. On `Update` it surfaces.
  • `reminder_sent` is reset to `false` when `Start` changes so the reminder loop re-fires for the new time.
  • Contact upsert fires only for newly added attendees, so retained attendees don't get `meeting_count` / `last_met` re-incremented on benign edits.
  • `DetectBusyConflicts` merges three sources — provider busy times, confirmed bookings, other hosted events — with `excludeEventID` for self-edit.
  • The service depends on a narrow `hostedEventEmailSender` interface so tests can inject a spy without dialling SMTP. `*EmailService` satisfies it.

Conferencing (`internal/services/conferencing.go`)

Extracted `createZoomMeetingRaw(ctx, hostID, topic, start, durationMin)` so both bookings and hosted events share the Zoom API call. New `CreateMeetingForHostedEvent(...)`. Existing `CreateMeeting(details)` keeps its public signature and now delegates internally.

Contacts (`internal/services/contact.go`)

New `UpsertFromHostedEventAttendee(ctx, tenantID, email, name, eventStart)`.

Email (`internal/services/email.go`)

Five new send methods following the inline-Go-string pattern of `SendBookingConfirmed` (`email.go:184`):

  • `SendHostedEventInvited`
  • `SendHostedEventUpdated` (with `changedFields`)
  • `SendHostedEventCancelled` (METHOD:CANCEL ICS)
  • `SendHostedEventCancelledForAttendee` (METHOD:CANCEL ICS, attendee-scoped)
  • `SendHostedEventReminder`

Plus `generateICSForHostedEvent(event, host, attendee, method, status)`.

Reminder (`internal/services/reminder.go`)

`checkAndSendReminders` now splits into `processBookingReminders` + `processHostedEventReminders` so a failure in one source can't abort the other.

Tests

`internal/services/hosted_event_test.go` — 13 cases:

  • `PersistsEventAndAttendees`
  • `ResolvesCalendarFromExplicit`
  • `ResolvesCalendarFromTemplateThenHost`
  • `ConferencingReauthRequired_StillPersistsEvent`
  • `GoogleMeet_LinkFromSyncerPersisted`
  • `SendsInvitedEmailToEachAttendee`
  • `UpsertsContactsForAttendees`
  • `Update_AttendeeDiff_RoutesEmailsCorrectly` (added/removed/retained → invited/cancelled-for-attendee/updated)
  • `Update_TimeChange_ResetsReminderSent`
  • `Update_NoMaterialChange_SendsNoEmail`
  • `Update_PatchesAllTrackedCalendarEvents`
  • `Update_ContactNotReupsertedForRetained`
  • `Cancel_DeletesTrackedRowsAndEmails`
  • `DetectBusyConflicts_ExcludesSelf`

`internal/services/reminder_test.go` — `processHostedEventReminders` flips `reminder_sent` and prevents re-fire.

Verification

Test plan

  • Review the calendar-resolution priority + the two-write conferencing-link sequencing in `Create`
  • Review the attendee-diff logic in `Update` (added/removed/retained, contact-upsert added-only, reminder_sent reset)
  • Review the email content for tone + ICS METHOD/STATUS pairing
  • Confirm the reminder loop split is the right approach

🤖 Generated with Claude Code

Phase C + F of the host-driven event scheduling work, building on PR #43's
CalendarEventSyncer + repos. No UI yet — that's the next PR.

Service (internal/services/hosted_event.go):
- HostedEventService with Create / Update / Cancel / Get / List / Archive /
  Unarchive / RetryCalendarEvent / DetectBusyConflicts.
- Calendar resolution: explicit input → template → host default → first
  writable (the syncer's resolveWritableCalendarID handles the last fallback).
- Conferencing-link write happens twice: once after CreateMeetingForHostedEvent
  (Zoom path) and again after the syncer surfaces a Google Meet link from the
  calendar create response — matches the booking flow's coupling.
- ErrConferencingReauthRequired on create logs and continues; the event still
  persists. On Update it surfaces (parity with booking.go:425).
- Update flow computes field + attendee diffs (lowercased email keys),
  resets reminder_sent when Start changes, and only upserts contacts for
  newly added attendees so retained attendees don't get meeting_count
  re-incremented on a benign edit.
- Email diff: removed → SendHostedEventCancelledForAttendee, added →
  SendHostedEventInvited, retained (when material field changed) →
  SendHostedEventUpdated.
- DetectBusyConflicts merges three sources (provider busy, confirmed
  bookings, scheduled hosted events) with excludeEventID for self-edit.
- Service depends on a narrow hostedEventEmailSender interface so tests
  can inject a spy without dialling SMTP.

Conferencing (internal/services/conferencing.go):
- Extracted createZoomMeetingRaw(ctx, hostID, topic, start, durationMin) so
  both bookings and hosted events share the Zoom API call.
- New CreateMeetingForHostedEvent(ctx, hostID, title, start, duration,
  locationType, customLocation). CreateMeeting(details) keeps its existing
  signature and now delegates to createZoomMeetingRaw internally.

Contacts (internal/services/contact.go):
- New UpsertFromHostedEventAttendee. Callers invoke this only for newly
  added attendees so meeting_count and last_met don't drift on edits.

Email (internal/services/email.go):
- SendHostedEventInvited / Updated / Cancelled / CancelledForAttendee /
  Reminder, plus generateICSForHostedEvent. Inline-Go-string pattern
  matching SendBookingConfirmed at email.go:184. Cancellation paths emit
  METHOD:CANCEL ICS so calendar clients remove the event.

Reminder (internal/services/reminder.go):
- checkAndSendReminders now splits into processBookingReminders +
  processHostedEventReminders so a partial failure in one source doesn't
  abort the other.

Tests:
- internal/services/hosted_event_test.go: 13 cases covering persistence,
  calendar resolution priority, ErrConferencingReauthRequired handling,
  Google Meet link surfacing through the syncer, invited-email fan-out,
  contact upsert, attendee-diff email routing (added/removed/retained),
  reminder_sent reset on Start change, no-op-update sends no email,
  Update.PatchesAllTrackedCalendarEvents, retained-attendee contact
  not re-upserted, Cancel deletes tracking rows + cancellation emails,
  DetectBusyConflicts excludes self when editing.
- internal/services/reminder_test.go: end-to-end pass through
  processHostedEventReminders flips reminder_sent and prevents re-fire.

go vet clean. All previously-passing tests still pass. Build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@Ceesaxp
Ceesaxp deleted the branch claude/refine-local-plan-9weBM May 7, 2026 13:41
@Ceesaxp Ceesaxp closed this May 7, 2026
@Ceesaxp
Ceesaxp deleted the feature/hosted-event-service branch May 7, 2026 13:43
Ceesaxp added a commit that referenced this pull request May 7, 2026
… + E) (#47)

* refactor(calendar): extract calendar fan-out into CalendarEventSyncer

Phase A of the host-driven event scheduling work (see plan in
/root/.claude/plans/here-is-a-draft-cryptic-crane.md). Pure refactor; no
behavioural change for bookings.

- Introduce CalendarEventInput as a provider-agnostic event shape and
  refactor CreateEventForHost / UpdateEvent / the private Google + CalDAV
  helpers to take it. CreateEvent(*BookingWithDetails) stays as a thin
  booking-side adapter; new BuildCalendarEventInputForBooking composes
  description + reschedule URL + attendees from the booking shape.
- Add the calendarEventWriter interface so the syncer can be tested
  without hitting the network.
- New CalendarEventSyncer.Create / Update / Delete fans out across all
  host targets and persists tracking rows in booking_calendar_events.
  The Update path explicitly persists any replacement event_id returned
  by the calendar layer (CalDAV delete+create or fall-through to create
  when the prior ID was empty), so subsequent updates and deletes target
  the correct provider event.
- BookingService loses its three duplicate fan-out helpers
  (createPooledHostCalendarEvents, updateAllCalendarEvents,
  deleteAllCalendarEvents) and now goes through the syncer. The legacy
  pre-pooled-host fallback (booking.CalendarEventID with
  template.CalendarID) is preserved for old rows.
- Regression tests cover one-host create, pooled-host fan-out, per-host
  failure isolation, the CalDAV replacement-id and prior-id-empty
  persistence invariants, delete fan-out, and Google Meet conference
  link surfacing.

https://claude.ai/code/session_01YWosUoHN5qrc7bTrTv1hzM

* feat(hosted-events): schema, models, and repositories

Phase B of the host-driven event scheduling work. DB-only — no service or
handler wiring yet.

- Migration 014 adds hosted_events, hosted_event_attendees, and
  hosted_event_calendar_events for both postgres (root migrations/) and
  sqlite (migrations/sqlite/). status enum is intentionally narrow for v1
  (scheduled | cancelled).
- Models HostedEvent, HostedEventAttendee, HostedEventCalendarEvent, and
  HostedEventStatus mirror the booking shapes' SQLiteTime / db tag /
  json tag style.
- HostedEventRepository: Create, GetByID, Update, ListByHost,
  GetByHostIDAndTimeRange (with excludeEventID for self-collision
  filtering on edits), GetUpcomingForReminders, MarkReminderSent.
- HostedEventAttendeeRepository.ReplaceForEvent: atomic delete-and-insert
  in a transaction. Source of truth for the attendee diff is whatever
  this method commits.
- HostedEventCalendarEventRepository: Create / GetByHostedEventID /
  Update / DeleteByHostedEventID — same shape as
  BookingCalendarEventRepository.
- Register the hostedEventTrackingStore on CalendarEventSyncer so the
  ItemKindHostedEvent dispatch is now wired (was a stub in Phase A).
- Round-trip tests for the new repos under sqlite.

Note on placeholders: q(driver, sql) does plain regex substitution of $N
to ?, so under sqlite the bind order follows the order placeholders
appear in the query — not their numeric value. Out-of-order $1/$3/$2
silently mis-binds. New time-range methods order placeholders strictly
ascending and document this constraint inline.

https://claude.ai/code/session_01YWosUoHN5qrc7bTrTv1hzM

* feat(hosted-events): HostedEventService + email + reminder integration

Phase C + F of the host-driven event scheduling work, building on PR #43's
CalendarEventSyncer + repos. No UI yet — that's the next PR.

Service (internal/services/hosted_event.go):
- HostedEventService with Create / Update / Cancel / Get / List / Archive /
  Unarchive / RetryCalendarEvent / DetectBusyConflicts.
- Calendar resolution: explicit input → template → host default → first
  writable (the syncer's resolveWritableCalendarID handles the last fallback).
- Conferencing-link write happens twice: once after CreateMeetingForHostedEvent
  (Zoom path) and again after the syncer surfaces a Google Meet link from the
  calendar create response — matches the booking flow's coupling.
- ErrConferencingReauthRequired on create logs and continues; the event still
  persists. On Update it surfaces (parity with booking.go:425).
- Update flow computes field + attendee diffs (lowercased email keys),
  resets reminder_sent when Start changes, and only upserts contacts for
  newly added attendees so retained attendees don't get meeting_count
  re-incremented on a benign edit.
- Email diff: removed → SendHostedEventCancelledForAttendee, added →
  SendHostedEventInvited, retained (when material field changed) →
  SendHostedEventUpdated.
- DetectBusyConflicts merges three sources (provider busy, confirmed
  bookings, scheduled hosted events) with excludeEventID for self-edit.
- Service depends on a narrow hostedEventEmailSender interface so tests
  can inject a spy without dialling SMTP.

Conferencing (internal/services/conferencing.go):
- Extracted createZoomMeetingRaw(ctx, hostID, topic, start, durationMin) so
  both bookings and hosted events share the Zoom API call.
- New CreateMeetingForHostedEvent(ctx, hostID, title, start, duration,
  locationType, customLocation). CreateMeeting(details) keeps its existing
  signature and now delegates to createZoomMeetingRaw internally.

Contacts (internal/services/contact.go):
- New UpsertFromHostedEventAttendee. Callers invoke this only for newly
  added attendees so meeting_count and last_met don't drift on edits.

Email (internal/services/email.go):
- SendHostedEventInvited / Updated / Cancelled / CancelledForAttendee /
  Reminder, plus generateICSForHostedEvent. Inline-Go-string pattern
  matching SendBookingConfirmed at email.go:184. Cancellation paths emit
  METHOD:CANCEL ICS so calendar clients remove the event.

Reminder (internal/services/reminder.go):
- checkAndSendReminders now splits into processBookingReminders +
  processHostedEventReminders so a partial failure in one source doesn't
  abort the other.

Tests:
- internal/services/hosted_event_test.go: 13 cases covering persistence,
  calendar resolution priority, ErrConferencingReauthRequired handling,
  Google Meet link surfacing through the syncer, invited-email fan-out,
  contact upsert, attendee-diff email routing (added/removed/retained),
  reminder_sent reset on Start change, no-op-update sends no email,
  Update.PatchesAllTrackedCalendarEvents, retained-attendee contact
  not re-upserted, Cancel deletes tracking rows + cancellation emails,
  DetectBusyConflicts excludes self when editing.
- internal/services/reminder_test.go: end-to-end pass through
  processHostedEventReminders flips reminder_sent and prevents re-fire.

go vet clean. All previously-passing tests still pass. Build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(hosted-events): dashboard handler, routes, and UI templates (Phase D + E)

Phase D + E of host-driven event scheduling. Builds on the
HostedEventService introduced in #44 and exposes it through 12 dashboard
routes plus 6 HTML templates. Sidebar gets a "Schedule Event" item between
Templates and Bookings.

## Routes (cmd/server/main.go)

- GET  /dashboard/events                       — list (?archived=true to include)
- GET  /dashboard/events/new                   — create form (?template=ID prefills)
- POST /dashboard/events                       — create
- GET  /dashboard/events/check-conflicts       — HTMX partial; busy-time merge
- GET  /dashboard/events/attendee-search       — HTMX partial; contact autocomplete
- GET  /dashboard/events/{id}/details          — modal partial
- GET  /dashboard/events/{id}/edit             — full edit form
- POST /dashboard/events/{id}/edit             — update
- POST /dashboard/events/{id}/cancel           — cancel
- POST /dashboard/events/{id}/archive          — archive
- POST /dashboard/events/{id}/unarchive        — unarchive
- POST /dashboard/events/{id}/retry-calendar   — retry calendar event creation

The HTMX partial routes use the /events/check-conflicts and
/events/attendee-search paths so they don't shadow {id}.

## Handler (internal/handlers/dashboard_events.go)

DashboardEventsHandler wired on the Handlers struct alongside Dashboard.
Form parsing uses parallel-indexed repeated form fields
(attendee_email/_name/_contact_id), matching the existing pattern used by
the templates handler. parseDateTimeInTZ combines the form's date + time +
timezone fields into a UTC time.Time before handing to the service. Update
flow uses pointer fields on UpdateHostedEventInput so the form can express
"unchanged" vs "set to empty".

## Templates (Phase E)

All six new templates reuse the existing primitives — `.section`,
`.section-header`, `.form-input`, `.form-select`, `.form-textarea`,
`.form-label`, `.form-hint`, `.btn .btn-primary/.btn-secondary/.btn-outline`,
`.btn-sm`, `.badge`, `.table-container/.table`, `.duration-chips`,
`.radio-cards`, `.modal-overlay/.modal-content/.modal-header/.modal-body`,
`.empty-state`, `.alert/.alert-warning/.alert-error`. No new CSS files; the
attendee chip styling is a small inline block confined to the form template.

- templates/pages/dashboard_events.html              — list + filter view
- templates/pages/dashboard_event_form.html          — create + edit form
- templates/partials/events_table_partial.html       — table body
- templates/partials/event_attendee_picker_results.html — autocomplete results
- templates/partials/event_conflict_warning.html     — soft conflict banner
- templates/partials/dashboard_event_detail_partial.html — modal detail

The form has 7 sections (Template prefill (new only) → Basics → When →
Location → Calendar → Attendees) with HTMX-driven conflict warnings and
contact autocomplete. Modal pattern matches the booking flow's recent
fetch-based approach (#41 pattern).

## Tests

internal/handlers/dashboard_events_test.go — 9 cases:

- TestEventAttendeePickerResults_RendersContacts
- TestEventAttendeePickerResults_EmptyShowsFreeFormHint
- TestEventAttendeePickerResults_EmptyAndNoQuery_RendersNothing
- TestEventConflictWarning_RendersConflicts (asserts pluralisation + soft-warning copy)
- TestEventConflictWarning_NoConflicts_RendersEmpty
- TestEventsTablePartial_RendersScheduledAndCancelled (status-routed badges + actions)
- TestEventForm_NewMode_RendersTitleAndAttendeePicker
- TestEventForm_EditMode_PrefillsAndCarriesExcludeEventID (zoom + 45-min + exclude_event_id)
- TestEventForm_FormErrorRendersHumanCopy (at_least_one_attendee → human copy)

Pattern matches internal/handlers/template_test.go: load real template
files, render to bytes.Buffer, assert strings. Tests render the {{define
"content"}} blocks directly to avoid the layout-loading dependency.

`make test`, `go vet ./...`, `go build ./cmd/server` all clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant