diff --git a/CHANGELOG.md b/CHANGELOG.md index 735264c2..b5daa9b2 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 1941b859..3c9043fc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -781,6 +781,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 6b430ec8..adc78ab0 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; /** Show the next free time above the booking page's time list, as a button that * opens that day. Off by default. */ show_next_available: boolean; diff --git a/frontend/src/lib/i18n/en.json b/frontend/src/lib/i18n/en.json index fef11731..aac1a055 100644 --- a/frontend/src/lib/i18n/en.json +++ b/frontend/src/lib/i18n/en.json @@ -1794,6 +1794,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 c0571645..2409babd 100644 --- a/frontend/src/lib/i18n/fr.json +++ b/frontend/src/lib/i18n/fr.json @@ -1794,6 +1794,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 54615ec7..890c41e8 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(''); @@ -350,6 +351,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'; } @@ -414,6 +416,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 @@ -1129,6 +1132,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..4b79c0a4 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -1346,10 +1346,65 @@ 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, 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 != '' + 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 + 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 { + 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 +1414,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 +1539,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 57bb725a..ae7cb205 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"` // ShowNextAvailable shows the next free time above the booking page's time list, as a // button that opens that day. Off by default (#254). ShowNextAvailable bool `json:"show_next_available"` @@ -109,7 +113,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, showNext int + var isActive, isPublic, showTaken, showNext, answersInHostEmail int dests := []any{ &et.ID, &et.Slug, &et.Name, &desc, @@ -122,6 +126,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...) @@ -140,6 +145,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 et.ShowNextAvailable = showNext != 0 if msgConf.Valid { et.MsgConfirmation = &msgConf.String @@ -181,7 +187,8 @@ const etColumns = `id, slug, name, description, is_active, is_public, show_taken_slots, show_next_available, 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" @@ -286,6 +293,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"` ShowNextAvailable *bool `json:"show_next_available"` InviteDelivery *string `json:"invite_delivery"` } @@ -362,6 +370,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 showNext := 0 if req.ShowNextAvailable != nil && *req.ShowNextAvailable { showNext = 1 @@ -395,12 +406,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, show_next_available, 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, showNext, 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") @@ -529,6 +542,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"` ShowNextAvailable *bool `json:"show_next_available"` InviteDelivery *string `json:"invite_delivery"` Archived *bool `json:"archived"` @@ -688,6 +702,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) + } if req.ShowNextAvailable != nil { v := 0 if *req.ShowNextAvailable { diff --git a/internal/handler/event_type_duplicate.go b/internal/handler/event_type_duplicate.go index 42ddf567..8b0746e0 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, show_next_available, 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, show_next_available, 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 4c94ba25..3b42ed86 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"` ShowNextAvailable bool `json:"show_next_available"` Archived bool `json:"archived"` MsgConfirmation *string `json:"msg_confirmation"` @@ -62,7 +63,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, show_next_available, + is_active, is_public, show_taken_slots, show_next_available, 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) @@ -71,7 +72,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, + 1, 0, 1, 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', @@ -186,6 +187,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.ShowNextAvailable { t.Error("show_next_available: got false; want the source's true") } @@ -608,8 +612,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..3d870a37 --- /dev/null +++ b/internal/handler/host_email_answers_internal_test.go @@ -0,0 +1,258 @@ +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") + } +} + +// 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) + } +} 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}}`)