From ad5a1355f00e2048e10ad21968822ae0cd6c97c5 Mon Sep 17 00:00:00 2001
From: Dominik Myszkowski
Date: Mon, 30 Nov 2026 12:56:54 +0100
Subject: [PATCH 1/6] fix(booking): a confirmed booking is a final state on all
three surfaces (#268)
book.html left its calendar clickable after confirming and re-enabled the
submit button, inviting a second booking under a different email, which
max_active_bookings cannot catch.
- book.html: finalize() on success and on the Stripe return disables the
calendar, month navigation, timezone and submit and resets the form; every
handler checks the flag. A submitting flag drops a second submit while the
first is in flight. "Book another time" is a fresh load without the Stripe
return parameters.
- embed.js: the calendar renders disabled in the confirm view and a second
submit is refused. "Book another time" resets the widget's own state and
reloads the month; it never navigates the host page.
- manage.html: the rescheduled and cancelled views are final; showView no
longer leaves them and neither action can be sent again.
New booker key book_another_time in every locale. TestBookPage_confirmationIsFinal
runs book.html's real page script under node against a small fake DOM and
checks that a second submit sends nothing; the widget and manage page are
pinned at source level.
---
CHANGELOG.md | 8 +
docs/ARCHITECTURE.md | 2 +
internal/handler/booking_final_state_test.go | 128 ++++++++++++++
internal/handler/embed.js | 26 ++-
internal/handler/templates/book.html | 83 +++++++---
internal/handler/templates/booking.css | 13 ++
internal/handler/templates/manage.html | 19 ++-
internal/handler/testdata/book_final_state.js | 156 ++++++++++++++++++
internal/i18n/locales/de-x-neutral.json | 1 +
internal/i18n/locales/de.json | 1 +
internal/i18n/locales/el.json | 1 +
internal/i18n/locales/en.json | 1 +
internal/i18n/locales/es.json | 1 +
internal/i18n/locales/fr-CA.json | 1 +
internal/i18n/locales/fr.json | 1 +
internal/i18n/locales/it.json | 1 +
internal/i18n/locales/nl.json | 1 +
internal/i18n/locales/pl.json | 1 +
internal/i18n/locales/pt.json | 1 +
internal/i18n/locales/sv.json | 1 +
20 files changed, 421 insertions(+), 26 deletions(-)
create mode 100644 internal/handler/booking_final_state_test.go
create mode 100644 internal/handler/testdata/book_final_state.js
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1149229b..b6b81e11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -61,6 +61,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 599c7672..bff405a7 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -413,6 +413,8 @@ 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.
+
`internal/booking/service.go` (transactions) + `internal/handler/booking_handler.go`
(HTTP + async side effects).
diff --git a/internal/handler/booking_final_state_test.go b/internal/handler/booking_final_state_test.go
new file mode 100644
index 00000000..3ad16142
--- /dev/null
+++ b/internal/handler/booking_final_state_test.go
@@ -0,0 +1,128 @@
+package handler
+
+import (
+ "bytes"
+ "html/template"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "regexp"
+ "strings"
+ "testing"
+
+ "github.com/calnode/calnode/internal/i18n"
+)
+
+// bookPageScript renders book.html and returns its main page script: the inline
+// `).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()
+ page := filepath.Join(dir, "page.js")
+ logic := filepath.Join(dir, "booking-logic.js")
+ if err := os.WriteFile(page, []byte(bookPageScript(t)), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ 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)
+ }
+ for _, scenario := range []string{"submit", "paid"} {
+ t.Run(scenario, func(t *testing.T) {
+ out, err := exec.Command(node, harness, page, logic, 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 a9fa9285..28503c9b 100644
--- a/internal/handler/embed.js
+++ b/internal/handler/embed.js
@@ -464,6 +464,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: '' }));
@@ -473,14 +476,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' }) }),
@@ -656,6 +660,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');
@@ -700,18 +706,32 @@
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(); });
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') }),
+ again,
]),
]);
}
+ bookAnother() {
+ this.state.day = null; this.state.slot = null; 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;
@@ -732,7 +752,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/templates/book.html b/internal/handler/templates/book.html
index dbce7454..c8f19561 100644
--- a/internal/handler/templates/book.html
+++ b/internal/handler/templates/book.html
@@ -260,6 +260,7 @@
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');
@@ -375,6 +382,28 @@
{{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.
+ function finalize() {
+ 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');
+ }
+
// 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 () {
@@ -384,7 +413,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();
// 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') {
@@ -500,10 +529,10 @@
`).join('');
for (let i = 0; i < startOffset; i++) h += '';
@@ -524,7 +553,7 @@
{{call .T "booking_confirmed"}}
if (isSel) cls += ' sel';
if (isToday) cls += ' today';
- if (disabled || !hasSlots) {
+ if (disabled || !hasSlots || finalized) {
h += ``;
} else {
h += ``;
@@ -535,15 +564,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);
@@ -562,7 +594,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);
}
@@ -616,6 +648,7 @@
{{call .T "booking_confirmed"}}
}
async function pickDate(ds, y, m, d) {
+ if (finalized) return;
pickedDate = new Date(y, m, d);
pickedSlot = null;
restoreDefaultHosts();
@@ -650,6 +683,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);
@@ -664,6 +698,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];
@@ -675,13 +710,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');
@@ -722,6 +760,7 @@
}
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;
}
});
@@ -846,6 +888,7 @@
{{call .T "booking_confirmed"}}
}
$('tz-select').addEventListener('change', async e => {
+ if (finalized) return;
TZ = e.target.value;
resizeTzSelect();
await loadMonthAvailability(navYear, navMonth); // rebuild the day cache for the new tz
diff --git a/internal/handler/templates/booking.css b/internal/handler/templates/booking.css
index c0ded652..ad9f6501 100644
--- a/internal/handler/templates/booking.css
+++ b/internal/handler/templates/booking.css
@@ -302,6 +302,19 @@ 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; }
/* Avatar */
.avatar-img {
diff --git a/internal/handler/templates/manage.html b/internal/handler/templates/manage.html
index 351d8513..3165db38 100644
--- a/internal/handler/templates/manage.html
+++ b/internal/handler/templates/manage.html
@@ -311,8 +311,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');
@@ -547,6 +558,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) {
@@ -567,7 +579,7 @@
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..c4e3a3e7
--- /dev/null
+++ b/internal/handler/testdata/book_final_state.js
@@ -0,0 +1,156 @@
+// 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.
+'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']);
+
+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 document = {
+ 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 search = scenario === 'paid' ? '?paid=1&session_id=cs_test&lang=pl' : '';
+const window = {
+ location: { href: 'https://cal.example/book/intro' + search, search },
+ innerWidth: 1200,
+ addEventListener: () => {},
+ __CALNODE_I18N: {},
+};
+
+const ctx = vm.createContext({ document, window, fetch, BookingLogic, console, URL, URLSearchParams });
+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`);
+ 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`);
+
+ 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 () => {
+ await tick();
+ 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 42941bee..0591634a 100644
--- a/internal/i18n/locales/de-x-neutral.json
+++ b/internal/i18n/locales/de-x-neutral.json
@@ -20,6 +20,7 @@
"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",
"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 c41e28dd..d4b481a1 100644
--- a/internal/i18n/locales/de.json
+++ b/internal/i18n/locales/de.json
@@ -20,6 +20,7 @@
"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",
"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 e81cfc1f..3677c6d1 100644
--- a/internal/i18n/locales/el.json
+++ b/internal/i18n/locales/el.json
@@ -20,6 +20,7 @@
"confirming": "Γίνεται επιβεβαίωση",
"booking_confirmed": "Η κράτηση επιβεβαιώθηκε",
"confirmation_email_sent": "Σας έχει αποσταλεί email επιβεβαίωσης.",
+ "book_another_time": "Κράτηση άλλης ώρας",
"required_fields_error": "Παρακαλούμε συμπληρώστε όλα τα υποχρεωτικά πεδία.",
"slot_taken_error": "Αυτή η ώρα έχει επιλεγεί από κάποιον άλλον. Παρακαλούμε επιλέξτε μια διαφορετική ώρα.",
"booking_failed_error": "Η κράτηση απέτυχε. Παρακαλούμε προσπαθήστε ξανά.",
diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json
index b268bdec..589d440e 100644
--- a/internal/i18n/locales/en.json
+++ b/internal/i18n/locales/en.json
@@ -20,6 +20,7 @@
"confirming": "Confirming…",
"booking_confirmed": "Booking confirmed",
"confirmation_email_sent": "A confirmation email has been sent to you.",
+ "book_another_time": "Book another time",
"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 896b898f..3a48fb9a 100644
--- a/internal/i18n/locales/es.json
+++ b/internal/i18n/locales/es.json
@@ -20,6 +20,7 @@
"confirming": "Confirmando…",
"booking_confirmed": "Reserva confirmada",
"confirmation_email_sent": "Te hemos enviado un correo de confirmación.",
+ "book_another_time": "Reservar otra hora",
"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 41143791..b917eb87 100644
--- a/internal/i18n/locales/fr-CA.json
+++ b/internal/i18n/locales/fr-CA.json
@@ -20,6 +20,7 @@
"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",
"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 7d79319d..7b18074c 100644
--- a/internal/i18n/locales/fr.json
+++ b/internal/i18n/locales/fr.json
@@ -20,6 +20,7 @@
"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",
"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 afeddd0c..f63073d7 100644
--- a/internal/i18n/locales/it.json
+++ b/internal/i18n/locales/it.json
@@ -20,6 +20,7 @@
"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",
"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 b3e730c3..2fce673d 100644
--- a/internal/i18n/locales/nl.json
+++ b/internal/i18n/locales/nl.json
@@ -20,6 +20,7 @@
"confirming": "Bevestigen…",
"booking_confirmed": "Boeking bevestigd",
"confirmation_email_sent": "We hebben je een bevestigingsmail gestuurd.",
+ "book_another_time": "Nog een tijd boeken",
"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 d7e95fcc..4dd94c14 100644
--- a/internal/i18n/locales/pl.json
+++ b/internal/i18n/locales/pl.json
@@ -20,6 +20,7 @@
"confirming": "Potwierdzanie…",
"booking_confirmed": "Rezerwacja potwierdzona",
"confirmation_email_sent": "E-mail z potwierdzeniem został wysłany.",
+ "book_another_time": "Umów kolejny termin",
"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 dc860ede..2b091409 100644
--- a/internal/i18n/locales/pt.json
+++ b/internal/i18n/locales/pt.json
@@ -20,6 +20,7 @@
"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",
"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 c2927d67..8f225b77 100644
--- a/internal/i18n/locales/sv.json
+++ b/internal/i18n/locales/sv.json
@@ -20,6 +20,7 @@
"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",
"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.",
From 0b24ebf4525c1853378e903d5939f29466d2e398 Mon Sep 17 00:00:00 2001
From: Dominik Myszkowski
Date: Tue, 1 Dec 2026 09:58:49 +0100
Subject: [PATCH 2/6] fix(booking): open a final page on the confirmation step
on mobile
On the return from Stripe Checkout finalize() shows the confirmation,
but the step-flow init then set the calendar step, which on a narrow
viewport hides the right pane: a disabled calendar and no confirmation.
The init now opens a final page on the right pane.
---
internal/handler/templates/book.html | 4 +++-
internal/handler/testdata/book_final_state.js | 3 +++
2 files changed, 6 insertions(+), 1 deletion(-)
diff --git a/internal/handler/templates/book.html b/internal/handler/templates/book.html
index c8f19561..2b735a13 100644
--- a/internal/handler/templates/book.html
+++ b/internal/handler/templates/book.html
@@ -439,7 +439,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);
diff --git a/internal/handler/testdata/book_final_state.js b/internal/handler/testdata/book_final_state.js
index c4e3a3e7..1e374d7a 100644
--- a/internal/handler/testdata/book_final_state.js
+++ b/internal/handler/testdata/book_final_state.js
@@ -106,6 +106,9 @@ const submit = () => $('booking-form').fire('submit', { preventDefault() {}, tar
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`);
From d8ddb83320524218c5d5f9c02eb21937385e1a5a Mon Sep 17 00:00:00 2001
From: Dominik Myszkowski
Date: Mon, 30 Nov 2026 15:22:08 +0100
Subject: [PATCH 3/6] feat(booking): optional redirect after a confirmed
booking (#268)
event_types.redirect_url and redirect_with_booking_id (migration 00077):
where the booker goes once a booking is confirmed, typically the operator's
thank-you page, optionally with ?booking_id= appended (off by default; the
booking id is a lookup key).
The value is an open-redirect surface, so it is checked three times:
validRedirectURL on save (absolute https, a host, no credentials, no
whitespace or control characters, <= 2000 chars), servedRedirectURL when a
page or the widget is given it (an invalid stored value is served as none
and logged), and BookingLogic.redirectTarget in the browser before use,
mirrored in embed.js.
- book.html: finalize() shows "Continue" and navigates after 1.5 s, leaving
time for the conversion push. Covers the Stripe return too: the success
URL now carries booking_id.
- embed.js: never navigates the host page; "Continue" opens the redirect in
a new tab (noopener).
- manage.html: no redirect; a reschedule or cancel is not a conversion.
- Admin: URL field and booking-id checkbox in the General tab (en/fr).
- New booker key "continue" in every locale.
Builds on the final confirmation state from the previous commit (#284).
---
CHANGELOG.md | 7 +
docs/ARCHITECTURE.md | 2 +
frontend/src/lib/api.ts | 6 +
frontend/src/lib/i18n/en.json | 3 +
frontend/src/lib/i18n/fr.json | 3 +
.../routes/event-types/[slug]/+page.svelte | 16 +
.../00077_event_type_redirect_url.sql | 19 ++
internal/handler/assets/booking-logic.js | 16 +
internal/handler/assets/booking-logic.test.js | 12 +
internal/handler/book.go | 101 ++++---
internal/handler/booking_final_state_test.go | 42 ++-
internal/handler/embed.js | 26 +-
internal/handler/event_type.go | 56 +++-
internal/handler/event_type_duplicate.go | 6 +-
internal/handler/event_type_duplicate_test.go | 1 +
internal/handler/redirect_url.go | 62 ++++
.../handler/redirect_url_internal_test.go | 275 ++++++++++++++++++
internal/handler/stripe_booking.go | 6 +-
internal/handler/templates/book.html | 26 +-
internal/handler/templates/booking.css | 4 +
internal/handler/testdata/book_final_state.js | 57 +++-
internal/i18n/locales/de-x-neutral.json | 1 +
internal/i18n/locales/de.json | 1 +
internal/i18n/locales/el.json | 1 +
internal/i18n/locales/en.json | 1 +
internal/i18n/locales/es.json | 1 +
internal/i18n/locales/fr-CA.json | 1 +
internal/i18n/locales/fr.json | 1 +
internal/i18n/locales/it.json | 1 +
internal/i18n/locales/nl.json | 1 +
internal/i18n/locales/pl.json | 1 +
internal/i18n/locales/pt.json | 1 +
internal/i18n/locales/sv.json | 1 +
33 files changed, 685 insertions(+), 73 deletions(-)
create mode 100644 internal/db/migrations/00077_event_type_redirect_url.sql
create mode 100644 internal/handler/redirect_url.go
create mode 100644 internal/handler/redirect_url_internal_test.go
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b6b81e11..57bcacfb 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
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index bff405a7..6e8ef3db 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -415,6 +415,8 @@ The `phone_outbound` location type ("we'll call you") is the outbound counterpar
A confirmed booking is a **final state** on all three booking surfaces (#268). A page that kept its calendar live and re-enabled its submit button after confirming invited a second booking under a different email, which `max_active_bookings` cannot catch. On `book.html`, `finalize()` (on success, and on the return from Stripe Checkout) disables the calendar, month navigation, timezone and submit, resets the form, and every handler checks the `finalized` flag rather than relying on the markup alone; a `submitting` flag also drops a second submit while the first request is in flight. "Book another time" is a fresh load of the page without the Stripe return parameters, so no picked day, slot or host state survives. The embed widget renders its calendar disabled while `state.view === 'confirm'` and refuses a second submit; its "Book another time" resets the widget's own state and reloads the month, never navigating the host page. On `manage.html` the success views (rescheduled, cancelled) are final: `showView` no longer leaves them and neither action can be sent again, because the page's times describe the booking as it was; a reload shows it as it now is. `TestBookPage_confirmationIsFinal` runs book.html's real page script under node against a small fake DOM (`testdata/book_final_state.js`) to check that a second submit sends nothing; the widget and manage page are pinned at source level.
+An event type can set a **post-booking redirect** (`redirect_url`, `redirect_with_booking_id`, migration 00077, #268), typically the operator's own thank-you page, where site analytics count the conversion. Although admin-configured, it is an open-redirect surface, so it is checked three times: `validRedirectURL` when the event type is saved (absolute https, a host, no credentials: `https://trusted.example@evil.example/` reads as one site and goes to another; no whitespace or control characters; at most 2000 characters), `servedRedirectURL` when a page or the widget is given it (a stored value that no longer passes is served as no redirect and logged), and `redirectTarget` in the browser right before use (`booking-logic.js`, mirrored in `embed.js`). `redirect_with_booking_id` appends `?booking_id=`; it is off by default because the booking id is a lookup key (`GET /v1/bookings/{id}` is public). On `book.html`, `finalize()` shows a "Continue" button and navigates after a short delay (`REDIRECT_DELAY_MS`), which leaves time for the dataLayer/GA4 conversion pushed right after it; this covers the return from Stripe Checkout too, whose success URL carries `booking_id` for that purpose. The **embed widget never navigates the host page**: its confirmation offers "Continue", which opens the redirect in a new tab (`noopener`). The manage page does not redirect: a reschedule or a cancellation is not a conversion.
+
`internal/booking/service.go` (transactions) + `internal/handler/booking_handler.go`
(HTTP + async side effects).
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index cd6c8723..a7a1e80a 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;
/** Who sends the booker's calendar invite. 'calendar': each host's connected calendar,
* from the host's own address. 'calnode': Calnode's own invite, from the email sender
* in Settings → Email, so no host's personal address reaches the booker. 'none': no
diff --git a/frontend/src/lib/i18n/en.json b/frontend/src/lib/i18n/en.json
index 1a3870ce..baf41e95 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=…)",
"allowPhoneCall": "Let invitees choose a phone call by entering their number"
},
"location": {
diff --git a/frontend/src/lib/i18n/fr.json b/frontend/src/lib/i18n/fr.json
index b9af9802..8b620cd9 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=…)",
"allowPhoneCall": "Permettre aux invités de choisir un appel téléphonique en saisissant leur numéro"
},
"location": {
diff --git a/frontend/src/routes/event-types/[slug]/+page.svelte b/frontend/src/routes/event-types/[slug]/+page.svelte
index 84e6f5d4..fe2b78a2 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,
+ 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,
invite_delivery: et.invite_delivery ?? 'calendar',
location_type: et.location_type,
location_value: et.location_value ?? '',
@@ -397,6 +400,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,
invite_delivery: form.invite_delivery,
allow_phone_call: allowPhoneCall,
location_type: form.location_type,
@@ -705,6 +711,16 @@
+
+
+
+
{$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 c2221521..ab85fc41 100644
--- a/internal/handler/assets/booking-logic.js
+++ b/internal/handler/assets/booking-logic.js
@@ -138,7 +138,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 39fadc62..79aa54ec 100644
--- a/internal/handler/assets/booking-logic.test.js
+++ b/internal/handler/assets/booking-logic.test.js
@@ -106,3 +106,15 @@ test('fmt leaves a string with no verbs untouched', () => {
assert.equal(B.fmt('No available times.', ['unused']), 'No available times.');
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));
+ }
+});
diff --git a/internal/handler/book.go b/internal/handler/book.go
index 7bddd295..56e35ba4 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
@@ -353,16 +358,20 @@ func (h *Handler) PublicEventType(w http.ResponseWriter, r *http.Request) {
msgGreeting sql.NullString
allowPhoneCall 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.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent,
+ 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)
+ slug).Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor,
+ &redirectRaw, &redirectWithID)
if errors.Is(err, sql.ErrNoRows) {
h.writeError(w, http.StatusNotFound, "event type not found")
return
@@ -373,6 +382,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 {
@@ -442,12 +452,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),
})
}
@@ -472,16 +486,20 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) {
msgGreeting sql.NullString
allowPhoneCall 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.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent,
+ 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)
+ slug).Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor,
+ &redirectRaw, &redirectWithID)
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, "Page not found", http.StatusNotFound)
@@ -543,37 +561,40 @@ 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