From ad5a1355f00e2048e10ad21968822ae0cd6c97c5 Mon Sep 17 00:00:00 2001 From: Dominik Myszkowski Date: Mon, 30 Nov 2026 12:56:54 +0100 Subject: [PATCH 1/2] 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 @@

{{.Name}}

{{call .T "booking_confirmed"}}

{{call .T "confirmation_email_sent"}}

+ {{call .T "book_another_time"}} @@ -302,6 +303,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'); @@ -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 @@

{{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 += '
'; @@ -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 @@

{{call .T "booking_confirmed"}}

} btn.disabled = true; btn.textContent = t('confirming'); errEl.textContent = ''; + submitting = true; try { const r = await fetch('/v1/bookings', { @@ -771,7 +810,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(); + renderCal(); if (window.__CALNODE_DL && typeof calnodePush === 'function') { var dlAnswers = {}; @@ -788,9 +832,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, @@ -800,17 +844,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; } }); @@ -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 @@

{{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 { @@ -585,7 +597,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}}, @@ -605,6 +617,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 { @@ -621,7 +634,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..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/2] 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`);