diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c565073..1f43424e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,13 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad deliveries. Migration `00075` normalises `bookings.updated_at` to whole-second RFC 3339 and hands it to triggers, so every change to a booking (payment transitions, meeting links, RSVPs included) now moves it. +- **Redirect after booking.** An event type can send the booker to a page of your own once + a booking is confirmed (Event type → General, `redirect_url`), typically a thank-you page + where site analytics count the conversion, optionally with `?booking_id=` appended. The + booking page shows a "Continue" button and moves on after a moment, also after paying + through Stripe. The embedded widget never leaves the host site: it offers "Continue" in a + new tab instead. Only absolute `https://` URLs without credentials are accepted, checked + when saved, when served and again in the browser. Migration `00077` adds the columns. - **Delete a booking for an erasure request.** Owners and admins can now permanently remove a booking from the Bookings list (trash icon, confirmation dialog; `DELETE /v1/bookings/{id}`). It removes the booking with its attendees, answers, manage links and host assignments, plus the diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2096c80d..40b34d39 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -439,6 +439,8 @@ The `phone_outbound` location type ("we'll call you") is the outbound counterpar A confirmed booking is a **final state** on all three booking surfaces (#268). A page that kept its calendar live and re-enabled its submit button after confirming invited a second booking under a different email, which `max_active_bookings` cannot catch. On `book.html`, `finalize()` (on success, and on the return from Stripe Checkout) disables the calendar, month navigation, timezone and submit, resets the form, and every handler checks the `finalized` flag rather than relying on the markup alone; a `submitting` flag also drops a second submit while the first request is in flight. "Book another time" is a fresh load of the page without the Stripe return parameters, so no picked day, slot or host state survives. The embed widget renders its calendar disabled while `state.view === 'confirm'` and refuses a second submit; its "Book another time" resets the widget's own state and reloads the month, never navigating the host page. On `manage.html` the success views (rescheduled, cancelled) are final: `showView` no longer leaves them and neither action can be sent again, because the page's times describe the booking as it was; a reload shows it as it now is. `TestBookPage_confirmationIsFinal` runs book.html's real page script under node against a small fake DOM (`testdata/book_final_state.js`) to check that a second submit sends nothing; the widget and manage page are pinned at source level. +An event type can set a **post-booking redirect** (`redirect_url`, `redirect_with_booking_id`, migration 00077, #268), typically the operator's own thank-you page, where site analytics count the conversion. Although admin-configured, it is an open-redirect surface, so it is checked three times: `validRedirectURL` when the event type is saved (absolute https, a host, no credentials: `https://trusted.example@evil.example/` reads as one site and goes to another; no whitespace or control characters; at most 2000 characters), `servedRedirectURL` when a page or the widget is given it (a stored value that no longer passes is served as no redirect and logged), and `redirectTarget` in the browser right before use (`booking-logic.js`, mirrored in `embed.js`). `redirect_with_booking_id` appends `?booking_id=`; it is off by default because the booking id is a lookup key (`GET /v1/bookings/{id}` is public). On `book.html`, `finalize()` shows a "Continue" button and navigates after a short delay (`REDIRECT_DELAY_MS`), which leaves time for the dataLayer/GA4 conversion pushed right after it; this covers the return from Stripe Checkout too, whose success URL carries `booking_id` for that purpose. The **embed widget never navigates the host page**: its confirmation offers "Continue", which opens the redirect in a new tab (`noopener`). The manage page does not redirect: a reschedule or a cancellation is not a conversion. + `internal/booking/service.go` (transactions) + `internal/handler/booking_handler.go` (HTTP + async side effects). diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index adc78ab0..0dad2655 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -42,6 +42,12 @@ export type EventType = { /** 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; + /** Where the booking page sends the booker after a confirmed booking (absolute https, + * no credentials). Absent/null = no redirect. The embed widget only offers it as a + * "Continue" button that opens a new tab. */ + redirect_url?: string | null; + /** Append ?booking_id= to redirect_url. */ + redirect_with_booking_id: 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 aac1a055..dd56c27b 100644 --- a/frontend/src/lib/i18n/en.json +++ b/frontend/src/lib/i18n/en.json @@ -1646,6 +1646,9 @@ "showTaken": "Show booked times as unavailable", "showTakenHint": "Booked times appear struck through on the booking page instead of being hidden, so visitors can see the calendar filling up. Only times inside your working hours are shown, never the rest of your day.", "showTakenWarning": "Anyone with the booking link can see which hours are taken.", + "redirectUrl": "Redirect after booking (optional)", + "redirectUrlHint": "After a confirmed booking, the booking page sends the booker here, for example your own thank-you page. Must start with https://. The embedded widget never leaves your site: it shows a Continue button that opens this page in a new tab.", + "redirectWithBookingId": "Add the booking ID to the address (?booking_id=…)", "showNextAvailable": "Show the next available time", "showNextAvailableHint": "Adds a button above the time list, such as \"Next available: Wed, Nov 18, 10:00 AM\", that opens that day. It uses the same times a visitor can already see.", "allowPhoneCall": "Let invitees choose a phone call by entering their number" diff --git a/frontend/src/lib/i18n/fr.json b/frontend/src/lib/i18n/fr.json index 2409babd..e569dd64 100644 --- a/frontend/src/lib/i18n/fr.json +++ b/frontend/src/lib/i18n/fr.json @@ -1646,6 +1646,9 @@ "showTaken": "Afficher les horaires réservés comme indisponibles", "showTakenHint": "Les horaires réservés apparaissent barrés sur la page de réservation au lieu d'être masqués, afin que les visiteurs voient le calendrier se remplir. Seuls les horaires dans vos heures de travail sont affichés, jamais le reste de votre journée.", "showTakenWarning": "Quiconque dispose du lien de réservation peut voir quels horaires sont pris.", + "redirectUrl": "Redirection après la réservation (facultatif)", + "redirectUrlHint": "Après une réservation confirmée, la page de réservation y envoie la personne, par exemple vers votre page de remerciement. Doit commencer par https://. Le widget intégré ne quitte jamais votre site : il affiche un bouton Continuer qui ouvre cette page dans un nouvel onglet.", + "redirectWithBookingId": "Ajouter l'identifiant de réservation à l'adresse (?booking_id=…)", "showNextAvailable": "Afficher le prochain horaire disponible", "showNextAvailableHint": "Ajoute au-dessus de la liste des horaires un bouton, par exemple « Prochain créneau disponible : mer. 18 nov., 10:00 », qui ouvre ce jour. Il utilise les mêmes horaires que ceux déjà visibles par un visiteur.", "allowPhoneCall": "Permettre aux invités de choisir un appel téléphonique en saisissant leur numéro" diff --git a/frontend/src/routes/event-types/[slug]/+page.svelte b/frontend/src/routes/event-types/[slug]/+page.svelte index 890c41e8..eae474dc 100644 --- a/frontend/src/routes/event-types/[slug]/+page.svelte +++ b/frontend/src/routes/event-types/[slug]/+page.svelte @@ -88,6 +88,7 @@ display_order: 0, name: '', slug: '', description: '', duration_minutes: 30, slot_interval_minutes: 30, is_active: true, is_public: true, show_taken_slots: false, show_next_available: false, + redirect_url: '', redirect_with_booking_id: false, invite_delivery: 'calendar' as EventType['invite_delivery'], location_type: 'link', location_value: '', buffer_before_minutes: 0, buffer_after_minutes: 0, @@ -337,6 +338,8 @@ is_active: et.is_active, is_public: et.is_public, show_taken_slots: et.show_taken_slots ?? false, + redirect_url: et.redirect_url ?? '', + redirect_with_booking_id: et.redirect_with_booking_id ?? false, show_next_available: et.show_next_available ?? false, invite_delivery: et.invite_delivery ?? 'calendar', location_type: et.location_type, @@ -400,6 +403,9 @@ is_active: form.is_active, is_public: form.is_public, show_taken_slots: form.show_taken_slots, + // '' clears it server-side (null would mean "leave unchanged"). + redirect_url: form.redirect_url.trim(), + redirect_with_booking_id: form.redirect_with_booking_id, show_next_available: form.show_next_available, invite_delivery: form.invite_delivery, allow_phone_call: allowPhoneCall, @@ -718,6 +724,16 @@

{$t('eventTypeEditor.general.showNextAvailableHint')}

+
+ + +

{$t('eventTypeEditor.general.redirectUrlHint')}

+
+ + +
+
+ {#if isOnlineMeeting(form.location_type)} {/if} diff --git a/internal/db/migrations/00077_event_type_redirect_url.sql b/internal/db/migrations/00077_event_type_redirect_url.sql new file mode 100644 index 00000000..0c77f47a --- /dev/null +++ b/internal/db/migrations/00077_event_type_redirect_url.sql @@ -0,0 +1,19 @@ +-- +goose Up +-- Where the booker goes after a confirmed booking: typically the operator's own thank-you +-- page, which is also where site analytics usually count the conversion. Requested in +-- discussion #268. +-- +-- redirect_url is NULL when unset, and the booking page then shows its own final +-- confirmation. It is admin-configured, but it is still an open-redirect surface, so it +-- is validated when saved and again before the page navigates: an absolute https URL +-- with a host and no credentials, nothing else. +-- +-- redirect_with_booking_id appends ?booking_id= so the thank-you page can tie the +-- conversion to the booking. Off by default: the booking id is a lookup key +-- (GET /v1/bookings/{id} is public), so handing it to another site is the operator's call. +ALTER TABLE event_types ADD COLUMN redirect_url TEXT; +ALTER TABLE event_types ADD COLUMN redirect_with_booking_id INTEGER NOT NULL DEFAULT 0; + +-- +goose Down +ALTER TABLE event_types DROP COLUMN redirect_with_booking_id; +ALTER TABLE event_types DROP COLUMN redirect_url; diff --git a/internal/handler/assets/booking-logic.js b/internal/handler/assets/booking-logic.js index f191ae91..52ca39c9 100644 --- a/internal/handler/assets/booking-logic.js +++ b/internal/handler/assets/booking-logic.js @@ -164,7 +164,23 @@ // consolidated onto it. If these are ever unified, the shared version must take the // locale's list_separator/list_conjunction, not hardcode punctuation. + // redirectTarget is where to send the booker after a confirmed booking, or '' (#268): + // the event type's redirect_url, checked once more right before navigating even though + // the server already validated it on save and on serve, then ?booking_id= appended when + // the event type asks for it. Absolute https with a host and no credentials, exactly as + // the server's validRedirectURL; anything else yields '' and the page simply stays on + // its own confirmation. MIRRORED in embed.js (which does not load this module). + function redirectTarget(raw, bookingId, withId) { + if (typeof raw !== 'string' || raw === '' || /[\u0000-\u0020\u007f]/.test(raw)) return ''; + var u; + try { u = new URL(raw); } catch (e) { return ''; } + if (u.protocol !== 'https:' || !u.hostname || u.username || u.password) return ''; + if (withId && bookingId) u.searchParams.set('booking_id', String(bookingId)); + return u.href; + } + return { + redirectTarget: redirectTarget, dateKeyFromISO: dateKeyFromISO, ymd: ymd, groupSlotsByDay: groupSlotsByDay, diff --git a/internal/handler/assets/booking-logic.test.js b/internal/handler/assets/booking-logic.test.js index f333c121..dc185137 100644 --- a/internal/handler/assets/booking-logic.test.js +++ b/internal/handler/assets/booking-logic.test.js @@ -107,6 +107,18 @@ test('fmt leaves a string with no verbs untouched', () => { assert.equal(B.fmt('Inga lediga tider.'), 'Inga lediga tider.'); }); +test('redirectTarget: https only, no credentials, optional booking_id', () => { + assert.equal(B.redirectTarget('https://example.com/thanks', 'b1', false), 'https://example.com/thanks'); + assert.equal(B.redirectTarget('https://example.com/thanks?src=cal', 'b 1', true), + 'https://example.com/thanks?src=cal&booking_id=b+1'); + assert.equal(B.redirectTarget('https://example.com/thanks', '', true), 'https://example.com/thanks'); + for (const bad of ['', 'http://example.com/', 'javascript:alert(1)', '//example.com/x', '/thanks', + 'https://user:pw@example.com/', 'https://trusted.example@evil.example/', 'https://exa mple.com/', + 'https://example.com/\nx', 'data:text/html,hi', null, undefined]) { + assert.equal(B.redirectTarget(bad, 'b1', true), '', String(bad)); + } +}); + test('earliestFreeSlot picks the soonest slot and the day it falls on in the selected tz', () => { const slots = [ { start: '2026-06-16T09:00:00Z' }, diff --git a/internal/handler/book.go b/internal/handler/book.go index 4f429a7c..3ab73a4e 100644 --- a/internal/handler/book.go +++ b/internal/handler/book.go @@ -45,6 +45,11 @@ type bookQuestion struct { type bookPageData struct { PhoneChoice bool + // RedirectURL is where the page sends the booker once a booking is confirmed, or "" + // (#268). Re-validated here, not trusted from the row, and again in the browser. + // RedirectWithBookingID appends ?booking_id=. + RedirectURL string + RedirectWithBookingID bool // PhoneRequired is the "we'll call you" location: the same phone field, but required, // because the attendee's number is the only way the host can reach them. PhoneRequired bool @@ -354,16 +359,20 @@ func (h *Handler) PublicEventType(w http.ResponseWriter, r *http.Request) { msgGreeting sql.NullString allowPhoneCall, showNext bool accentColor string + redirectRaw string + redirectWithID bool ) err := h.db.QueryRowContext(r.Context(), ` SELECT et.id, et.name, COALESCE(et.description, ''), et.duration_minutes, et.location_type, COALESCE(et.location_value, ''), et.max_future_days, et.min_notice_minutes, et.routing_mode, u.name, COALESCE(u.avatar_url, ''), - et.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent, et.show_next_available + et.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent, et.show_next_available, + COALESCE(et.redirect_url, ''), et.redirect_with_booking_id FROM event_types et JOIN users u ON u.id = et.user_id WHERE et.slug = ? AND et.is_active = 1 AND et.is_public = 1`, - slug).Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor, &showNext) + slug).Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor, &showNext, + &redirectRaw, &redirectWithID) if errors.Is(err, sql.ErrNoRows) { h.writeError(w, http.StatusNotFound, "event type not found") return @@ -374,6 +383,7 @@ func (h *Handler) PublicEventType(w http.ResponseWriter, r *http.Request) { return } accentColor = accentOrDefault(accentColor) + redirectURL := h.servedRedirectURL(r, slug, redirectRaw) hosts := h.displayHosts(r.Context(), etID, routingMode) if len(hosts) == 0 { @@ -444,12 +454,16 @@ func (h *Handler) PublicEventType(w http.ResponseWriter, r *http.Request) { "assistant_greeting": assistantGreeting(msgGreeting, loc), "price_cents": priceCents, "currency": currency, - "hosts": outHosts, - "business_name": brand.BusinessName, - "logo_url": abs(brand.LogoURL), - "banner_url": abs(brand.BannerURL), - "locale": loc.Code, - "i18n": json.RawMessage(i18nJSON), + // Post-booking redirect (#268). The widget never navigates the host page with it: + // it offers a "Continue" that opens it in a new tab. + "redirect_url": redirectURL, + "redirect_with_booking_id": redirectWithID && redirectURL != "", + "hosts": outHosts, + "business_name": brand.BusinessName, + "logo_url": abs(brand.LogoURL), + "banner_url": abs(brand.BannerURL), + "locale": loc.Code, + "i18n": json.RawMessage(i18nJSON), }) } @@ -474,17 +488,21 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { msgGreeting sql.NullString allowPhoneCall bool accentColor string + redirectRaw string + redirectWithID bool showNext bool ) err := h.db.QueryRowContext(r.Context(), ` SELECT et.id, et.name, COALESCE(et.description, ''), et.duration_minutes, et.location_type, COALESCE(et.location_value, ''), et.max_future_days, et.min_notice_minutes, et.routing_mode, u.name, COALESCE(u.avatar_url, ''), - et.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent, et.show_next_available + et.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent, et.show_next_available, + COALESCE(et.redirect_url, ''), et.redirect_with_booking_id FROM event_types et JOIN users u ON u.id = et.user_id WHERE et.slug = ? AND et.is_active = 1 AND et.is_public = 1`, - slug).Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor, &showNext) + slug).Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor, &showNext, + &redirectRaw, &redirectWithID) if errors.Is(err, sql.ErrNoRows) { http.Error(w, "Page not found", http.StatusNotFound) @@ -546,38 +564,41 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { loc := h.resolveLocaleWithFallback(r, brand.FallbackLocale) i18nJSON, _ := loc.JSON() + redirectURL := h.servedRedirectURL(r, slug, redirectRaw) data := bookPageData{ - PhoneChoice: allowPhoneCall && onlineMeetingLocation(locType), - PhoneRequired: locType == phoneOutboundLocation, - AccentColor: accentColor, - AccentForeground: accentForeground(accentColor), - Slug: slug, - Name: name, - Description: renderMarkdown(description), - DurationLabel: durationLabel(durMins, loc), - HostName: hosts[0].Name, - HostInitial: hosts[0].Initial, - AvatarURL: hosts[0].AvatarURL, - Hosts: capHostFaces(hosts, maxHostFaces), - HostsMore: hostsOverflow(hosts, maxHostFaces), - HostsLabel: hostsLabel(hosts, loc), - SoleHostName: soleHostName(hosts), - MinNoticeLabel: noticeLabel(minNotice, loc), - LocationLabel: locationLabel(locType, locValue, loc), - PriceLabel: formatPrice(priceCents, currency), - Locale: loc.Code, - T: loc.T, - I18NJSON: template.JS(i18nJSON), // #nosec G203 -- json.Marshal output, which escapes <,>,& by default; safe for embedding in a