From 8f3a7a72693e57565021137eb335f250bc471714 Mon Sep 17 00:00:00 2001 From: Dominik Myszkowski Date: Mon, 30 Nov 2026 11:12:29 +0100 Subject: [PATCH 1/2] feat(email): intake answers in the host's booking email, opt-in per event type (#264) event_types.answers_in_host_email (migration 00076, default off) lists the attendee's intake answers in each host's new-booking email, and in the new host's email when a booking is reassigned. Unanswered questions are left out. The answers travel in BookingData.HostAnswers, which only the host templates read and which is set only on each host's copy in notifyHosts, never on the data the attendee's email and .ics are built from. The calendar event description is deliberately not used: the attendee sees it in their own invite on Google, Microsoft and CalDAV. Editor: a checkbox in the Notifications tab (en/fr). Duplicating an event type carries the flag. --- CHANGELOG.md | 7 + docs/ARCHITECTURE.md | 8 + frontend/src/lib/api.ts | 3 + frontend/src/lib/i18n/en.json | 2 + frontend/src/lib/i18n/fr.json | 2 + .../routes/event-types/[slug]/+page.svelte | 12 + ...00076_event_type_answers_in_host_email.sql | 15 ++ internal/handler/booking_handler.go | 52 +++- internal/handler/event_type.go | 27 +- internal/handler/event_type_duplicate.go | 4 +- internal/handler/event_type_duplicate_test.go | 13 +- .../host_email_answers_internal_test.go | 236 ++++++++++++++++++ internal/handler/reassign.go | 3 + internal/mailer/booking.go | 25 +- internal/mailer/host_answers_test.go | 79 ++++++ internal/mailer/html.go | 5 + 16 files changed, 478 insertions(+), 15 deletions(-) create mode 100644 internal/db/migrations/00076_event_type_answers_in_host_email.sql create mode 100644 internal/handler/host_email_answers_internal_test.go create mode 100644 internal/mailer/host_answers_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1149229b..ba1e2543 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,13 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad is still pending is refused until the reconciler has removed it. A past meeting's event stays on the host's calendar, because removing it through the provider would email the guest; the dialog says so. Database backups keep the data until their own retention ends. +- **Intake answers in the host's booking email.** A per-event-type option (Notifications + tab, `answers_in_host_email`, off by default) lists the attendee's answers to the intake + questions in each host's new-booking email, and in the new host's email when a booking is + reassigned, so the context is at hand before the call. Only hosts get them. The + attendee's emails and the calendar event do not, because on Google, Microsoft and CalDAV + the attendee sees the event description in their own invite. Migration `00076` adds the + column. - **German without du or Sie (`de-x-neutral`).** An opt-in wording variant of the German booker catalogue that addresses nobody: "Tag auswählen" rather than "Wählen Sie einen Tag". It is for operators whose own site is informal, where the formal widget stands out diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 599c7672..03e880f4 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -757,6 +757,14 @@ as the desired state: - **Per-event-type customisation:** custom note bodies (`msg_*`) and custom subject lines (`subj_*`, migration 00026) for the four attendee emails; a blank subject falls back to the built-in default (`BookingData.SubjectOverride` / `subjectOr`). +- **Intake answers in the host's email** (`event_types.answers_in_host_email`, migration + 00076, **default off**, #264): each host's new-booking email (on create, and to the new + host on reassignment) lists the attendee's answers, unanswered ones left out + (`Handler.hostEmailAnswers`). They travel in `BookingData.HostAnswers`, which only the + host templates read and which is set only on each host's copy (`notifyHosts`), never on + the data the attendee's email and `.ics` are built from. The calendar event description + is deliberately **not** used: on Google, Microsoft and CalDAV the attendee is an invitee + and sees it in their own invite, so it is not a host-only channel. - **Branding (`branding_settings.go`, migrations 00029/00050):** instance-wide `business_name` + `logo_url` + `banner_url` on the singleton row. Business name is the wordmark fallback (defaults to "Calnode") + public-page header; the logo is the email diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index cd6c8723..f45c6353 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -39,6 +39,9 @@ export type EventType = { * them. Off by default: the slots endpoint is public, so this makes the host's * booked hours visible to anyone with the link. */ show_taken_slots: boolean; + /** List the attendee's intake answers in each host's new-booking email. Off by + * default; never added to the attendee's emails or the calendar event. */ + answers_in_host_email: boolean; /** Who sends the booker's calendar invite. 'calendar': each host's connected calendar, * from the host's own address. 'calnode': Calnode's own invite, from the email sender * in Settings → Email, so no host's personal address reaches the booker. 'none': no diff --git a/frontend/src/lib/i18n/en.json b/frontend/src/lib/i18n/en.json index 1a3870ce..f1ea9a61 100644 --- a/frontend/src/lib/i18n/en.json +++ b/frontend/src/lib/i18n/en.json @@ -1792,6 +1792,8 @@ "notifications": { "reminders": "Reminders", "remindersHint": "Send attendees a reminder email before the meeting. Defaults to 24 hours before if none are set.", + "answersInHostEmail": "List intake answers in the host's booking email", + "answersInHostEmailHint": "The new-booking email to each host includes the attendee's answers to the intake questions, so they are at hand before the meeting. Only hosts receive them: the attendee's emails and the calendar event never include them. Off by default, because answers can contain personal details.", "addReminder": "+ Add reminder", "customMessages": "Custom messages", "customMessagesHint": "Add an optional note appended to each email type.", diff --git a/frontend/src/lib/i18n/fr.json b/frontend/src/lib/i18n/fr.json index b9af9802..92335c8f 100644 --- a/frontend/src/lib/i18n/fr.json +++ b/frontend/src/lib/i18n/fr.json @@ -1792,6 +1792,8 @@ "notifications": { "reminders": "Rappels", "remindersHint": "Envoyer aux participants un e-mail de rappel avant la réunion. Par défaut 24 heures avant si aucun n'est défini.", + "answersInHostEmail": "Inclure les réponses au questionnaire dans l'e-mail à l'hôte", + "answersInHostEmailHint": "L'e-mail de nouvelle réservation envoyé à chaque hôte contient les réponses du participant aux questions du formulaire, pour les avoir sous la main avant la réunion. Seuls les hôtes les reçoivent : les e-mails du participant et l'événement du calendrier ne les contiennent jamais. Désactivé par défaut, car les réponses peuvent contenir des données personnelles.", "addReminder": "+ Ajouter un rappel", "customMessages": "Messages personnalisés", "customMessagesHint": "Ajoutez une note facultative à la fin de chaque type d'e-mail.", diff --git a/frontend/src/routes/event-types/[slug]/+page.svelte b/frontend/src/routes/event-types/[slug]/+page.svelte index 84e6f5d4..269db1d9 100644 --- a/frontend/src/routes/event-types/[slug]/+page.svelte +++ b/frontend/src/routes/event-types/[slug]/+page.svelte @@ -296,6 +296,7 @@ { value: 168, label: $t('eventTypeEditor.reminders.option.168h') }, ]); let reminders = $state([]); + let answersInHostEmail = $state(false); let msg_confirmation = $state(''); let msg_cancellation = $state(''); let msg_reschedule = $state(''); @@ -349,6 +350,7 @@ }; priceMajor = ((et.price_cents ?? 0) / 100).toFixed(2); reminders = et.reminders ?? []; + answersInHostEmail = et.answers_in_host_email ?? false; if (et.routing_mode === 'round_robin') { hostScope = 'people'; staffing = 'rotate'; } else if (et.routing_mode === 'collective') { hostScope = 'people'; staffing = 'together'; } else { hostScope = 'me'; } @@ -412,6 +414,7 @@ routing_mode: routingMode, rr_strategy: rrStrategy, reminders, + answers_in_host_email: answersInHostEmail, // Not `|| null`: this form always saves the whole page state, so a blanked // field must send '' to actually clear it. The API treats null as "leave // unchanged" (for partial-PATCH callers), which would silently keep the old @@ -1119,6 +1122,15 @@ + +
+
+ + +
+

{$t('eventTypeEditor.notifications.answersInHostEmailHint')}

+
+

{$t('eventTypeEditor.notifications.customMessages')}

diff --git a/internal/db/migrations/00076_event_type_answers_in_host_email.sql b/internal/db/migrations/00076_event_type_answers_in_host_email.sql new file mode 100644 index 00000000..a5663173 --- /dev/null +++ b/internal/db/migrations/00076_event_type_answers_in_host_email.sql @@ -0,0 +1,15 @@ +-- +goose Up +-- Whether the host's new-booking email lists the attendee's intake answers, so the +-- context they gave (company, topic, phone number...) is where the host looks right +-- before the call instead of only in the admin UI. Requested in discussion #264. +-- +-- Default 0: intake answers are often the sensitive part of a booking (a phone number, +-- free text about a person or a condition), and an email is a copy that leaves Calnode, +-- so it has to be chosen per event type and never inherited by surprise. Only the host's +-- own notification carries them. The attendee's emails and the calendar event do not: +-- the event description is visible to the attendee in their invite on Google, Microsoft +-- and CalDAV alike, which is why that half of #264 was not taken. +ALTER TABLE event_types ADD COLUMN answers_in_host_email INTEGER NOT NULL DEFAULT 0; + +-- +goose Down +ALTER TABLE event_types DROP COLUMN answers_in_host_email; diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index e1f54313..8976f4b0 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -1346,10 +1346,54 @@ func (h *Handler) createHostEvents(ctx context.Context, b *booking.Booking, in b wg.Wait() } +// hostEmailAnswers returns the booking's intake answers for the host's new-booking +// email, or nil when the event type has not opted in (answers_in_host_email, #264). +// Unanswered optional questions are left out. Errors are logged and yield nil: a +// missing answers block must not hold up the confirmation itself. +func (h *Handler) hostEmailAnswers(ctx context.Context, eventTypeID, bookingID string) []mailer.Answer { + var optedIn bool + if err := h.db.QueryRowContext(ctx, + `SELECT answers_in_host_email FROM event_types WHERE id = ?`, eventTypeID).Scan(&optedIn); err != nil { + if !errors.Is(err, sql.ErrNoRows) { + h.logger.Error("host email answers: load opt-in", "error", err, "booking_id", bookingID) + } + return nil + } + if !optedIn { + return nil + } + rows, err := h.db.QueryContext(ctx, ` + SELECT q.label, a.value + FROM booking_answers a + JOIN event_type_questions q ON q.id = a.question_id + WHERE a.booking_id = ? AND a.value != '' + ORDER BY q.position, q.id`, bookingID) + if err != nil { + h.logger.Error("host email answers: query", "error", err, "booking_id", bookingID) + return nil + } + defer rows.Close() + var answers []mailer.Answer + for rows.Next() { + var a mailer.Answer + if err := rows.Scan(&a.Question, &a.Value); err != nil { + h.logger.Error("host email answers: scan", "error", err, "booking_id", bookingID) + return nil + } + answers = append(answers, a) + } + if err := rows.Err(); err != nil { + h.logger.Error("host email answers: rows", "error", err, "booking_id", bookingID) + return nil + } + return answers +} + // notifyHosts emails each host that has host-booking notifications on. Returns the // primary host's notification prefs, for the caller's single attendee-confirmation send, -// and whether any host email failed. -func (h *Handler) notifyHosts(ctx context.Context, b *booking.Booking, bData mailer.BookingData, hosts []assignedHost, livekitHostURL string) (hostPrefs, bool) { +// and whether any host email failed. answers (see hostEmailAnswers) go on each host's +// copy only, never on bData, which the caller goes on to send to the attendee. +func (h *Handler) notifyHosts(ctx context.Context, b *booking.Booking, bData mailer.BookingData, hosts []assignedHost, livekitHostURL string, answers []mailer.Answer) (hostPrefs, bool) { primaryPrefs := allOnPrefs confirmFailed := false for _, host := range hosts { @@ -1359,6 +1403,7 @@ func (h *Handler) notifyHosts(ctx context.Context, b *booking.Booking, bData mai } if prefs.NotifyHostBooking { hd := h.hostBookingData(ctx, bData, host, b.InviteDelivery, b.UpdatedAt) + hd.HostAnswers = answers if livekitHostURL != "" { hd.LocationValue = livekitHostURL // host email gets the controls-enabled link } @@ -1483,7 +1528,8 @@ func (h *Handler) dispatchBookingConfirmation(b *booking.Booking, in bookingConf mailCtx, cancelMail := context.WithTimeout(context.Background(), dispatchMailBudget) defer cancelMail() - primaryPrefs, confirmFailed := h.notifyHosts(mailCtx, b, bData, hosts, livekitHostURL) + answers := h.hostEmailAnswers(mailCtx, b.EventTypeID, b.ID) + primaryPrefs, confirmFailed := h.notifyHosts(mailCtx, b, bData, hosts, livekitHostURL, answers) // Attendee confirmation, once. "With:" names the primary host; gated on the // primary host's notification preference (matches prior behaviour). diff --git a/internal/handler/event_type.go b/internal/handler/event_type.go index 41fe25c3..90dc0b99 100644 --- a/internal/handler/event_type.go +++ b/internal/handler/event_type.go @@ -42,6 +42,10 @@ type eventTypeJSON struct { // instead of omitting them. Off by default: the slots endpoint is public, so this // makes the host's booked hours legible to anyone with the link (#19). ShowTakenSlots bool `json:"show_taken_slots"` + // AnswersInHostEmail lists the attendee's intake answers in the host's new-booking + // email. Off by default: answers are often the sensitive part of a booking, and only + // the host's own email carries them, never the attendee's or the calendar event (#264). + AnswersInHostEmail bool `json:"answers_in_host_email"` // InviteDelivery is who sends the booker's calendar invite: "calendar" (each host's // connected calendar, from the host's own address), "calnode" (Calnode's own .ics, // from the instance sender, so no host address reaches the booker) or "none" (no one: @@ -106,7 +110,7 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { var et eventTypeJSON var desc, locVal, msgConf, msgCancel, msgResched, msgRemind, msgGreeting sql.NullString var subjConf, subjCancel, subjResched, subjRemind sql.NullString - var isActive, isPublic, showTaken int + var isActive, isPublic, showTaken, answersInHostEmail int dests := []any{ &et.ID, &et.Slug, &et.Name, &desc, @@ -119,6 +123,7 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { &msgConf, &msgCancel, &msgResched, &msgRemind, &msgGreeting, &subjConf, &subjCancel, &subjResched, &subjRemind, &et.PriceCents, &et.Currency, &et.InviteDelivery, &et.DisplayOrder, + &answersInHostEmail, } dests = append(dests, trailing...) err := s.Scan(dests...) @@ -137,6 +142,7 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { et.IsActive = isActive != 0 et.IsPublic = isPublic != 0 et.ShowTakenSlots = showTaken != 0 + et.AnswersInHostEmail = answersInHostEmail != 0 if msgConf.Valid { et.MsgConfirmation = &msgConf.String } @@ -177,7 +183,8 @@ const etColumns = `id, slug, name, description, is_active, is_public, show_taken_slots, created_at, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, - price_cents, currency, invite_delivery, display_order` + price_cents, currency, invite_delivery, display_order, + answers_in_host_email` // selectETCols fetches a single event type without the caller-relative columns. const selectETCols = "SELECT " + etColumns + " FROM event_types" @@ -282,6 +289,7 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { MaxActiveBookings *int `json:"max_active_bookings"` AllowPhoneCall *bool `json:"allow_phone_call"` ShowTakenSlots *bool `json:"show_taken_slots"` + AnswersInHostEmail *bool `json:"answers_in_host_email"` InviteDelivery *string `json:"invite_delivery"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { @@ -357,6 +365,9 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { if req.ShowTakenSlots != nil && *req.ShowTakenSlots { showTaken = 1 } + // Off unless asked for, for the same reason: intake answers leave Calnode in an + // email, so that is chosen per event type (#264). + answersInHostEmail := req.AnswersInHostEmail != nil && *req.AnswersInHostEmail inviteDelivery := booking.InviteByCalendar if req.InviteDelivery != nil { mode, ok := normalizeInviteDelivery(*req.InviteDelivery) @@ -386,12 +397,14 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { slot_interval_minutes, location_type, location_value, allow_phone_call, routing_mode, buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, max_active_bookings, show_taken_slots, invite_delivery, - msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, display_order) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, display_order, + answers_in_host_email) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, user.ID, req.Slug, req.Name, req.Description, req.DurationMinutes, slotInterval, locType, req.LocationValue, req.AllowPhoneCall != nil && *req.AllowPhoneCall, routingMode, bufBefore, bufAfter, minNotice, maxFuture, maxActive, showTaken, inviteDelivery, - defaultMsgConfirmation, defaultMsgCancellation, defaultMsgReschedule, defaultMsgReminder, req.DisplayOrder) + defaultMsgConfirmation, defaultMsgCancellation, defaultMsgReschedule, defaultMsgReminder, req.DisplayOrder, + answersInHostEmail) if err != nil { if db.IsUniqueViolation(err) { h.writeError(w, http.StatusConflict, "slug already in use") @@ -520,6 +533,7 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { IsPublic *bool `json:"is_public"` AllowPhoneCall *bool `json:"allow_phone_call"` ShowTakenSlots *bool `json:"show_taken_slots"` + AnswersInHostEmail *bool `json:"answers_in_host_email"` InviteDelivery *string `json:"invite_delivery"` Archived *bool `json:"archived"` MsgConfirmation *string `json:"msg_confirmation"` @@ -678,6 +692,9 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { } set("show_taken_slots", v) } + if req.AnswersInHostEmail != nil { + set("answers_in_host_email", *req.AnswersInHostEmail) + } var newInviteDelivery string if req.InviteDelivery != nil { mode, ok := normalizeInviteDelivery(*req.InviteDelivery) diff --git a/internal/handler/event_type_duplicate.go b/internal/handler/event_type_duplicate.go index a4d7bff9..3728c66b 100644 --- a/internal/handler/event_type_duplicate.go +++ b/internal/handler/event_type_duplicate.go @@ -143,7 +143,7 @@ func (h *Handler) DuplicateEventType(w http.ResponseWriter, r *http.Request) { is_active, is_public, show_taken_slots, archived_at, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, - price_cents, currency, invite_delivery, display_order) + price_cents, currency, invite_delivery, display_order, answers_in_host_email) SELECT ?, user_id, team_id, ?, name, description, duration_minutes, slot_interval_minutes, @@ -154,7 +154,7 @@ func (h *Handler) DuplicateEventType(w http.ResponseWriter, r *http.Request) { 0, is_public, show_taken_slots, NULL, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, - price_cents, currency, invite_delivery, display_order + price_cents, currency, invite_delivery, display_order, answers_in_host_email FROM event_types WHERE id = ?`, newID, newSlug, srcID); err != nil { h.logger.ErrorContext(r.Context(), "duplicate event type: copy row", "error", err) h.writeError(w, http.StatusInternalServerError, "internal error") diff --git a/internal/handler/event_type_duplicate_test.go b/internal/handler/event_type_duplicate_test.go index 581aef3d..a1ab9b19 100644 --- a/internal/handler/event_type_duplicate_test.go +++ b/internal/handler/event_type_duplicate_test.go @@ -31,6 +31,7 @@ type duplicateResponse struct { IsActive bool `json:"is_active"` IsPublic bool `json:"is_public"` ShowTakenSlots bool `json:"show_taken_slots"` + AnswersInHostEmail bool `json:"answers_in_host_email"` Archived bool `json:"archived"` MsgConfirmation *string `json:"msg_confirmation"` SubjConfirmation *string `json:"subj_confirmation"` @@ -61,7 +62,7 @@ func seedRichEventType(t *testing.T, database *sql.DB, ownerID, memberID string) duration_minutes, slot_interval_minutes, location_type, location_value, routing_mode, rr_strategy, buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, max_active_bookings, seat_limit, - is_active, is_public, show_taken_slots, + is_active, is_public, show_taken_slots, answers_in_host_email, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, price_cents, currency) @@ -70,7 +71,7 @@ func seedRichEventType(t *testing.T, database *sql.DB, ownerID, memberID string) 45, 15, 'phone', '+15550100', 'round_robin', 'priority', 10, 20, 240, 45, 3, 4, - 1, 0, 1, + 1, 0, 1, 1, 'See you soon', 'Sorry to miss you', 'New time below', 'Coming up', 'Hi! When suits you?', 'Confirmed: intro', 'Cancelled: intro', 'Moved: intro', 'Reminder: intro', @@ -185,6 +186,9 @@ func TestDuplicateEventType_copiesTheRowAndEveryChildDataset(t *testing.T) { if !got.ShowTakenSlots { t.Error("show_taken_slots: got false; want the source's true") } + if !got.AnswersInHostEmail { + t.Error("answers_in_host_email: got false; want the source's true") + } if got.MsgConfirmation == nil || *got.MsgConfirmation != "See you soon" { t.Errorf("msg_confirmation: got %v", got.MsgConfirmation) } @@ -604,8 +608,9 @@ func TestDuplicateEventType_handlesEveryEventTypeColumn(t *testing.T) { "subj_confirmation": true, "subj_cancellation": true, "subj_reschedule": true, "subj_reminder": true, "price_cents": true, "currency": true, - "invite_delivery": true, - "display_order": true, + "invite_delivery": true, + "display_order": true, + "answers_in_host_email": true, } // Deliberately not inherited, with the reason. notInherited := map[string]string{ diff --git a/internal/handler/host_email_answers_internal_test.go b/internal/handler/host_email_answers_internal_test.go new file mode 100644 index 00000000..add6469c --- /dev/null +++ b/internal/handler/host_email_answers_internal_test.go @@ -0,0 +1,236 @@ +package handler + +import ( + "context" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/calnode/calnode/internal/booking" + "github.com/calnode/calnode/internal/db" + "github.com/calnode/calnode/internal/mailer" +) + +// answersFixture is a workspace with one event type that has two intake questions, and +// a booking that answered one of them (the optional one is left blank). +type answersFixture struct { + h *Handler + cap *captureMailer + apiKey string + etID string + booking *booking.Booking +} + +func newAnswersFixture(t *testing.T, etBody string) answersFixture { + t.Helper() + database, err := db.Open("sqlite://:memory:") + if err != nil { + t.Fatalf("db.Open: %v", err) + } + t.Cleanup(func() { database.Close() }) + if err := db.Migrate(database); err != nil { + t.Fatalf("db.Migrate: %v", err) + } + h := New(database, slog.Default()) + cap := &captureMailer{} + h.SetMailer(cap, "https://calnode.example.com") + + rec := httptest.NewRecorder() + h.Setup(rec, httptest.NewRequest(http.MethodPost, "/v1/setup", + strings.NewReader(`{"name":"Test Host","email":"host@example.com","timezone":"UTC"}`))) + if rec.Code != http.StatusCreated { + t.Fatalf("setup: %d — %s", rec.Code, rec.Body.String()) + } + var setup struct { + APIKey string `json:"api_key"` + UserID string `json:"user_id"` + } + json.Unmarshal(rec.Body.Bytes(), &setup) //nolint:errcheck + + req := httptest.NewRequest(http.MethodPost, "/v1/event-types", strings.NewReader(etBody)) + req.Header.Set("X-API-Key", setup.APIKey) + rec = httptest.NewRecorder() + h.RequireAuth(h.CreateEventType)(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("create event type: %d — %s", rec.Code, rec.Body.String()) + } + var et struct { + ID string `json:"id"` + } + json.Unmarshal(rec.Body.Bytes(), &et) //nolint:errcheck + + for _, q := range []string{ + `('q1', ?, 'Company', 'text', 1, 0)`, + `('q2', ?, 'Anything else?', 'text', 0, 1)`, + } { + if _, err := database.Exec(`INSERT INTO event_type_questions (id, event_type_id, label, type, required, position) VALUES `+q, et.ID); err != nil { + t.Fatalf("seed question: %v", err) + } + } + + b, err := h.bookingSvc.Create(context.Background(), booking.CreateParams{ + EventTypeID: et.ID, + HostIDs: []string{setup.UserID}, + RoutingMode: "fixed", + StartAt: time.Now().Add(48 * time.Hour).UTC(), + EndAt: time.Now().Add(48*time.Hour + 30*time.Minute).UTC(), + Organizer: booking.Attendee{Name: "Ana Attendee", Email: "ana@example.com", IANATimezone: "UTC"}, + Answers: []booking.Answer{ + {QuestionID: "q1", Value: "Acme Sp. z o.o."}, + {QuestionID: "q2", Value: ""}, + }, + }) + if err != nil { + t.Fatalf("bookingSvc.Create: %v", err) + } + return answersFixture{h: h, cap: cap, apiKey: setup.APIKey, etID: et.ID, booking: b} +} + +// dispatch runs the confirmation side effects synchronously, the way CreateBooking +// runs them in a goroutine. +func (f answersFixture) dispatch() { + f.h.dispatchBookingConfirmation(f.booking, bookingConfirmationInput{ + EventTypeName: "Discovery call", + EventTypeSlug: "discovery", + OrganizerName: "Ana Attendee", + OrganizerEmail: "ana@example.com", + OrganizerTimezone: "UTC", + }) +} + +const answersETBody = `{"slug":"discovery","name":"Discovery call","duration_minutes":30,"location_type":"phone_outbound","max_future_days":0%s}` + +func TestHostEmailAnswers_optedIn_hostGetsThemAttendeeDoesNot(t *testing.T) { + f := newAnswersFixture(t, strings.Replace(answersETBody, "%s", `,"answers_in_host_email":true`, 1)) + f.dispatch() + + host := f.cap.find("host@example.com") + if host == nil { + t.Fatalf("no host email; sent to %v", f.cap.recipients()) + } + if !strings.Contains(host.Text, " Company\n Acme Sp. z o.o.\n") { + t.Errorf("host email lacks the answer:\n%s", host.Text) + } + if !strings.Contains(host.HTML, "Acme Sp. z o.o.") { + t.Errorf("host HTML lacks the answer") + } + // The optional question was left blank, so it is not listed. + if strings.Contains(host.Text, "Anything else?") { + t.Errorf("an unanswered question should be left out:\n%s", host.Text) + } + + att := f.cap.find("ana@example.com") + if att == nil { + t.Fatalf("no attendee email; sent to %v", f.cap.recipients()) + } + if strings.Contains(att.Text, "Acme") || strings.Contains(att.HTML, "Acme") { + t.Errorf("the attendee's confirmation must not carry the answers:\n%s", att.Text) + } + for _, a := range att.Attachments { + if strings.Contains(string(a.Content), "Acme") { + t.Errorf("the attendee's .ics must not carry the answers") + } + } +} + +func TestHostEmailAnswers_offByDefault(t *testing.T) { + f := newAnswersFixture(t, strings.Replace(answersETBody, "%s", "", 1)) + f.dispatch() + + host := f.cap.find("host@example.com") + if host == nil { + t.Fatalf("no host email; sent to %v", f.cap.recipients()) + } + if strings.Contains(host.Text, "Acme") || strings.Contains(host.Text, "Answers") { + t.Errorf("without the opt-in the host email must not list answers:\n%s", host.Text) + } +} + +// The flag is readable and writable through the API: off on create unless asked for, +// and a PATCH turns it on and off again. +func TestHostEmailAnswers_flagRoundTripsThroughAPI(t *testing.T) { + f := newAnswersFixture(t, strings.Replace(answersETBody, "%s", "", 1)) + + get := func() bool { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/v1/event-types/discovery", nil) + req.Header.Set("X-API-Key", f.apiKey) + req.SetPathValue("slug", "discovery") + rec := httptest.NewRecorder() + f.h.RequireAuth(f.h.GetEventType)(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("get: %d — %s", rec.Code, rec.Body.String()) + } + var et struct { + AnswersInHostEmail *bool `json:"answers_in_host_email"` + } + json.Unmarshal(rec.Body.Bytes(), &et) //nolint:errcheck + if et.AnswersInHostEmail == nil { + t.Fatalf("answers_in_host_email missing from the event type JSON: %s", rec.Body.String()) + } + return *et.AnswersInHostEmail + } + patch := func(v string) { + t.Helper() + req := httptest.NewRequest(http.MethodPatch, "/v1/event-types/discovery", + strings.NewReader(`{"answers_in_host_email":`+v+`}`)) + req.Header.Set("X-API-Key", f.apiKey) + req.SetPathValue("slug", "discovery") + rec := httptest.NewRecorder() + f.h.RequireAuth(f.h.PatchEventType)(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("patch %s: %d — %s", v, rec.Code, rec.Body.String()) + } + } + + if get() { + t.Fatal("answers_in_host_email should default to false") + } + patch("true") + if !get() { + t.Fatal("PATCH true did not turn it on") + } + patch("false") + if get() { + t.Fatal("PATCH false did not turn it off") + } +} + +// A reassigned booking's new host is notified with the confirmation template, so they +// get the answers too: they are the one about to meet this attendee. +func TestHostEmailAnswers_reassignedHostGetsThem(t *testing.T) { + f := newAnswersFixture(t, strings.Replace(answersETBody, "%s", `,"answers_in_host_email":true`, 1)) + if _, err := f.h.db.Exec(`INSERT INTO users (id, email, name, iana_timezone, is_admin, created_at) + VALUES ('host-2', 'colleague@example.com', 'Colleague', 'UTC', 0, '2026-01-01T00:00:00Z')`); err != nil { + t.Fatalf("seed second host: %v", err) + } + req := httptest.NewRequest(http.MethodPost, "/v1/bookings/"+f.booking.ID+"/reassign", + strings.NewReader(`{"host_id":"host-2"}`)) + req.SetPathValue("id", f.booking.ID) + req.Header.Set("X-API-Key", f.apiKey) + rec := httptest.NewRecorder() + f.h.RequireAuth(f.h.ReassignBooking)(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("reassign: %d — %s", rec.Code, rec.Body.String()) + } + + var msg *mailer.Message + for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(5 * time.Millisecond) { + if msg = f.cap.find("colleague@example.com"); msg != nil { + break + } + } + if msg == nil { + t.Fatalf("new host was not notified; sent to %v", f.cap.recipients()) + } + if !strings.Contains(msg.Text, "Acme Sp. z o.o.") { + t.Errorf("new host's email lacks the answers:\n%s", msg.Text) + } + if att := f.cap.find("ana@example.com"); att != nil && strings.Contains(att.Text, "Acme") { + t.Errorf("the attendee's reassignment email must not carry the answers") + } +} diff --git a/internal/handler/reassign.go b/internal/handler/reassign.go index 484f9893..41893817 100644 --- a/internal/handler/reassign.go +++ b/internal/handler/reassign.go @@ -223,6 +223,9 @@ func (h *Handler) ReassignBooking(w http.ResponseWriter, r *http.Request) { hd := d h.applyHostInvite(ctx, &hd, inviteMode, newHostID) hd.ICSSequence = int(time.Now().Unix()) + // The new host is meeting this attendee for the first time, so they get the + // same answers the original host's confirmation carried. + hd.HostAnswers = h.hostEmailAnswers(ctx, bCopy.EventTypeID, bCopy.ID) if err := mailer.SendConfirmationToHost(ctx, h.mailer, hd); err != nil { h.logger.Error("reassign: email new host", "error", err, "booking_id", bCopy.ID) } diff --git a/internal/mailer/booking.go b/internal/mailer/booking.go index 7791b310..d09232b9 100644 --- a/internal/mailer/booking.go +++ b/internal/mailer/booking.go @@ -6,6 +6,7 @@ import ( "fmt" "net/url" "strconv" + "strings" "text/template" "time" @@ -65,6 +66,11 @@ type BookingData struct { // emails. Set for host notifications — the manage token is the attendee's // self-serve link, not something the host should action from email. HideManageLink bool + // HostAnswers are the attendee's intake answers, listed in the host's new-booking + // email when the event type opts in (event_types.answers_in_host_email). Only the + // host templates read this field, and the handler sets it only on each host's copy + // of the data, so the answers never reach an attendee-facing email or the .ics. + HostAnswers []Answer // Locale drives T/Tf and all date/time formatting below — the attendee's stored // booking_attendees.locale at send time, resolved by the caller. nil (the zero // value) falls back to English via locale(). Host-facing sends (SendConfirmationToHost @@ -75,6 +81,19 @@ type BookingData struct { Locale *i18n.Locale } +// Answer is one intake question with the attendee's answer, as shown to the host. +type Answer struct { + Question string + Value string +} + +// IndentedValue is Value with continuation lines indented to match the first, for +// the plain-text email, where a multi-line free-text answer would otherwise run into +// the next question. +func (a Answer) IndentedValue() string { + return strings.ReplaceAll(a.Value, "\n", "\n ") +} + // locale returns d.Locale, or English if unset. func (d BookingData) locale() *i18n.Locale { if d.Locale != nil { @@ -470,7 +489,11 @@ With: {{.OrganizerName}} <{{.OrganizerEmail}}> Start: {{.StartFmt}} End: {{.EndFmt}}{{if .LocationValue}} Location: {{.LocationValue}}{{end}} - +{{if .HostAnswers}} +Answers: +{{range .HostAnswers}} {{.Question}} + {{.IndentedValue}} +{{end}}{{end}} Booking reference: {{.BookingID}} — Calnode diff --git a/internal/mailer/host_answers_test.go b/internal/mailer/host_answers_test.go new file mode 100644 index 00000000..c00d2e7f --- /dev/null +++ b/internal/mailer/host_answers_test.go @@ -0,0 +1,79 @@ +package mailer + +import ( + "context" + "strings" + "testing" +) + +// The host's new-booking email lists the intake answers when the handler supplies them +// (event_types.answers_in_host_email, #264), in both the text and the HTML part. +func TestSendConfirmationToHost_listsAnswers(t *testing.T) { + d := testBookingData() + d.HostAnswers = []Answer{ + {Question: "Company", Value: "Acme "}, + {Question: "What would you like to cover?", Value: "Pricing\nOnboarding"}, + } + cap := &captureMailer{} + if err := SendConfirmationToHost(context.Background(), cap, d); err != nil { + t.Fatalf("send: %v", err) + } + msgs := cap.all() + if len(msgs) != 1 { + t.Fatalf("got %d messages; want 1", len(msgs)) + } + m := msgs[0] + + for _, want := range []string{ + "Answers:\n", + " Company\n Acme \n", + // A multi-line answer stays indented under its question. + " What would you like to cover?\n Pricing\n Onboarding\n", + } { + if !strings.Contains(m.Text, want) { + t.Errorf("text part lacks %q:\n%s", want, m.Text) + } + } + if !strings.Contains(m.Text, "Onboarding\n\nBooking reference:") { + t.Errorf("answers block should end with one blank line before the reference:\n%s", m.Text) + } + + if !strings.Contains(m.HTML, ">Answers

") || !strings.Contains(m.HTML, "What would you like to cover?") { + t.Errorf("HTML part lacks the answers block:\n%s", m.HTML) + } + // Answers are attendee input: the HTML part must escape them. + if strings.Contains(m.HTML, "Acme ") || !strings.Contains(m.HTML, "Acme <Ltd>") { + t.Errorf("HTML part did not escape the answer:\n%s", m.HTML) + } +} + +// Without answers the host email is unchanged: no empty "Answers" heading. +func TestSendConfirmationToHost_noAnswersNoBlock(t *testing.T) { + cap := &captureMailer{} + if err := SendConfirmationToHost(context.Background(), cap, testBookingData()); err != nil { + t.Fatalf("send: %v", err) + } + m := cap.all()[0] + if strings.Contains(m.Text, "Answers") || strings.Contains(m.HTML, "Answers") { + t.Errorf("an email without answers must not show the block:\n%s", m.Text) + } + if !strings.Contains(m.Text, "Location: https://meet.example.com/abc\n\nBooking reference:") { + t.Errorf("text layout changed for an email without answers:\n%s", m.Text) + } +} + +// HostAnswers is host-only. Even if it were set on the data an attendee email is +// rendered from, no attendee template reads it. +func TestAttendeeEmails_neverRenderHostAnswers(t *testing.T) { + d := testBookingData() + d.HostAnswers = []Answer{{Question: "Phone", Value: "+48600100200"}} + for _, typ := range []string{"confirmation", "cancellation", "reschedule", "reminder"} { + _, text, html, ok := RenderBody(typ, d) + if !ok { + t.Fatalf("RenderBody(%q) not ok", typ) + } + if strings.Contains(text, "+48600100200") || strings.Contains(html, "+48600100200") { + t.Errorf("%s email to the attendee contains a host-only answer", typ) + } + } +} diff --git a/internal/mailer/html.go b/internal/mailer/html.go index 1f5b787c..3b3c4d73 100644 --- a/internal/mailer/html.go +++ b/internal/mailer/html.go @@ -90,6 +90,11 @@ var htmlConfirmHost = content(`{{define "content"}} ` + labelTD + `When` + valueTD + `{{.WhenFmt}} {{if .LocationValue}}` + labelTD + `Location{{.LocationValue}}{{end}} {{template "cardClose" .}} +{{if .HostAnswers}}

Answers

+{{template "cardOpen" .}} +{{range .HostAnswers}}{{.Question}} +{{.Value}} +{{end}}{{template "cardClose" .}}{{end}} {{template "ref" .}} {{end}}`) From afbd40f7b753eef7cb0783b363a6af8967e55b70 Mon Sep 17 00:00:00 2001 From: Dominik Myszkowski Date: Tue, 1 Dec 2026 09:57:41 +0100 Subject: [PATCH 2/2] fix(email): show checkbox answers as Yes/No in the host email The admin booking view reads checkbox answers through checkboxTicked, because older rows hold whatever the surface sent ("Yes", "1", "on"). The host email printed the raw token; it now reads them the same way. --- internal/handler/booking_handler.go | 15 +++++++++++-- .../host_email_answers_internal_test.go | 22 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index 8976f4b0..4b79c0a4 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -1363,7 +1363,7 @@ func (h *Handler) hostEmailAnswers(ctx context.Context, eventTypeID, bookingID s return nil } rows, err := h.db.QueryContext(ctx, ` - SELECT q.label, a.value + SELECT q.label, q.type, a.value FROM booking_answers a JOIN event_type_questions q ON q.id = a.question_id WHERE a.booking_id = ? AND a.value != '' @@ -1376,10 +1376,21 @@ func (h *Handler) hostEmailAnswers(ctx context.Context, eventTypeID, bookingID s var answers []mailer.Answer for rows.Next() { var a mailer.Answer - if err := rows.Scan(&a.Question, &a.Value); err != nil { + var typ string + if err := rows.Scan(&a.Question, &typ, &a.Value); err != nil { h.logger.Error("host email answers: scan", "error", err, "booking_id", bookingID) return nil } + // A checkbox reads as Yes/No, as in the admin booking view: older rows hold + // whatever the surface sent ("Yes", "1", "on"), and a consent box must never read + // as the opposite of what the guest ticked. + if typ == "checkbox" { + if checkboxTicked(a.Value) { + a.Value = "Yes" + } else { + a.Value = "No" + } + } answers = append(answers, a) } if err := rows.Err(); err != nil { diff --git a/internal/handler/host_email_answers_internal_test.go b/internal/handler/host_email_answers_internal_test.go index add6469c..3d870a37 100644 --- a/internal/handler/host_email_answers_internal_test.go +++ b/internal/handler/host_email_answers_internal_test.go @@ -234,3 +234,25 @@ func TestHostEmailAnswers_reassignedHostGetsThem(t *testing.T) { t.Errorf("the attendee's reassignment email must not carry the answers") } } + +// A checkbox answer reaches the host as Yes/No whatever token the row holds: rows from +// before answers were canonicalised can carry "Yes", "1", "on" or "checked". +func TestHostEmailAnswers_checkboxReadsAsYesNo(t *testing.T) { + f := newAnswersFixture(t, strings.Replace(answersETBody, "%s", `,"answers_in_host_email":true`, 1)) + db := f.h.db + if _, err := db.Exec(`INSERT INTO event_type_questions (id, event_type_id, label, type, required, position) + VALUES ('q3', ?, 'Consent', 'checkbox', 0, 2), ('q4', ?, 'Newsletter', 'checkbox', 0, 3)`, f.etID, f.etID); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO booking_answers (id, booking_id, question_id, value) + VALUES ('a3', ?, 'q3', 'on'), ('a4', ?, 'q4', 'no')`, f.booking.ID, f.booking.ID); err != nil { + t.Fatal(err) + } + got := map[string]string{} + for _, a := range f.h.hostEmailAnswers(context.Background(), f.etID, f.booking.ID) { + got[a.Question] = a.Value + } + if got["Consent"] != "Yes" || got["Newsletter"] != "No" || got["Company"] != "Acme Sp. z o.o." { + t.Errorf("answers = %v; want Consent Yes, Newsletter No, Company unchanged", got) + } +}