diff --git a/CHANGELOG.md b/CHANGELOG.md index 735264c2..f13831e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,13 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad ### Added +- **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 @@ -68,6 +75,14 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad the attribute to its primary subtag before sending it, so `lang="fr-CA"` loaded France French. The attribute is now sent whole and the server falls back to the primary language when there is no exact match, so `lang="de-DE"` still selects German. +- **A confirmed booking is final on the booking page, the embed widget and the manage + page.** After confirming, the booking page left its calendar clickable and re-enabled the + submit button, which invited a second booking under a different email (the per-invitee cap + cannot catch that). Now the calendar, month navigation, timezone and form stop responding, + a second submit sends nothing (including a double click while the first is in flight), and + a "Book another time" link starts over from a fresh page. The widget does the same without + ever navigating the host page, and the manage page's rescheduled and cancelled screens no + longer lead back to actions on a booking that has changed. ## [0.14.0] - 2026-11-08 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 1941b859..dc13e600 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -437,6 +437,10 @@ Google Meet and Teams event types can opt into `allow_phone_call`. Their booking The `phone_outbound` location type ("we'll call you") is the outbound counterpart: the host calls the attendee. The event type carries no number (`validateLocation` requires none); the booking page and widget show a required `phone` field instead, and `CreateBooking` refuses a missing or invalid number with HTTP 400 rather than falling back to another meeting type. A valid number is stored exactly like the `allow_phone_call` path (`bookings.location_type = "phone"`, `location_value = "tel:"`), so calendar events, emails, webhooks and the manage page treat it as an ordinary telephone appointment. The manage page needs no field of its own: a reschedule keeps the booking's stored number. The shared booking core (`createBookingForSlug`) refuses these event types, because the assistant and MCP cannot collect the number, and the booking page and widget hide the assistant for them. +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 6b430ec8..8d88a140 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -39,6 +39,12 @@ 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; + /** 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 fef11731..05747a72 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 c0571645..400e67f2 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 54615ec7..c2c97d0b 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, @@ -336,6 +337,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, @@ -398,6 +401,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, @@ -715,6 +721,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 `).FindAllStringSubmatch(buf.String(), -1) { + if strings.Contains(m[1], "const SLUG") { + return m[1] + } + } + t.Fatal("book.html has no page script defining SLUG") + return "" +} + +// TestBookPage_confirmationIsFinal runs book.html's real page script under node against a +// small fake DOM (testdata/book_final_state.js) and checks the harm #268 is about: once a +// booking is confirmed, a second submit sends nothing and the calendar no longer leads +// back into the form. Both entry points to the confirmation are covered: a booking made +// through the form, and the return from Stripe Checkout. Skips without node, like the +// CLDR cross-check. +func TestBookPage_confirmationIsFinal(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not available; skipping the book.html behaviour test") + } + dir := t.TempDir() + logic := filepath.Join(dir, "booking-logic.js") + if err := os.WriteFile(logic, []byte(bookingLogicJS), 0o600); err != nil { + t.Fatal(err) + } + harness, err := filepath.Abs(filepath.Join("testdata", "book_final_state.js")) + if err != nil { + t.Fatal(err) + } + const thanks = "https://thanks.example/done?src=cal" + for _, tc := range []struct { + scenario string + redirect string + withID bool + }{ + {"submit", "", false}, + {"paid", "", false}, + {"redirect", thanks, true}, + {"redirect-paid", thanks, true}, + {"redirect-refused", "http://thanks.example/done", true}, + {"redirect-assistant", thanks, true}, + } { + t.Run(tc.scenario, func(t *testing.T) { + page := filepath.Join(t.TempDir(), "page.js") + if err := os.WriteFile(page, []byte(bookPageScript(t, tc.redirect, tc.withID)), 0o600); err != nil { + t.Fatal(err) + } + out, err := exec.Command(node, harness, page, logic, tc.scenario).CombinedOutput() // #nosec G204 -- fixed test inputs + if err != nil { + t.Fatalf("%s\n%v", out, err) + } + // node exits 0 when its event loop drains with a promise still pending, so a + // hung step would otherwise pass silently. The harness prints ok only at the end. + if strings.TrimSpace(string(out)) != "ok" { + t.Fatalf("harness did not finish (want \"ok\"):\n%s", out) + } + }) + } +} + +// TestManagePage_successIsFinal pins manage.html's half: after a reschedule or a cancel +// succeeds, the page cannot navigate away from the success view or send either action +// again, since the times it holds describe the booking as it was (#268). +func TestManagePage_successIsFinal(t *testing.T) { + var buf bytes.Buffer + if err := manageTmpl.Execute(&buf, managePageData{T: i18n.Default().T}); err != nil { + t.Fatalf("render manage.html: %v", err) + } + src := buf.String() + for _, want := range []string{ + "function showView(id) {\n if (finalized) return;", + "if (finalized || !pickedSlot) return;", // confirm reschedule + "finalize('success-reschedule-view');", // reschedule success + "finalize('success-cancel-view');", // cancel success + "$('confirm-cancel-btn').addEventListener('click', async () => {\n if (finalized) return;", + } { + if !strings.Contains(src, want) { + t.Errorf("manage.html no longer contains %q - the success view may not be final any more", want) + } + } +} + +// TestEmbedJS_confirmationIsFinal pins the widget's half. It builds its own calendar and +// form, so book.html's guards don't cover it: once confirmed, the calendar renders +// disabled, a second submit is refused, and "Book another time" resets the widget in +// place rather than navigating the host page. +func TestEmbedJS_confirmationIsFinal(t *testing.T) { + h := &Handler{} + rec := httptest.NewRecorder() + h.EmbedJS(rec, httptest.NewRequest(http.MethodGet, "/embed.js", nil)) + body := rec.Body.String() + for _, want := range []string{ + "var isFinal = st.view === 'confirm';", + "if (!has || isFinal) btn.disabled = true;", + "next.disabled = isFinal;", + "if (cta.disabled || self.state.view === 'confirm') return;", + "t(this.i18n, 'book_another_time')", + "bookAnother() {", + } { + if !strings.Contains(body, want) { + t.Errorf("embed.js no longer contains %q - the confirmation may not be final in the widget", want) + } + } + // "Book another time" must not navigate: the widget lives on someone else's page. + start := strings.Index(body, "bookAnother() {") + if end := strings.Index(body[start:], "\n }"); start < 0 || end < 0 || + strings.Contains(body[start:start+end], "location") { + t.Error("bookAnother must reset the widget's own state, never navigate the host page") + } +} diff --git a/internal/handler/embed.js b/internal/handler/embed.js index 3a2e95b1..864f9caf 100644 --- a/internal/handler/embed.js +++ b/internal/handler/embed.js @@ -51,6 +51,17 @@ // t: pure lookup, not a method — mirrors internal/i18n.Locale.T (falls back to the // key itself if the string table hasn't loaded yet or the key is missing). function t(i18n, key) { return (i18n && i18n[key]) || key; } + // redirectTarget: the post-booking redirect, re-checked before use, or '' (#268). + // Mirrors BookingLogic.redirectTarget in internal/handler/assets/booking-logic.js; this + // widget does NOT load that module, so the two must be kept in step. + 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; + } // fmt: argument substitution for the translated strings that carry one — %s in order, // plus the indexed %[n]s a translation may use to reorder. Mirrors BookingLogic.fmt in // internal/handler/assets/booking-logic.js; this widget does NOT load that module (see @@ -508,7 +519,17 @@ this.asstMessages.push({ role: 'assistant', content: botEl.textContent }); if (booking) botEl.className = 'asst-msg ok'; } - if (booking) this.dispatchEvent(new CustomEvent('calnode:booked', { bubbles: true, composed: true, detail: booking })); + if (booking) { + // A chat booking ends the widget the same way as the form: the final state, with + // "Continue" when a redirect is configured (#268). + if (booking.id && this.state.view !== 'confirm') { + this.state.slot = { start: booking.start_at }; + this.state.bookingId = booking.id; + this.state.view = 'confirm'; + this.render(); + } + this.dispatchEvent(new CustomEvent('calnode:booked', { bubbles: true, composed: true, detail: booking })); + } } catch (e) { if (typing.parentNode) typing.remove(); this.asstAdd(t(this.i18n, 'assistant_error'), 'note'); @@ -534,6 +555,9 @@ calPane() { var self = this, st = this.state, first = st.month; + // A confirmed booking is final (#268): the calendar renders but no longer responds, + // so a second booking cannot start from it. "Book another time" is the way back. + var isFinal = st.view === 'confirm'; var grid = el('div', { class: 'cal-grid' }); this.dow.forEach(function (d) { grid.appendChild(el('div', { class: 'ch', text: d })); }); for (var i = 0; i < mondayIndex(first); i++) grid.appendChild(el('div', { class: 'cd', text: '' })); @@ -543,14 +567,15 @@ var has = !!st.slotsByDay[key] && key >= todayKey; var cls = 'cd' + (has ? ' available' : '') + (st.day === key ? ' sel' : '') + (key === todayKey ? ' today' : ''); var btn = el('button', { class: cls, text: String(d) }); - if (!has) btn.disabled = true; + if (!has || isFinal) btn.disabled = true; else btn.addEventListener('click', (function (k) { return function () { self.state.day = k; self.state.view = 'pick'; self.render(); }; })(key)); grid.appendChild(btn); } var prev = el('button', { 'aria-label': t(this.i18n, 'prev_month_aria'), html: SVG_PREV }); - prev.disabled = !(startOfMonth(first) > startOfMonth(new Date())); + prev.disabled = isFinal || !(startOfMonth(first) > startOfMonth(new Date())); prev.addEventListener('click', function () { self.nav(-1); }); var next = el('button', { 'aria-label': t(this.i18n, 'next_month_aria'), html: SVG_NEXT }); + next.disabled = isFinal; next.addEventListener('click', function () { self.nav(1); }); var nav = el('div', { class: 'cal-nav' }, [ el('span', { class: 'month-label', text: first.toLocaleDateString(this.locale, { month: 'long', year: 'numeric' }) }), @@ -726,6 +751,8 @@ form.appendChild(errBox); form.appendChild(cta); form.addEventListener('submit', function (e) { e.preventDefault(); + // In flight already (double click, Enter), or already booked: never send twice. + if (cta.disabled || self.state.view === 'confirm') return; errBox.textContent = ''; if (phoneRequired && !phone.value.trim()) { errBox.textContent = t(self.i18n, 'required_fields_error'); @@ -760,6 +787,7 @@ // Paid event types: the server returns a Stripe Checkout URL. Send the visitor // there (top window, so it isn't trapped in the host page's frame). if (res.data && res.data.checkout_url) { (window.top || window).location.href = res.data.checkout_url; return; } + self.state.bookingId = (res.data && res.data.id) || ''; self.state.view = 'confirm'; self.render(); self.dispatchEvent(new CustomEvent('calnode:booked', { bubbles: true, composed: true, detail: res.data })); }).catch(function (err) { @@ -770,18 +798,40 @@ return el('div', {}, [back, el('p', { class: 'slot-label', text: shortDay(slot.start, this.locale) + ' · ' + timeLabel(slot.start, this.locale) }), form]); } + // confirmView is the final state (#268). The widget never navigates the host page, so + // "Book another time" resets the widget's own state instead, and reloads the month, + // which no longer offers the slot just taken. confirmView(slot) { + var self = this; + var again = el('button', { class: 'book-another', type: 'button', text: t(this.i18n, 'book_another_time') }); + again.addEventListener('click', function () { self.bookAnother(); }); + // A configured redirect is offered, never followed: navigating would take the + // customer's own site away. "Continue" opens it in a new tab instead (#268). + var info = this.info || {}; + var target = redirectTarget(info.redirect_url, this.state.bookingId, info.redirect_with_booking_id); + var cont = null; + if (target) { + cont = el('button', { class: 'btn-primary continue-link', type: 'button', text: t(this.i18n, 'continue') }); + cont.addEventListener('click', function () { window.open(target, '_blank', 'noopener'); }); + } return el('div', {}, [ el('div', { class: 'confirm-icon', html: SVG_CHECK }), el('div', { class: 'confirm-view' }, [ el('h3', { text: t(this.i18n, 'booking_confirmed') }), el('p', { class: 'when', text: shortDay(slot.start, this.locale) + ' · ' + timeLabel(slot.start, this.locale) }), el('p', { class: 'sub', text: t(this.i18n, 'confirmation_email_sent') }), - ]), + ].concat(cont ? [cont] : [], [again])), ]); } + bookAnother() { + this.state.day = null; this.state.slot = null; this.state.bookingId = ''; this.state.view = 'pick'; + var self = this; + this.loadMonth().then(function () { self.render(); }); + } + nav(delta) { + if (this.state.view === 'confirm') return; this.state.month = addMonths(this.state.month, delta); this.state.day = null; this.state.view = 'pick'; var self = this; @@ -802,7 +852,7 @@ render() { var self = this; this.wrap.innerHTML = ''; - this.card = el('div', { class: 'card' }, [this.infoPane(), this.calPane(), this.rightPane()]); + this.card = el('div', { class: 'card' + (this.state.view === 'confirm' ? ' is-final' : '') }, [this.infoPane(), this.calPane(), this.rightPane()]); // In step-flow, a slots/form view needs a back-to-calendar affordance. if (this.narrow && (this.state.view === 'pick' && this.state.day)) { var rc = this.card.querySelector('.right-col'); diff --git a/internal/handler/event_type.go b/internal/handler/event_type.go index 57bb725a..b81bf76d 100644 --- a/internal/handler/event_type.go +++ b/internal/handler/event_type.go @@ -42,6 +42,11 @@ 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"` + // RedirectURL is where the booking page sends the booker after a confirmed booking + // (nil = no redirect; the page shows its own final confirmation). Absolute https, no + // credentials: validRedirectURL. RedirectWithBookingID appends ?booking_id=. (#268) + RedirectURL *string `json:"redirect_url"` + RedirectWithBookingID bool `json:"redirect_with_booking_id"` // 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"` @@ -107,9 +112,9 @@ func scanEventType(s rowScanner) (*eventTypeJSON, error) { // pointers (e.g. the computed `owned` column from the list/get queries). func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { var et eventTypeJSON - var desc, locVal, msgConf, msgCancel, msgResched, msgRemind, msgGreeting sql.NullString + var desc, locVal, msgConf, msgCancel, msgResched, msgRemind, msgGreeting, redirectURL sql.NullString var subjConf, subjCancel, subjResched, subjRemind sql.NullString - var isActive, isPublic, showTaken, showNext int + var isActive, isPublic, showTaken, showNext, redirectWithID int dests := []any{ &et.ID, &et.Slug, &et.Name, &desc, @@ -122,6 +127,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, + &redirectURL, &redirectWithID, } dests = append(dests, trailing...) err := s.Scan(dests...) @@ -140,6 +146,10 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { et.IsActive = isActive != 0 et.IsPublic = isPublic != 0 et.ShowTakenSlots = showTaken != 0 + if redirectURL.Valid && redirectURL.String != "" { + et.RedirectURL = &redirectURL.String + } + et.RedirectWithBookingID = redirectWithID != 0 et.ShowNextAvailable = showNext != 0 if msgConf.Valid { et.MsgConfirmation = &msgConf.String @@ -181,7 +191,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, + redirect_url, redirect_with_booking_id` // selectETCols fetches a single event type without the caller-relative columns. const selectETCols = "SELECT " + etColumns + " FROM event_types" @@ -288,6 +299,8 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { ShowTakenSlots *bool `json:"show_taken_slots"` ShowNextAvailable *bool `json:"show_next_available"` InviteDelivery *string `json:"invite_delivery"` + RedirectURL *string `json:"redirect_url"` + RedirectWithID *bool `json:"redirect_with_booking_id"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { h.writeError(w, http.StatusBadRequest, "invalid JSON") @@ -362,6 +375,18 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { if req.ShowTakenSlots != nil && *req.ShowTakenSlots { showTaken = 1 } + var redirectURL any // NULL unless a non-empty, valid URL was given + if req.RedirectURL != nil { + v, ok := validRedirectURL(*req.RedirectURL) + if !ok { + h.writeError(w, http.StatusBadRequest, errRedirectURL) + return + } + if v != "" { + redirectURL = v + } + } + redirectWithID := req.RedirectWithID != nil && *req.RedirectWithID showNext := 0 if req.ShowNextAvailable != nil && *req.ShowNextAvailable { showNext = 1 @@ -395,12 +420,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, + redirect_url, redirect_with_booking_id) + 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, + redirectURL, redirectWithID) if err != nil { if db.IsUniqueViolation(err) { h.writeError(w, http.StatusConflict, "slug already in use") @@ -531,6 +558,8 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { ShowTakenSlots *bool `json:"show_taken_slots"` ShowNextAvailable *bool `json:"show_next_available"` InviteDelivery *string `json:"invite_delivery"` + RedirectURL *string `json:"redirect_url"` // "" clears it + RedirectWithID *bool `json:"redirect_with_booking_id"` Archived *bool `json:"archived"` MsgConfirmation *string `json:"msg_confirmation"` MsgCancellation *string `json:"msg_cancellation"` @@ -688,6 +717,9 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { } set("show_taken_slots", v) } + if req.RedirectWithID != nil { + set("redirect_with_booking_id", *req.RedirectWithID) + } if req.ShowNextAvailable != nil { v := 0 if *req.ShowNextAvailable { @@ -773,10 +805,10 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { // Look up the event type ID, owner + current location (needed for reminder upsert, // to verify the caller may edit it, and to validate the effective online-meeting // location below). - var etID, ownerID, curLocType, curLocVal, curInviteDelivery string + var etID, ownerID, curLocType, curLocVal, curInviteDelivery, curRedirectURL string err := h.db.QueryRowContext(r.Context(), - `SELECT id, user_id, location_type, COALESCE(location_value, ''), invite_delivery FROM event_types WHERE slug = ?`, slug). - Scan(&etID, &ownerID, &curLocType, &curLocVal, &curInviteDelivery) + `SELECT id, user_id, location_type, COALESCE(location_value, ''), invite_delivery, COALESCE(redirect_url, '') FROM event_types WHERE slug = ?`, slug). + Scan(&etID, &ownerID, &curLocType, &curLocVal, &curInviteDelivery, &curRedirectURL) if err == sql.ErrNoRows || (err == nil && !canManageEventType(user, ownerID)) { h.writeError(w, http.StatusNotFound, "event type not found") return @@ -836,6 +868,23 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { set("invite_delivery", newInviteDelivery) } + // And for the redirect: the editor re-submits it on every save, so a stored value that + // no longer passes (written by hand, or before a rule was tightened; servedRedirectURL + // already serves it as no redirect) must not lock the operator out of other fields. + // A changed value is validated; an unchanged one is left as it is. + if req.RedirectURL != nil && strings.TrimSpace(*req.RedirectURL) != curRedirectURL { + v, ok := validRedirectURL(*req.RedirectURL) + if !ok { + h.writeError(w, http.StatusBadRequest, errRedirectURL) + return + } + if v == "" { + set("redirect_url", nil) + } else { + set("redirect_url", v) + } + } + // The slug is the public booking URL, so renaming one that is already in circulation // breaks every link to it: an invitation in somebody's inbox, a page embedding the // widget, a QR code on a card. It is allowed only while the event type has no diff --git a/internal/handler/event_type_duplicate.go b/internal/handler/event_type_duplicate.go index 42ddf567..46babb6a 100644 --- a/internal/handler/event_type_duplicate.go +++ b/internal/handler/event_type_duplicate.go @@ -143,7 +143,8 @@ 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, + redirect_url, redirect_with_booking_id) SELECT ?, user_id, team_id, ?, name, description, duration_minutes, slot_interval_minutes, @@ -154,7 +155,8 @@ 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, + redirect_url, redirect_with_booking_id 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..93b31773 100644 --- a/internal/handler/event_type_duplicate_test.go +++ b/internal/handler/event_type_duplicate_test.go @@ -610,6 +610,7 @@ func TestDuplicateEventType_handlesEveryEventTypeColumn(t *testing.T) { "price_cents": true, "currency": true, "invite_delivery": true, "display_order": true, + "redirect_url": true, "redirect_with_booking_id": true, } // Deliberately not inherited, with the reason. notInherited := map[string]string{ diff --git a/internal/handler/redirect_url.go b/internal/handler/redirect_url.go new file mode 100644 index 00000000..1fc43f3b --- /dev/null +++ b/internal/handler/redirect_url.go @@ -0,0 +1,62 @@ +package handler + +import ( + "net/http" + "net/url" + "strings" +) + +// maxRedirectURLLen bounds event_types.redirect_url. Generous for a thank-you page with +// tracking parameters, small enough that the column can't be used as storage. +const maxRedirectURLLen = 2000 + +// validRedirectURL checks an event type's post-booking redirect (#268) and returns it +// trimmed. Empty is valid and means "no redirect". Anything else must be an absolute +// https URL with a host and no credentials: the same https-and-host rule as the other +// operator-supplied links (validVideoURL), tightened because this one is navigated to +// automatically. Userinfo is refused because "https://trusted.example@evil.example/" +// reads as one site and goes to another, which is what makes an admin-set redirect worth +// stealing. Whitespace and control characters are refused rather than cleaned up. +// +// Checked when the event type is saved, again when a page or the widget is given the +// value, and once more in the browser before navigating (BookingLogic.redirectTarget and +// its mirror in embed.js), so a value that predates a tightened rule never reaches a +// visitor. +func validRedirectURL(raw string) (string, bool) { + v := strings.TrimSpace(raw) + if v == "" { + return "", true + } + if len(v) > maxRedirectURLLen { + return "", false + } + for _, r := range v { + if r <= ' ' || r == 0x7f { + return "", false + } + } + u, err := url.Parse(v) + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Opaque != "" { + return "", false + } + return v, true +} + +// errRedirectURL is the message for a refused redirect_url. +const errRedirectURL = "redirect_url must be an absolute https:// URL without credentials (user:password@)" + +// servedRedirectURL is the redirect a booking page or the widget may be given: the +// stored value if it still passes validRedirectURL, otherwise "" (no redirect), logged +// so the operator can find and fix it. A row written before a rule was tightened, or by +// hand, must not reach a visitor. +func (h *Handler) servedRedirectURL(r *http.Request, slug, raw string) string { + if raw == "" { + return "" + } + v, ok := validRedirectURL(raw) + if !ok { + h.logger.WarnContext(r.Context(), "event type redirect_url fails validation; not redirecting", "slug", slug) + return "" + } + return v +} diff --git a/internal/handler/redirect_url_internal_test.go b/internal/handler/redirect_url_internal_test.go new file mode 100644 index 00000000..7ed57a8a --- /dev/null +++ b/internal/handler/redirect_url_internal_test.go @@ -0,0 +1,314 @@ +package handler + +import ( + "context" + "encoding/json" + "log/slog" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" + + "github.com/calnode/calnode/internal/db" + "github.com/calnode/calnode/internal/payments" +) + +func TestValidRedirectURL(t *testing.T) { + ok := map[string]string{ + "": "", + " ": "", + "https://example.com/thanks": "https://example.com/thanks", + " https://example.com/t?a=1#done ": "https://example.com/t?a=1#done", + "https://sub.example.co.uk:8443/x/y": "https://sub.example.co.uk:8443/x/y", + } + for in, want := range ok { + got, valid := validRedirectURL(in) + if !valid || got != want { + t.Errorf("validRedirectURL(%q) = %q, %v; want %q, true", in, got, valid, want) + } + } + for _, in := range []string{ + "http://example.com/thanks", // https only + "javascript:alert(1)", // not a web URL + "data:text/html,hi", // + "//example.com/thanks", // protocol-relative + "/thanks", // relative + "https:example.com", // opaque, no host + "https://:8080/thanks", // port, but no host + "https://user:pw@example.com/", // credentials + "https://trusted.example@evil.example/", // reads as one site, goes to another + "https://exa mple.com/", // whitespace inside + "https://example.com/\nx", // control character + "https://" + strings.Repeat("a", 2000), // too long + } { + if v, valid := validRedirectURL(in); valid { + t.Errorf("validRedirectURL(%q) accepted it as %q", in, v) + } + } +} + +// redirectFixture is a workspace with one public event type, "intro". +type redirectFixture struct { + h *Handler + apiKey string +} + +func newRedirectFixture(t *testing.T) redirectFixture { + 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()) + 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"` + } + json.Unmarshal(rec.Body.Bytes(), &setup) //nolint:errcheck + f := redirectFixture{h: h, apiKey: setup.APIKey} + if rec := f.call(t, h.CreateEventType, http.MethodPost, "/v1/event-types", "", + `{"slug":"intro","name":"Intro","duration_minutes":30,"location_type":"phone","location_value":"+48 600 100 200"}`); rec.Code != http.StatusCreated { + t.Fatalf("create event type: %d — %s", rec.Code, rec.Body.String()) + } + return f +} + +func (f redirectFixture) call(t *testing.T, fn http.HandlerFunc, method, path, slug, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("X-API-Key", f.apiKey) + if slug != "" { + req.SetPathValue("slug", slug) + } + rec := httptest.NewRecorder() + f.h.RequireAuth(fn)(rec, req) + return rec +} + +func (f redirectFixture) patch(t *testing.T, body string) *httptest.ResponseRecorder { + t.Helper() + return f.call(t, f.h.PatchEventType, http.MethodPatch, "/v1/event-types/intro", "intro", body) +} + +func (f redirectFixture) get(t *testing.T) (redirect *string, withID bool) { + t.Helper() + rec := f.call(t, f.h.GetEventType, http.MethodGet, "/v1/event-types/intro", "intro", "") + var et struct { + RedirectURL *string `json:"redirect_url"` + WithID bool `json:"redirect_with_booking_id"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &et); err != nil { + t.Fatalf("decode: %v — %s", err, rec.Body.String()) + } + return et.RedirectURL, et.WithID +} + +func TestRedirectURL_savedOnlyWhenValid(t *testing.T) { + f := newRedirectFixture(t) + if r, _ := f.get(t); r != nil { + t.Fatalf("a new event type has no redirect; got %q", *r) + } + + if rec := f.patch(t, `{"redirect_url":"http://example.com/thanks"}`); rec.Code != http.StatusBadRequest { + t.Fatalf("http:// should be refused with 400, got %d", rec.Code) + } + if rec := f.patch(t, `{"redirect_url":"https://a.example@evil.example/"}`); rec.Code != http.StatusBadRequest { + t.Fatalf("credentials should be refused with 400, got %d", rec.Code) + } + if r, _ := f.get(t); r != nil { + t.Fatalf("a refused PATCH must leave nothing behind; got %q", *r) + } + + if rec := f.patch(t, `{"redirect_url":" https://example.com/thanks ","redirect_with_booking_id":true}`); rec.Code != http.StatusOK { + t.Fatalf("valid PATCH: %d — %s", rec.Code, rec.Body.String()) + } + if r, withID := f.get(t); r == nil || *r != "https://example.com/thanks" || !withID { + t.Fatalf("got %v, %v; want the trimmed URL and the flag on", r, withID) + } + + if rec := f.patch(t, `{"redirect_url":""}`); rec.Code != http.StatusOK { + t.Fatalf("clearing PATCH: %d", rec.Code) + } + if r, _ := f.get(t); r != nil { + t.Fatalf(`"" should clear the redirect; got %q`, *r) + } + + // A stored value that no longer passes (a hand-written row) must not make the event + // type unsaveable: the editor re-submits it with every unrelated change. + if _, err := f.h.db.Exec(`UPDATE event_types SET redirect_url = 'http://legacy.example/' WHERE slug = 'intro'`); err != nil { + t.Fatal(err) + } + if rec := f.patch(t, `{"name":"Intro call","redirect_url":"http://legacy.example/"}`); rec.Code != http.StatusOK { + t.Fatalf("an unchanged legacy redirect blocked an unrelated edit: %d — %s", rec.Code, rec.Body.String()) + } + if rec := f.patch(t, `{"redirect_url":"http://other.example/"}`); rec.Code != http.StatusBadRequest { + t.Fatalf("changing it to another invalid value should still be 400, got %d", rec.Code) + } + if rec := f.patch(t, `{"redirect_url":""}`); rec.Code != http.StatusOK { + t.Fatalf("clearing the legacy redirect: %d", rec.Code) + } + + // Create validates too. + if rec := f.call(t, f.h.CreateEventType, http.MethodPost, "/v1/event-types", "", + `{"slug":"other","name":"Other","duration_minutes":30,"location_type":"phone","location_value":"+48 600 100 200","redirect_url":"javascript:alert(1)"}`); rec.Code != http.StatusBadRequest { + t.Fatalf("create with a bad redirect should be 400, got %d", rec.Code) + } +} + +// The booking page and the widget's /public payload carry the redirect, and a stored +// value that fails validation (a row written by hand, or before a rule was tightened) +// is served as no redirect at all. +func TestRedirectURL_servedToPageAndWidget(t *testing.T) { + f := newRedirectFixture(t) + + page := func() string { + req := httptest.NewRequest(http.MethodGet, "/book/intro", nil) + req.SetPathValue("slug", "intro") + rec := httptest.NewRecorder() + f.h.BookPage(rec, req) + return rec.Body.String() + } + public := func() map[string]any { + req := httptest.NewRequest(http.MethodGet, "/v1/event-types/intro/public", nil) + req.SetPathValue("slug", "intro") + rec := httptest.NewRecorder() + f.h.PublicEventType(rec, req) + var m map[string]any + json.Unmarshal(rec.Body.Bytes(), &m) //nolint:errcheck + return m + } + + if p := page(); !redirectConst(p, `""`) { + t.Errorf("no redirect should render an empty REDIRECT_URL") + } + if m := public(); m["redirect_url"] != "" || m["redirect_with_booking_id"] != false { + t.Errorf("public payload without a redirect: %v / %v", m["redirect_url"], m["redirect_with_booking_id"]) + } + + f.patch(t, `{"redirect_url":"https://example.com/thanks?src=cal","redirect_with_booking_id":true}`) + p := page() + if !redirectConst(p, `"https://example.com/thanks?src=cal"`) { + t.Errorf("page should carry the redirect as a JS string; script excerpt: %s", excerpt(p, "REDIRECT_URL")) + } + if !withIDConst(p, "true") { + t.Errorf("page should carry the booking_id flag") + } + if m := public(); m["redirect_url"] != "https://example.com/thanks?src=cal" || m["redirect_with_booking_id"] != true { + t.Errorf("public payload: %v / %v", m["redirect_url"], m["redirect_with_booking_id"]) + } + + if _, err := f.h.db.Exec(`UPDATE event_types SET redirect_url = 'http://legacy.example/' WHERE slug = 'intro'`); err != nil { + t.Fatal(err) + } + if p := page(); !redirectConst(p, `""`) || !withIDConst(p, "false") { + t.Errorf("an invalid stored redirect must be served as none; got %s", excerpt(p, "REDIRECT_URL")) + } + if m := public(); m["redirect_url"] != "" { + t.Errorf("an invalid stored redirect must not reach the widget; got %v", m["redirect_url"]) + } +} + +// redirectConst and withIDConst match the page's two redirect constants whatever +// whitespace html/template puts around the values. +func redirectConst(page, jsValue string) bool { + return regexp.MustCompile(`const REDIRECT_URL\s*=\s*` + regexp.QuoteMeta(jsValue) + `\s*;`).MatchString(page) +} + +func withIDConst(page, v string) bool { + return regexp.MustCompile(`const REDIRECT_WITH_ID\s*=\s*` + v + `\s*;`).MatchString(page) +} + +func excerpt(s, near string) string { + i := strings.Index(s, near) + if i < 0 { + return "(" + near + " not found)" + } + end := i + 160 + if end > len(s) { + end = len(s) + } + return s[i:end] +} + +// captureCheckout is a payments.Provider that records the checkout request. +type captureCheckout struct { + payments.Provider + req payments.CheckoutRequest +} + +func (c *captureCheckout) Name() string { return "stripe" } +func (c *captureCheckout) CreateCheckout(_ context.Context, req payments.CheckoutRequest) (*payments.CheckoutSession, error) { + c.req = req + return &payments.CheckoutSession{ID: "cs_test", URL: "https://checkout.example/cs_test"}, nil +} + +// On the return from Checkout the page cannot otherwise know which booking it was, so the +// success URL carries booking_id for the redirect's optional ?booking_id= (#268). +func TestBookingCheckout_successURLCarriesBookingID(t *testing.T) { + f := newRedirectFixture(t) + f.h.SetMailer(nil, "https://cal.example") + p := &captureCheckout{} + if _, err := f.h.startBookingCheckout(context.Background(), p, "b-123", 5000, "eur", "Intro", "intro", "ana@example.com"); err != nil { + t.Fatalf("startBookingCheckout: %v", err) + } + want := "/book/intro?paid=1&booking_id=b-123&session_id={CHECKOUT_SESSION_ID}" + if !strings.HasSuffix(p.req.SuccessURL, want) { + t.Errorf("SuccessURL = %q; want it to end with %q", p.req.SuccessURL, want) + } +} + +// The widget lives on someone else's page: a configured redirect is offered as a +// "Continue" that opens a new tab, never followed in place, and it is re-checked by the +// widget's own mirror of redirectTarget first. +func TestEmbedJS_redirectOpensNewTab(t *testing.T) { + h := &Handler{} + rec := httptest.NewRecorder() + h.EmbedJS(rec, httptest.NewRequest(http.MethodGet, "/embed.js", nil)) + body := rec.Body.String() + for _, want := range []string{ + "function redirectTarget(raw, bookingId, withId) {", + "u.protocol !== 'https:' || !u.hostname || u.username || u.password", + "redirectTarget(info.redirect_url, this.state.bookingId, info.redirect_with_booking_id)", + "window.open(target, '_blank', 'noopener')", + } { + if !strings.Contains(body, want) { + t.Errorf("embed.js no longer contains %q", want) + } + } + if strings.Contains(body, "location.assign(target)") || strings.Contains(body, "location.href = target") { + t.Error("the widget must never navigate the host page to the redirect") + } +} + +// A booking made in the assistant chat ends the page and the widget like one made +// through the form (#268): book.html's chat script announces it to the page script, whose +// listener the behaviour harness covers ("redirect-assistant"), and the widget's chat +// switches to the confirmation view, where its Continue lives. +func TestAssistantBooking_reachesTheFinalState(t *testing.T) { + if !strings.Contains(bookTmplSrc, "if (booking) document.dispatchEvent(new CustomEvent('calnode:assistant-booked', { detail: booking }));") { + t.Error("book.html's assistant chat no longer announces its booking to the page script") + } + h := &Handler{} + rec := httptest.NewRecorder() + h.EmbedJS(rec, httptest.NewRequest(http.MethodGet, "/embed.js", nil)) + body := rec.Body.String() + for _, want := range []string{ + "this.state.slot = { start: booking.start_at };", + "this.state.bookingId = booking.id;", + "this.state.view = 'confirm';", + } { + if !strings.Contains(body, want) { + t.Errorf("embed.js chat booking no longer contains %q", want) + } + } +} diff --git a/internal/handler/stripe_booking.go b/internal/handler/stripe_booking.go index b2aba742..17962047 100644 --- a/internal/handler/stripe_booking.go +++ b/internal/handler/stripe_booking.go @@ -4,6 +4,7 @@ import ( "context" "io" "net/http" + "net/url" "time" "github.com/calnode/calnode/internal/payments" @@ -26,7 +27,10 @@ func (h *Handler) startBookingCheckout(ctx context.Context, provider payments.Pr ProductName: productName, CustomerEmail: email, // Stripe substitutes {CHECKOUT_SESSION_ID}; the page shows a "payment received" banner. - SuccessURL: base + "/book/" + slug + "?paid=1&session_id={CHECKOUT_SESSION_ID}", + // booking_id lets the page hand the booking to an event type's post-booking + // redirect (redirect_with_booking_id, #268), which it otherwise cannot know on + // the return leg. + SuccessURL: base + "/book/" + slug + "?paid=1&booking_id=" + url.QueryEscape(bookingID) + "&session_id={CHECKOUT_SESSION_ID}", CancelURL: base + "/book/" + slug, ExpiresAt: time.Now().Add(checkoutHoldWindow), Metadata: map[string]string{"booking_id": bookingID}, diff --git a/internal/handler/templates/book.html b/internal/handler/templates/book.html index e353a7a5..bb64cb38 100644 --- a/internal/handler/templates/book.html +++ b/internal/handler/templates/book.html @@ -264,6 +264,8 @@

{{.Name}}

{{call .T "booking_confirmed"}}

{{call .T "confirmation_email_sent"}}

+ + {{call .T "book_another_time"}} @@ -291,6 +293,14 @@

{{call .T "booking_confirmed"}}

const SOLE_HOST = {{.SoleHostName}}; const MIN_NOTICE_LABEL = {{.MinNoticeLabel}}; const LOCALE = "{{.Locale}}"; + // Post-booking redirect (#268): "" when the event type sets none. Validated on save and + // on serve, and once more by BookingLogic.redirectTarget before navigating. + const REDIRECT_URL = {{.RedirectURL}}; + const REDIRECT_WITH_ID = {{.RedirectWithBookingID}}; + // Long enough for the confirmation to register and the dataLayer/GA4 conversion pushed + // right after finalize() to go out; short enough not to feel like a stall. The + // "Continue" button is there for anyone who doesn't want to wait. + const REDIRECT_DELAY_MS = 1500; const I18N = window.__CALNODE_I18N || {}; function t(key) { return I18N[key] || key; } // key itself as a last-resort fallback, matching Locale.T server-side let TZ = Intl.DateTimeFormat().resolvedOptions().timeZone; @@ -306,6 +316,12 @@

{{call .T "booking_confirmed"}}

let noticeDates = new Set(); // days the minimum-notice policy took starts away from let slotsDegraded = false; // an external calendar check failed: busy data is // incomplete, so offered times may be unbookable + // finalized: a booking was confirmed (here, or on return from Stripe Checkout). The + // confirmation is then a final state: the calendar, slots, form and timezone stop + // responding, and "Book another time" reloads the page for a clean start. Leaving them + // live invited a second booking under a different email, which max_active_bookings + // cannot catch (#268). Every handler below checks this flag, not just the markup. + let finalized = false; const $ = id => document.getElementById(id); const pad = n => String(n).padStart(2, '0'); @@ -379,6 +395,39 @@

{{call .T "booking_confirmed"}}

); } + // finalize puts the page in its final, confirmed state (see `finalized`). Safe to call + // before the calendar has rendered: renderCal reads the flag when it next runs. + // bookingId feeds the redirect's optional ?booking_id=; it may be empty. + function finalize(bookingId) { + finalized = true; + const card = document.querySelector('.card'); + if (card) card.classList.add('is-final'); + $('booking-form').reset(); + $('submit-btn').disabled = true; + $('tz-select').disabled = true; + $('prev-btn').disabled = true; + $('next-btn').disabled = true; + $('empty-hint').classList.add('hidden'); + $('notice-hint').classList.add('hidden'); + // A fresh load is the reset: no picked day, slot, hosts or form state can survive it. + // The Stripe return parameters are dropped so the page doesn't land here again. + const url = new URL(window.location.href); + url.searchParams.delete('paid'); + url.searchParams.delete('session_id'); + $('book-another').href = url.pathname + url.search; + showView('confirm-view'); + + // With a redirect, the confirmation is a waypoint: show where the booker is going + // and go. "Book another time" is hidden then, since the page is about to leave. + const target = BookingLogic.redirectTarget(REDIRECT_URL, bookingId, REDIRECT_WITH_ID); + if (target) { + $('continue-link').href = target; + $('continue-link').classList.remove('hidden'); + $('book-another').classList.add('hidden'); + setTimeout(() => window.location.assign(target), REDIRECT_DELAY_MS); + } + } + // Returning from Stripe Checkout (success_url): the payment was captured and the booking // is confirmed by webhook. Show a payment-received confirmation instead of the picker. (function () { @@ -388,7 +437,7 @@

{{call .T "booking_confirmed"}}

var _csub = document.querySelector('#confirm-view .sub'); if (_ch3) _ch3.textContent = t('payment_received'); if (_csub) _csub.textContent = t('payment_confirmed_sub'); - showView('confirm-view'); + finalize(params.get('booking_id') || ''); // Fire the conversion event for paid bookings too (the form-submit path redirected to // Stripe before it could). transaction_id lets GA4/GTM dedupe on refresh. if (window.__CALNODE_DL && typeof calnodePush === 'function') { @@ -405,6 +454,17 @@

{{call .T "booking_confirmed"}}

if (typeof ga4Convert === 'function') ga4Convert(true, PRICE_CENTS / 100, CURRENCY, params.get('session_id')); })(); + // A booking made in the assistant chat (its own script, further down) ends the page + // the same way as the form: the final state, and the redirect if one is configured. + document.addEventListener('calnode:assistant-booked', (e) => { + const b = (e && e.detail) || {}; + if (finalized || !b.id) return; + if (b.start_at) $('confirm-time').textContent = `${fmtDate(new Date(b.start_at))} · ${fmtTime(b.start_at)}`; + finalize(b.id); + setStep('right'); + renderCal(); + }); + // ── Mobile step-flow ──────────────────────────────────────────────────────── // On narrow viewports (CSS-gated) we show one section at a time: calendar, then // the right pane (slots → form → confirm). On desktop the classes are inert. @@ -414,7 +474,9 @@

{{call .T "booking_confirmed"}}

cardEl.classList.toggle('m-cal', s === 'cal'); cardEl.classList.toggle('m-right', s === 'right'); } - setStep('cal'); + // A page that is already final (the Stripe return) opens on the right pane, where the + // confirmation lives; the calendar step would hide it on a narrow viewport. + setStep(finalized ? 'right' : 'cal'); // ── Description clamp + "Show more" ───────────────────────────────────────── // Clamp to 2 lines only in constrained layouts (where the 3 columns can't fit); @@ -513,10 +575,10 @@

{{call .T "booking_confirmed"}}

const thisMonFirst = new Date(today.getFullYear(), today.getMonth(), 1); const navFirst = new Date(navYear, navMonth, 1); - $('prev-btn').disabled = navFirst <= thisMonFirst; - $('next-btn').disabled = maxDate + $('prev-btn').disabled = finalized || navFirst <= thisMonFirst; + $('next-btn').disabled = finalized || (maxDate ? navFirst >= new Date(maxDate.getFullYear(), maxDate.getMonth(), 1) - : false; + : false); let h = DOW_LABELS.map(d => `
${d}
`).join(''); for (let i = 0; i < startOffset; i++) h += '
'; @@ -537,7 +599,7 @@

{{call .T "booking_confirmed"}}

if (isSel) cls += ' sel'; if (isToday) cls += ' today'; - if (disabled || !hasSlots) { + if (disabled || !hasSlots || finalized) { h += ``; } else { h += ``; @@ -548,15 +610,18 @@

{{call .T "booking_confirmed"}}

} $('prev-btn').addEventListener('click', () => { + if (finalized) return; if (navMonth-- === 0) { navMonth = 11; navYear--; } loadMonthAvailability(navYear, navMonth); }); $('next-btn').addEventListener('click', () => { + if (finalized) return; if (navMonth++ === 11) { navMonth = 0; navYear++; } loadMonthAvailability(navYear, navMonth); }); $('cal').addEventListener('click', e => { + if (finalized) return; const btn = e.target.closest('.cd'); if (!btn || btn.disabled) return; pickDate(btn.dataset.ds, +btn.dataset.y, +btn.dataset.m, +btn.dataset.d); @@ -575,7 +640,7 @@

{{call .T "booking_confirmed"}}

const el = $('notice-hint'); if (!el) return; const text = noticeHintText(); - const show = !pickedDate && noticeDates.size > 0 && text !== ''; + const show = !finalized && !pickedDate && noticeDates.size > 0 && text !== ''; el.textContent = show ? text : ''; el.classList.toggle('hidden', !show); } @@ -629,6 +694,7 @@

{{call .T "booking_confirmed"}}

} async function pickDate(ds, y, m, d) { + if (finalized) return; pickedDate = new Date(y, m, d); pickedSlot = null; restoreDefaultHosts(); @@ -663,6 +729,7 @@

{{call .T "booking_confirmed"}}

} $('slots-list').addEventListener('click', e => { + if (finalized) return; const period = e.target.closest('[data-period]'); if (period) { selectedPeriod = Number(period.dataset.period); @@ -677,6 +744,7 @@

{{call .T "booking_confirmed"}}

// ── Slot pick ───────────────────────────────────────────────────────────── function pickSlot(i) { + if (finalized) return; if (i < 0 || i >= slotsCache.length) return; if (slotsCache[i].taken) return; // never bookable, whatever route got us here pickedSlot = slotsCache[i]; @@ -688,13 +756,16 @@

{{call .T "booking_confirmed"}}

showView('form-view'); } - $('back-btn').addEventListener('click', () => showView('slots-view')); - $('cal-back-btn').addEventListener('click', () => setStep('cal')); + $('back-btn').addEventListener('click', () => { if (!finalized) showView('slots-view'); }); + $('cal-back-btn').addEventListener('click', () => { if (!finalized) setStep('cal'); }); // ── Booking form ────────────────────────────────────────────────────────── + // `submitting` closes the window between the click and the response, where a double + // click or Enter would otherwise send the same booking twice. + let submitting = false; $('booking-form').addEventListener('submit', async e => { e.preventDefault(); - if (!pickedSlot) return; + if (finalized || submitting || !pickedSlot) return; const form = e.target; const btn = $('submit-btn'); const errEl = $('form-error'); @@ -735,6 +806,7 @@

{{call .T "booking_confirmed"}}

} btn.disabled = true; btn.textContent = t('confirming'); errEl.textContent = ''; + submitting = true; try { const r = await fetch('/v1/bookings', { @@ -784,7 +856,12 @@

{{call .T "booking_confirmed"}}

} $('confirm-time').textContent = `${fmtDate(pickedDate)} · ${fmtTime(pickedSlot.start)}`; - showView('confirm-view'); + // Read before finalize() resets the form: the dataLayer event below reports them. + const attendeeName = form.name.value.trim(); + const attendeeEmail = form.email.value.trim(); + const attendeePhone = form.elements.phone?.value.trim() || ""; + finalize((booked && booked.id) || ''); + renderCal(); if (window.__CALNODE_DL && typeof calnodePush === 'function') { var dlAnswers = {}; @@ -801,9 +878,9 @@

{{call .T "booking_confirmed"}}

status: 'confirmed', location: (booked && booked.location_value) || '', host_name: (booked && Array.isArray(booked.hosts)) ? booked.hosts.map(function (h) { return h.name; }).join(', ') : '', - attendee_name: form.name.value.trim(), - attendee_email: form.email.value.trim(), - phone: form.elements.phone?.value.trim() || "", + attendee_name: attendeeName, + attendee_email: attendeeEmail, + phone: attendeePhone, attendee_timezone: TZ, answers: dlAnswers, is_paid: false, @@ -813,17 +890,15 @@

{{call .T "booking_confirmed"}}

} if (typeof ga4Convert === 'function') ga4Convert(false, PRICE_CENTS / 100, CURRENCY, booked && booked.id); - // Booking succeeded. Re-enable the button so a second booking attempt in the - // same session (before the page is refreshed) isn't silently blocked by a - // button left disabled from this success. Every error path already resets it; - // the success path didn't, which is what left it stuck on "Confirming…". - // The server enforces the per-invitee active-booking cap and returns a clear - // message, so the resubmit surfaces that instead of hanging. - btn.disabled = false; btn.textContent = t('confirm_booking'); + // Booking succeeded: the button stays disabled. The confirmation is final + // (finalize), and another booking starts from "Book another time", a fresh load. + btn.textContent = t('confirm_booking'); } catch { errEl.textContent = t('network_error'); btn.disabled = false; btn.textContent = t('confirm_booking'); + } finally { + submitting = false; } }); @@ -901,6 +976,7 @@

{{call .T "booking_confirmed"}}

})); $('tz-select').addEventListener('change', async e => { + if (finalized) return; TZ = e.target.value; resizeTzSelect(); loadNextAvailable(); // the soonest time is a different wall-clock time in the new tz @@ -1020,6 +1096,7 @@

{{call .T "booking_confirmed"}}

calnodePush('calnode_booking_confirmed', { booking_id: booking.id, via: 'assistant' }); } if (booking && typeof ga4Convert === 'function') ga4Convert(false, 0, '', booking.id); + if (booking) document.dispatchEvent(new CustomEvent('calnode:assistant-booked', { detail: booking })); } catch (err) { if (typing.parentNode) typing.remove(); add(t('assistant_error'), 'note'); diff --git a/internal/handler/templates/booking.css b/internal/handler/templates/booking.css index b5ee4217..208ac6b2 100644 --- a/internal/handler/templates/booking.css +++ b/internal/handler/templates/booking.css @@ -321,6 +321,23 @@ button, input, select, textarea { font-family: inherit; } .confirm-view h3 { font-size: 1rem; font-weight: 700; margin-bottom: .375rem; } .confirm-view .when { font-size: .875rem; font-weight: 600; color: #111827; margin-bottom: .25rem; } .confirm-view .sub { font-size: .8125rem; color: #6b7280; } +/* "Book another time": the only way on from a confirmed booking (#268). A link on + book.html (a fresh load is the reset), a button in the embed widget (which must not + navigate the host page); styled the same on both. */ +.book-another { + display: inline-block; margin-top: 1rem; padding: 0; + background: none; border: none; cursor: pointer; + font: inherit; font-size: .8125rem; font-weight: 500; + color: var(--booking-accent, #111827); text-decoration: underline; text-underline-offset: 2px; +} +.book-another:hover { text-decoration-thickness: 2px; } +/* Once confirmed, the calendar stays in view for context but reads as inactive. Its day + and nav buttons are disabled in script too; this is only the look of it. */ +.card.is-final .cal-col { opacity: .5; } +/* "Continue" to the event type's post-booking redirect (#268). The button style is + .btn-primary; this only spaces it inside the confirmation and lets the anchor size + like the buttons it sits beside. */ +.continue-link { display: block; margin-top: 1rem; text-align: center; text-decoration: none; } /* Avatar */ .avatar-img { diff --git a/internal/handler/templates/manage.html b/internal/handler/templates/manage.html index cfa8e0ab..0454762d 100644 --- a/internal/handler/templates/manage.html +++ b/internal/handler/templates/manage.html @@ -313,8 +313,19 @@

{{call .T "booking_cancelled_title"}}

card.classList.toggle('m-rcal', step === 'cal'); card.classList.toggle('m-rslots', step === 'slots'); } + // finalized: the booking was rescheduled or cancelled from this page. The success view + // is then final: nothing navigates away from it and neither action can be sent again, + // because CURRENT_ISO and the picked slot describe a booking that no longer looks like + // that (#268). Reloading the page shows the booking as it now is. + let finalized = false; + function finalize(id) { + showView(id); + finalized = true; + } + // Show one right-column view; the calendar column is visible only while picking. function showView(id) { + if (finalized) return; TEXT_VIEWS.forEach(v => $(v).classList.toggle('hidden', v !== id)); $('cal-col').classList.toggle('hidden', id !== 'reschedule-view'); if (id !== 'reschedule-view' && card) card.classList.remove('m-rcal', 'm-rslots'); @@ -600,6 +611,7 @@

{{call .T "booking_cancelled_title"}}

// ── Navigation ────────────────────────────────────────────────────────────── $('reschedule-btn').addEventListener('click', () => { + if (finalized) return; showView('reschedule-view'); setRStep('cal'); // mobile: start on the calendar step if (!pickedDate) { @@ -621,7 +633,7 @@

{{call .T "booking_cancelled_title"}}

// ── Confirm reschedule ────────────────────────────────────────────────────── $('confirm-reschedule-btn').addEventListener('click', async () => { - if (!pickedSlot) return; + if (finalized || !pickedSlot) return; const btn = $('confirm-reschedule-btn'), errEl = $('reschedule-error'); btn.disabled = true; btn.textContent = t('rescheduling'); errEl.textContent = ''; try { @@ -639,7 +651,7 @@

{{call .T "booking_cancelled_title"}}

btn.disabled = false; btn.textContent = t('confirm_reschedule'); return; } $('success-new-time').textContent = fmtDate(pickedDate) + ' · ' + fmtTime(pickedSlot.start); - showView('success-reschedule-view'); + finalize('success-reschedule-view'); if (window.__CALNODE_DL && typeof calnodePush === 'function') { calnodePush('calnode_booking_rescheduled', { booking_id: {{.BookingID}}, @@ -659,6 +671,7 @@

{{call .T "booking_cancelled_title"}}

// ── Confirm cancel ────────────────────────────────────────────────────────── $('confirm-cancel-btn').addEventListener('click', async () => { + if (finalized) return; const btn = $('confirm-cancel-btn'), errEl = $('cancel-error'); btn.disabled = true; btn.textContent = t('cancelling'); errEl.textContent = ''; try { @@ -675,7 +688,7 @@

{{call .T "booking_cancelled_title"}}

errEl.textContent = data.error || t('cancellation_failed_error'); btn.disabled = false; btn.textContent = t('yes_cancel_booking'); return; } - showView('success-cancel-view'); + finalize('success-cancel-view'); if (window.__CALNODE_DL && typeof calnodePush === 'function') { calnodePush('calnode_booking_cancelled', { booking_id: {{.BookingID}}, diff --git a/internal/handler/testdata/book_final_state.js b/internal/handler/testdata/book_final_state.js new file mode 100644 index 00000000..870fa2ef --- /dev/null +++ b/internal/handler/testdata/book_final_state.js @@ -0,0 +1,215 @@ +// Runs book.html's page script against a minimal fake DOM and checks that a confirmed +// booking is a final state (#268): a second submit sends nothing, and the calendar, +// slots and timezone stop responding. Driven by TestBookPage_confirmationIsFinal, which +// renders the real template and passes the extracted script. +// +// Usage: node book_final_state.js +// scenario "submit": book a slot through the form, then try again. +// scenario "paid": land on ?paid=1 (return from Stripe Checkout), then try to book. +// With a post-booking redirect rendered into the page (#268): +// "redirect": book through the form; the page navigates to the URL + booking_id. +// "redirect-paid": the Stripe return; booking_id comes from the return URL. +// "redirect-refused": the page was rendered with a URL the browser-side check refuses +// (http://); it must stay on its own confirmation. +// "redirect-assistant": booked in the assistant chat, whose script announces it with a +// calnode:assistant-booked event; the page ends the same way. +'use strict'; +const fs = require('fs'); +const vm = require('vm'); +const assert = require('assert'); + +const [pagePath, logicPath, scenario] = process.argv.slice(2); +const pageJS = fs.readFileSync(pagePath, 'utf8'); +const BookingLogic = require(logicPath); + +// ── Fake DOM: just enough surface for the page script ────────────────────────── +const HIDDEN_AT_LOAD = new Set(['slots-view', 'form-view', 'confirm-view', 'notice-hint', 'continue-link']); + +function makeEl(id) { + const listeners = {}; + const classes = new Set(HIDDEN_AT_LOAD.has(id) ? ['hidden'] : []); + const el = { + id, dataset: {}, style: {}, value: '', disabled: false, textContent: '', innerHTML: '', + href: '', options: [], selectedIndex: 0, offsetWidth: 0, scrollHeight: 0, clientHeight: 0, + classList: { + add: (...c) => c.forEach(x => classes.add(x)), + remove: (...c) => c.forEach(x => classes.delete(x)), + toggle: (c, force) => { + const on = force === undefined ? !classes.has(c) : !!force; + if (on) classes.add(c); else classes.delete(c); + return on; + }, + contains: c => classes.has(c), + }, + addEventListener: (type, fn) => { (listeners[type] = listeners[type] || []).push(fn); }, + appendChild: () => {}, insertAdjacentHTML: () => {}, focus: () => {}, + querySelector: () => null, querySelectorAll: () => [], + // fire runs every listener for type and waits for async ones to settle. + fire: async (type, ev) => { for (const fn of listeners[type] || []) await fn(ev); }, + }; + return el; +} + +const els = {}; +const $ = id => (els[id] = els[id] || makeEl(id)); + +// The booking form: named inputs, as the page reads them (form.name.value etc.). +const form = $('booking-form'); +form.name = { value: '' }; +form.email = { value: '' }; +form.hp_extra = { value: '' }; +form.elements = {}; +form.reset = () => { form.name.value = ''; form.email.value = ''; }; + +const card = makeEl('card'); +const docEl = makeEl('document'); +const document = { + addEventListener: docEl.addEventListener, + getElementById: $, + querySelector: sel => (sel === '.card' ? card : sel.startsWith('#confirm-view') ? makeEl(sel) : null), + querySelectorAll: () => [], + createElement: () => makeEl(''), +}; + +const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(0, 0, 0, 0); +const pad = n => String(n).padStart(2, '0'); +const DS = `${tomorrow.getFullYear()}-${pad(tomorrow.getMonth() + 1)}-${pad(tomorrow.getDate())}`; +const SLOT = new Date(tomorrow.getTime() + 10 * 3600e3).toISOString(); + +// fetch: slots for any GET, and a POST /v1/bookings that the test resolves by hand so it +// can try a second submit while the first is still in flight. +const posts = []; +const pending = []; +const releasePosts = () => pending.splice(0).forEach(r => r()); +async function fetch(url, opts) { + if (opts && opts.method === 'POST') { + posts.push(JSON.parse(opts.body)); + await new Promise(r => pending.push(r)); + return { ok: true, status: 201, json: async () => ({ id: 'b1', hosts: [] }) }; + } + return { + ok: true, status: 200, + json: async () => ({ slots: [{ start: SLOT, end: SLOT, host_ids: [] }], taken: [], hosts: {} }), + }; +} + +const paidReturn = scenario === 'paid' || scenario === 'redirect-paid'; +const search = paidReturn ? '?paid=1&booking_id=b9&session_id=cs_test&lang=pl' : ''; +const assigned = []; +const timers = []; +const window = { + location: { href: 'https://cal.example/book/intro' + search, search, assign: u => assigned.push(u) }, + innerWidth: 1200, + addEventListener: () => {}, + __CALNODE_I18N: {}, +}; + +// Timers are recorded, not run, so the test can check the delay and then fire them. +const setTimeout = (fn, ms) => { timers.push({ fn, ms }); return timers.length; }; +const ctx = vm.createContext({ document, window, fetch, BookingLogic, console, URL, URLSearchParams, setTimeout }); +vm.runInContext(pageJS, ctx); + +const tick = () => new Promise(r => setImmediate(r)); +const visible = id => !$(id).classList.contains('hidden'); +const dayBtn = { dataset: { ds: DS, y: String(tomorrow.getFullYear()), m: String(tomorrow.getMonth()), d: String(tomorrow.getDate()) }, disabled: false }; +const clickDay = () => $('cal').fire('click', { target: { closest: () => dayBtn } }); +const clickSlot = () => $('slots-list').fire('click', { target: { closest: s => (s === '.slot-btn' ? { dataset: { i: '0' }, disabled: false } : null) } }); +const submit = () => $('booking-form').fire('submit', { preventDefault() {}, target: form }); + +// Every way back into a booking must now be inert. +async function assertFinal(label) { + assert.ok(visible('confirm-view'), `${label}: the confirmation should be showing`); + assert.ok(card.classList.contains('is-final'), `${label}: the card should be marked final`); + // On a narrow viewport only one step shows; the confirmation is in the right pane. + assert.ok(card.classList.contains('m-right') && !card.classList.contains('m-cal'), + `${label}: the mobile step must be the right pane, where the confirmation is`); + assert.ok($('submit-btn').disabled, `${label}: the submit button must stay disabled`); + assert.ok($('tz-select').disabled && $('prev-btn').disabled && $('next-btn').disabled, + `${label}: timezone and month navigation must be disabled`); + + await clickDay(); await tick(); + assert.ok(!visible('slots-view'), `${label}: a calendar click must not reopen the slots`); + assert.ok(visible('confirm-view'), `${label}: a calendar click must not leave the confirmation`); + await clickSlot(); await tick(); + assert.ok(!visible('form-view'), `${label}: a slot click must not reopen the form`); + + const before = posts.length; + form.name.value = 'Someone Else'; form.email.value = 'other@example.com'; + const again = submit(); await tick(); releasePosts(); await again; await tick(); + assert.equal(posts.length, before, `${label}: a second submit after confirmation must send nothing`); + + if (scenario.startsWith('redirect')) return; + const href = $('book-another').href; + assert.ok(href.startsWith('/book/intro'), `${label}: "Book another time" should reload the page, got ${href}`); + assert.ok(!/paid|session_id/.test(href), `${label}: "Book another time" must drop the Stripe return params, got ${href}`); +} + +async function bookThroughForm() { + await clickDay(); await tick(); + await clickSlot(); await tick(); + form.name.value = 'Ana'; form.email.value = 'ana@example.com'; + const p = submit(); await tick(); releasePosts(); await p; await tick(); +} + +// After the delay the page navigates to want (or nowhere when want is ''). +function assertRedirect(want) { + const navs = timers.filter(x => x.ms >= 1000); + if (!want) { + assert.equal(navs.length, 0, 'no navigation may be scheduled'); + assert.ok($('continue-link').classList.contains('hidden'), 'Continue must stay hidden without a redirect'); + assert.ok(!$('book-another').classList.contains('hidden'), '"Book another time" stays without a redirect'); + return; + } + assert.equal($('continue-link').href, want, 'Continue should point at the redirect'); + assert.ok(!$('continue-link').classList.contains('hidden'), 'Continue should be shown'); + assert.ok($('book-another').classList.contains('hidden'), '"Book another time" is hidden while leaving'); + assert.equal(navs.length, 1, 'exactly one navigation should be scheduled'); + assert.equal(assigned.length, 0, 'navigation waits for the delay'); + navs[0].fn(); + assert.deepEqual(assigned, [want]); +} + +(async () => { + await tick(); + if (scenario === 'redirect') { + await bookThroughForm(); + await assertFinal('redirect'); + assertRedirect('https://thanks.example/done?src=cal&booking_id=b1'); + } else if (scenario === 'redirect-paid') { + await assertFinal('redirect paid return'); + assertRedirect('https://thanks.example/done?src=cal&booking_id=b9'); + } else if (scenario === 'redirect-assistant') { + await docEl.fire('calnode:assistant-booked', { detail: { id: 'b7', start_at: SLOT } }); await tick(); + assert.ok($('confirm-time').textContent.includes('·'), 'the confirmation should show the booked time'); + await assertFinal('assistant booking'); + assertRedirect('https://thanks.example/done?src=cal&booking_id=b7'); + } else if (scenario === 'redirect-refused') { + await bookThroughForm(); + await assertFinal('refused redirect'); + assertRedirect(''); + } else if (scenario === 'paid') { + await assertFinal('paid return'); + assert.equal(posts.length, 0); + assert.ok($('book-another').href.includes('lang=pl'), 'other query params (lang) should survive'); + } else { + await clickDay(); await tick(); + assert.ok(visible('slots-view'), 'setup: picking a day should show its slots'); + await clickSlot(); await tick(); + assert.ok(visible('form-view'), 'setup: picking a slot should show the form'); + + form.name.value = 'Ana'; form.email.value = 'ana@example.com'; + const first = submit(); + await tick(); + // Double click / Enter while the first request is in flight. Not awaited: on a page + // without the guard it would be a second request, held open like the first. + const second = submit(); await tick(); + assert.equal(posts.length, 1, 'a second submit while the first is in flight must send nothing'); + + releasePosts(); + await first; await second; await tick(); + assert.equal(posts.length, 1); + assert.equal(form.name.value, '', 'the form should be reset once the booking is confirmed'); + await assertFinal('after booking'); + } + console.log('ok'); +})().catch(err => { console.error(err.message); process.exit(1); }); diff --git a/internal/i18n/locales/de-x-neutral.json b/internal/i18n/locales/de-x-neutral.json index f76f8d0c..87bf61cb 100644 --- a/internal/i18n/locales/de-x-neutral.json +++ b/internal/i18n/locales/de-x-neutral.json @@ -21,6 +21,8 @@ "confirming": "Wird bestätigt…", "booking_confirmed": "Buchung bestätigt", "confirmation_email_sent": "Eine Bestätigungs-E-Mail wurde gesendet.", + "book_another_time": "Weiteren Termin buchen", + "continue": "Weiter", "required_fields_error": "Bitte alle Pflichtfelder ausfüllen.", "slot_taken_error": "Dieser Termin wurde gerade vergeben. Bitte einen anderen wählen.", "booking_failed_error": "Die Buchung ist fehlgeschlagen. Bitte erneut versuchen.", diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index 7ec028f5..4fef0f0c 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -21,6 +21,8 @@ "confirming": "Wird bestätigt…", "booking_confirmed": "Buchung bestätigt", "confirmation_email_sent": "Wir haben Ihnen eine Bestätigungs-E-Mail gesendet.", + "book_another_time": "Weiteren Termin buchen", + "continue": "Weiter", "required_fields_error": "Bitte füllen Sie alle Pflichtfelder aus.", "slot_taken_error": "Dieser Termin wurde gerade vergeben. Bitte wählen Sie einen anderen.", "booking_failed_error": "Die Buchung ist fehlgeschlagen. Bitte versuchen Sie es erneut.", diff --git a/internal/i18n/locales/el.json b/internal/i18n/locales/el.json index 997b1ed5..d6291317 100644 --- a/internal/i18n/locales/el.json +++ b/internal/i18n/locales/el.json @@ -21,6 +21,8 @@ "confirming": "Γίνεται επιβεβαίωση", "booking_confirmed": "Η κράτηση επιβεβαιώθηκε", "confirmation_email_sent": "Σας έχει αποσταλεί email επιβεβαίωσης.", + "book_another_time": "Κράτηση άλλης ώρας", + "continue": "Συνέχεια", "required_fields_error": "Παρακαλούμε συμπληρώστε όλα τα υποχρεωτικά πεδία.", "slot_taken_error": "Αυτή η ώρα έχει επιλεγεί από κάποιον άλλον. Παρακαλούμε επιλέξτε μια διαφορετική ώρα.", "booking_failed_error": "Η κράτηση απέτυχε. Παρακαλούμε προσπαθήστε ξανά.", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 4504be37..123171d5 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -21,6 +21,8 @@ "confirming": "Confirming…", "booking_confirmed": "Booking confirmed", "confirmation_email_sent": "A confirmation email has been sent to you.", + "book_another_time": "Book another time", + "continue": "Continue", "required_fields_error": "Please fill in all required fields.", "slot_taken_error": "That slot was just taken. Please choose another time.", "booking_failed_error": "Booking failed. Please try again.", diff --git a/internal/i18n/locales/es.json b/internal/i18n/locales/es.json index 641c3496..63cae8fe 100644 --- a/internal/i18n/locales/es.json +++ b/internal/i18n/locales/es.json @@ -21,6 +21,8 @@ "confirming": "Confirmando…", "booking_confirmed": "Reserva confirmada", "confirmation_email_sent": "Te hemos enviado un correo de confirmación.", + "book_another_time": "Reservar otra hora", + "continue": "Continuar", "required_fields_error": "Completa todos los campos obligatorios.", "slot_taken_error": "Ese horario acaba de ser reservado. Elige otro horario.", "booking_failed_error": "No se pudo completar la reserva. Inténtalo de nuevo.", diff --git a/internal/i18n/locales/fr-CA.json b/internal/i18n/locales/fr-CA.json index d7480085..0201371f 100644 --- a/internal/i18n/locales/fr-CA.json +++ b/internal/i18n/locales/fr-CA.json @@ -21,6 +21,8 @@ "confirming": "Confirmation…", "booking_confirmed": "Réservation confirmée", "confirmation_email_sent": "Un courriel de confirmation vous a été envoyé.", + "book_another_time": "Réserver un autre créneau", + "continue": "Continuer", "required_fields_error": "Veuillez remplir tous les champs obligatoires.", "slot_taken_error": "Ce créneau vient d'être réservé. Veuillez en choisir un autre.", "booking_failed_error": "La réservation a échoué. Veuillez réessayer.", diff --git a/internal/i18n/locales/fr.json b/internal/i18n/locales/fr.json index 7b555505..6b4ecc24 100644 --- a/internal/i18n/locales/fr.json +++ b/internal/i18n/locales/fr.json @@ -21,6 +21,8 @@ "confirming": "Confirmation…", "booking_confirmed": "Réservation confirmée", "confirmation_email_sent": "Un e-mail de confirmation vous a été envoyé.", + "book_another_time": "Réserver un autre créneau", + "continue": "Continuer", "required_fields_error": "Veuillez remplir tous les champs obligatoires.", "slot_taken_error": "Ce créneau vient d'être réservé. Veuillez en choisir un autre.", "booking_failed_error": "La réservation a échoué. Veuillez réessayer.", diff --git a/internal/i18n/locales/it.json b/internal/i18n/locales/it.json index 61b5753c..5c85815b 100644 --- a/internal/i18n/locales/it.json +++ b/internal/i18n/locales/it.json @@ -21,6 +21,8 @@ "confirming": "Conferma in corso…", "booking_confirmed": "Prenotazione confermata", "confirmation_email_sent": "Le abbiamo inviato un'email di conferma.", + "book_another_time": "Prenota un altro orario", + "continue": "Continua", "required_fields_error": "Compila tutti i campi obbligatori.", "slot_taken_error": "Questo orario è appena stato prenotato. Ne scelga un altro.", "booking_failed_error": "Prenotazione non riuscita. Riprovi.", diff --git a/internal/i18n/locales/nl.json b/internal/i18n/locales/nl.json index 07b9a48a..cc73a5f9 100644 --- a/internal/i18n/locales/nl.json +++ b/internal/i18n/locales/nl.json @@ -21,6 +21,8 @@ "confirming": "Bevestigen…", "booking_confirmed": "Boeking bevestigd", "confirmation_email_sent": "We hebben je een bevestigingsmail gestuurd.", + "book_another_time": "Nog een tijd boeken", + "continue": "Doorgaan", "required_fields_error": "Vul alle verplichte velden in.", "slot_taken_error": "Deze tijd is net geboekt. Kies een andere.", "booking_failed_error": "Boeken is mislukt. Probeer het opnieuw.", diff --git a/internal/i18n/locales/pl.json b/internal/i18n/locales/pl.json index a9830169..73aa0c3d 100644 --- a/internal/i18n/locales/pl.json +++ b/internal/i18n/locales/pl.json @@ -21,6 +21,8 @@ "confirming": "Potwierdzanie…", "booking_confirmed": "Rezerwacja potwierdzona", "confirmation_email_sent": "E-mail z potwierdzeniem został wysłany.", + "book_another_time": "Umów kolejny termin", + "continue": "Dalej", "required_fields_error": "Wypełnij wszystkie wymagane pola.", "slot_taken_error": "Ten termin właśnie został zajęty. Wybierz inną godzinę.", "booking_failed_error": "Rezerwacja nie powiodła się. Spróbuj ponownie.", diff --git a/internal/i18n/locales/pt.json b/internal/i18n/locales/pt.json index a02652a8..3053cd41 100644 --- a/internal/i18n/locales/pt.json +++ b/internal/i18n/locales/pt.json @@ -21,6 +21,8 @@ "confirming": "A confirmar…", "booking_confirmed": "Marcação confirmada", "confirmation_email_sent": "Enviámos-lhe um e-mail de confirmação.", + "book_another_time": "Reservar outro horário", + "continue": "Continuar", "required_fields_error": "Preencha todos os campos obrigatórios.", "slot_taken_error": "Este horário acabou de ser ocupado. Escolha outro.", "booking_failed_error": "A marcação falhou. Tente novamente.", diff --git a/internal/i18n/locales/sv.json b/internal/i18n/locales/sv.json index 38b898a4..ee89c7a7 100644 --- a/internal/i18n/locales/sv.json +++ b/internal/i18n/locales/sv.json @@ -21,6 +21,8 @@ "confirming": "Bekräftar…", "booking_confirmed": "Bokningen är bekräftad", "confirmation_email_sent": "Vi har skickat ett bekräftelsemejl till dig.", + "book_another_time": "Boka en annan tid", + "continue": "Fortsätt", "required_fields_error": "Fyll i alla obligatoriska fält.", "slot_taken_error": "Den här tiden blev precis bokad. Välj en annan.", "booking_failed_error": "Bokningen misslyckades. Försök igen.",