From 6a16da85734dc2c30ee7e1ae223eb5212a31d74c Mon Sep 17 00:00:00 2001 From: KishenG <42324009+KishenG@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:53:59 +0000 Subject: [PATCH 1/3] feat(booking): optional next available time above the slot picker (#254) A per-event-type setting, off by default, adds a button above the time list that opens the soonest free day. Worked out from the free slots only, bounded by max_future_days, and silent on a failed or degraded check. Shown on the booking and reschedule pages; the embed widget is left for a follow-up. --- CHANGELOG.md | 7 + docs/ARCHITECTURE.md | 23 +++ frontend/src/lib/api.ts | 3 + frontend/src/lib/i18n/en.json | 2 + frontend/src/lib/i18n/fr.json | 2 + .../routes/event-types/[slug]/+page.svelte | 12 +- .../00073_event_type_show_next_available.sql | 12 ++ internal/handler/assets/booking-logic.js | 28 ++++ internal/handler/assets/booking-logic.test.js | 53 +++++++ internal/handler/book.go | 7 +- internal/handler/event_type.go | 29 +++- internal/handler/event_type_duplicate.go | 4 +- internal/handler/event_type_duplicate_test.go | 10 +- internal/handler/manage_handler.go | 7 +- internal/handler/next_available_test.go | 136 ++++++++++++++++++ internal/handler/templates/book.html | 50 +++++++ internal/handler/templates/booking.css | 19 +++ internal/handler/templates/manage.html | 49 +++++++ internal/i18n/locales/en.json | 1 + 19 files changed, 438 insertions(+), 16 deletions(-) create mode 100644 internal/db/migrations/00073_event_type_show_next_available.sql create mode 100644 internal/handler/next_available_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 6eec3898..4298f1a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,13 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad The variant is never offered in the language switcher or matched from `Accept-Language`; select it with `?lang=de-x-neutral` or ``. +- **Next available time on the booking page.** A per-event-type setting, off by default, + adds a button above the time list, such as "Next available: Wed, Dec 9, 10:00 AM", that + opens that day. It is worked out from the free times only, walks forward month by month + but never past `max_future_days`, and shows nothing when the availability check failed or + was degraded, rather than implying there is none. It appears on the booking and reschedule + pages. The embed widget does not have it yet. Proposed in discussion #254. + ### Fixed - **Buttons and inputs in the booking UI now use the surrounding font.** Form controls diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0856972d..9cd9657f 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -363,6 +363,29 @@ in discussion #14, issue #19. having something available. Fully booked days *are* still openable, deliberately - a list of struck-through times explains itself better than a dead date. +### Showing the next available time + +`event_types.show_next_available` (migration 00073, **default off**) opts one event type +into a button above the time list that opens the soonest free day. Requested in +discussion #254. + +- **Worked out in the browser from the free list.** `loadNextAvailable` in book.html and + manage.html reads `/slots` month by month from today and stops at the first free + slot. It never reads `taken`, which would advertise a struck-through time, and it never + walks past `maxDate`, so it cannot run beyond `max_future_days`. `monthsToProbe` and + `earliestFreeSlot` live in `assets/booking-logic.js` and are unit tested. +- **Silent when unsure.** A failed request or a `degraded` response shows nothing: a + check that fell over is not the same as "nothing is available". +- **Timezone.** The server already applies the requested timezone to `/slots`, so the + page only formats. Changing the timezone restarts the search. +- **Reschedule.** manage.html leaves out the booking's own current start, so the button + offers the next time the booking could move to. +- **Two copies of the button.** On narrow screens the calendar step hides the right + column, so a second copy sits above the calendar there and `booking.css` shows one + at a time. +- **Not in the embed widget yet.** It does not load `booking-logic.js`, so it would need + its own mirrored copy of the two helpers. + ### Explaining an empty day, and the minimum-notice gap Two silences on the booker-facing surfaces, issue #20. A day with nothing on it used to diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index cd6c8723..6b430ec8 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -39,6 +39,9 @@ export type EventType = { * them. Off by default: the slots endpoint is public, so this makes the host's * booked hours visible to anyone with the link. */ show_taken_slots: boolean; + /** Show the next free time above the booking page's time list, as a button that + * opens that day. Off by default. */ + show_next_available: boolean; /** 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 d14b9130..fdcca633 100644 --- a/frontend/src/lib/i18n/en.json +++ b/frontend/src/lib/i18n/en.json @@ -1631,6 +1631,8 @@ "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.", + "showNextAvailable": "Show the next available time", + "showNextAvailableHint": "Adds a button above the time list, such as \"Next available: Wed, Nov 18, 10:00\", that opens that day. It uses the same times a visitor can already see.", "allowPhoneCall": "Let invitees choose a phone call by entering their number" }, "location": { diff --git a/frontend/src/lib/i18n/fr.json b/frontend/src/lib/i18n/fr.json index 46ca13d0..8a23fc52 100644 --- a/frontend/src/lib/i18n/fr.json +++ b/frontend/src/lib/i18n/fr.json @@ -1631,6 +1631,8 @@ "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.", + "showNextAvailable": "Afficher le prochain horaire disponible", + "showNextAvailableHint": "Ajoute au-dessus de la liste des horaires un bouton, par exemple « Prochain horaire : mer. 18 nov., 10:00 », qui ouvre ce jour. Il utilise les mêmes horaires que ceux déjà visibles par un visiteur.", "allowPhoneCall": "Permettre aux invités de choisir un appel téléphonique en saisissant leur numéro" }, "location": { diff --git a/frontend/src/routes/event-types/[slug]/+page.svelte b/frontend/src/routes/event-types/[slug]/+page.svelte index 6f5c49eb..f35a64f8 100644 --- a/frontend/src/routes/event-types/[slug]/+page.svelte +++ b/frontend/src/routes/event-types/[slug]/+page.svelte @@ -86,7 +86,7 @@ let form = $state({ display_order: 0, name: '', slug: '', description: '', duration_minutes: 30, slot_interval_minutes: 30, - is_active: true, is_public: true, show_taken_slots: false, + is_active: true, is_public: true, show_taken_slots: false, show_next_available: false, invite_delivery: 'calendar' as EventType['invite_delivery'], location_type: 'link', location_value: '', buffer_before_minutes: 0, buffer_after_minutes: 0, @@ -335,6 +335,7 @@ is_active: et.is_active, is_public: et.is_public, show_taken_slots: et.show_taken_slots ?? false, + show_next_available: et.show_next_available ?? false, invite_delivery: et.invite_delivery ?? 'calendar', location_type: et.location_type, location_value: et.location_value ?? '', @@ -396,6 +397,7 @@ is_active: form.is_active, is_public: form.is_public, show_taken_slots: form.show_taken_slots, + show_next_available: form.show_next_available, invite_delivery: form.invite_delivery, allow_phone_call: allowPhoneCall, location_type: form.location_type, @@ -703,6 +705,14 @@

+
+
+ + +
+

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

+
+ {#if isOnlineMeeting(form.location_type)} {/if} diff --git a/internal/db/migrations/00073_event_type_show_next_available.sql b/internal/db/migrations/00073_event_type_show_next_available.sql new file mode 100644 index 00000000..74f22b8b --- /dev/null +++ b/internal/db/migrations/00073_event_type_show_next_available.sql @@ -0,0 +1,12 @@ +-- +goose Up +-- Whether the booking page shows the next available time above the time list, as a +-- button that jumps to that day. Proposed in discussion #254. +-- +-- Default 0, so nothing changes for an existing event type. It follows +-- show_taken_slots (00057) rather than being always on: the line is computed from the +-- same public slots endpoint a visitor can already read, so it discloses nothing new, +-- but a host whose page is meant to be browsed day by day may not want it. +ALTER TABLE event_types ADD COLUMN show_next_available INTEGER NOT NULL DEFAULT 0; + +-- +goose Down +ALTER TABLE event_types DROP COLUMN show_next_available; diff --git a/internal/handler/assets/booking-logic.js b/internal/handler/assets/booking-logic.js index c2221521..ddf372b2 100644 --- a/internal/handler/assets/booking-logic.js +++ b/internal/handler/assets/booking-logic.js @@ -65,6 +65,32 @@ } + // earliestFreeSlot — the soonest bookable slot in `slots` (the FREE list from /slots, never + // the merged free+taken view: that would advertise a struck-through time), with the + // "YYYY-MM-DD" it falls on in the selected tz. `excludeStart` drops one slot (reschedule + // excludes the booking's own time). Null when there is none. Does not re-derive the + // timezone: the server already applied the requested one, and dateKeyFromISO formats in it. + function earliestFreeSlot(slots, tz, excludeStart) { + var best = null; + (slots || []).forEach(function (s) { + if (excludeStart && s.start === excludeStart) return; + if (best === null || Date.parse(s.start) < Date.parse(best.start)) best = s; + }); + return best === null ? null : { slot: best, day: dateKeyFromISO(best.start, tz) }; + } + + // monthsToProbe — the months, oldest first, that a search for the next available day should + // walk: from `now`'s month up to and including `maxDate`'s month, so it can never run past + // the event type's max_future_days. maxDate null means no limit is set, so `capMonths` + // (default 12) bounds the walk instead. + function monthsToProbe(now, maxDate, capMonths) { + var out = []; + var first = now.getFullYear() * 12 + now.getMonth(); + var last = maxDate ? maxDate.getFullYear() * 12 + maxDate.getMonth() : first + (capMonths || 12) - 1; + for (var idx = first; idx <= last; idx++) out.push({ year: Math.floor(idx / 12), month: idx % 12 }); + return out; + } + // formatTime — "1:30 PM" in the selected tz. function formatTime(iso, tz, locale) { return new Intl.DateTimeFormat(locale || [], { @@ -143,6 +169,8 @@ ymd: ymd, groupSlotsByDay: groupSlotsByDay, mergeDaySlots: mergeDaySlots, + earliestFreeSlot: earliestFreeSlot, + monthsToProbe: monthsToProbe, fmt: fmt, formatTime: formatTime, formatDay: formatDay, diff --git a/internal/handler/assets/booking-logic.test.js b/internal/handler/assets/booking-logic.test.js index 39fadc62..322adabd 100644 --- a/internal/handler/assets/booking-logic.test.js +++ b/internal/handler/assets/booking-logic.test.js @@ -106,3 +106,56 @@ 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('earliestFreeSlot picks the soonest slot and the day it falls on in the selected tz', () => { + const slots = [ + { start: '2026-06-16T09:00:00Z' }, + { start: '2026-06-15T02:00:00Z' }, // NY → 06-14 22:00 + { start: '2026-06-15T20:00:00Z' } + ]; + const ny = B.earliestFreeSlot(slots, 'America/New_York'); + assert.equal(ny.slot.start, '2026-06-15T02:00:00Z'); + assert.equal(ny.day, '2026-06-14'); // the day key follows the selected tz, not UTC + assert.equal(B.earliestFreeSlot(slots, 'UTC').day, '2026-06-15'); +}); + +test('earliestFreeSlot orders by instant, not by string, across offsets', () => { + // As strings "…T10:00:00+02:00" sorts after "…T09:30:00Z", but it is the earlier instant. + const slots = [{ start: '2026-06-15T09:30:00Z' }, { start: '2026-06-15T10:00:00+02:00' }]; + assert.equal(B.earliestFreeSlot(slots, 'UTC').slot.start, '2026-06-15T10:00:00+02:00'); +}); + +test('earliestFreeSlot skips the excluded slot and returns null when nothing is left', () => { + const slots = [{ start: '2026-06-15T09:00:00Z' }, { start: '2026-06-15T10:00:00Z' }]; + assert.equal(B.earliestFreeSlot(slots, 'UTC', '2026-06-15T09:00:00Z').slot.start, '2026-06-15T10:00:00Z'); + assert.equal(B.earliestFreeSlot([], 'UTC'), null); + assert.equal(B.earliestFreeSlot(undefined, 'UTC'), null); + assert.equal(B.earliestFreeSlot([{ start: '2026-06-15T09:00:00Z' }], 'UTC', '2026-06-15T09:00:00Z'), null); +}); + +test('earliestFreeSlot ignores a taken slot because it is only ever given the free list', () => { + // The caller passes data.slots (free), never mergeDaySlots output. If it did pass merged + // entries, a taken one would win; this pins that the free list is the contract. + const free = [{ start: '2026-06-15T11:00:00Z' }]; + const taken = [{ start: '2026-06-15T09:00:00Z' }]; + assert.equal(B.earliestFreeSlot(free, 'UTC').slot.start, '2026-06-15T11:00:00Z'); + assert.equal(B.earliestFreeSlot(B.mergeDaySlots(free, taken), 'UTC').slot.start, '2026-06-15T09:00:00Z'); +}); + +test('monthsToProbe walks from this month to maxDate\'s month and never past it', () => { + const now = new Date(2026, 10, 18); // 18 Nov 2026 + const max = new Date(2027, 0, 20); // 20 Jan 2027 + assert.deepEqual(B.monthsToProbe(now, max), [ + { year: 2026, month: 10 }, { year: 2026, month: 11 }, { year: 2027, month: 0 } + ]); +}); + +test('monthsToProbe is one month when maxDate falls in this month', () => { + assert.deepEqual(B.monthsToProbe(new Date(2026, 10, 18), new Date(2026, 10, 30)), [{ year: 2026, month: 10 }]); +}); + +test('monthsToProbe is bounded by the cap when there is no maxDate', () => { + const m = B.monthsToProbe(new Date(2026, 10, 18), null, 3); + assert.deepEqual(m, [{ year: 2026, month: 10 }, { year: 2026, month: 11 }, { year: 2027, month: 0 }]); + assert.equal(B.monthsToProbe(new Date(2026, 10, 18), null).length, 12); +}); diff --git a/internal/handler/book.go b/internal/handler/book.go index 3f80ee42..832de37b 100644 --- a/internal/handler/book.go +++ b/internal/handler/book.go @@ -72,6 +72,7 @@ type bookPageData struct { PriceCents int // raw price for the dataLayer conversion value (0 = free) Currency string // ISO 4217, lowercase MaxFutureDays int + NextAvailable bool // show the "next available" button above the time list (#254) Questions []bookQuestion // AssistantEnabled shows the conversational-booking chat panel when the LLM layer is on. AssistantEnabled bool @@ -464,16 +465,17 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { msgGreeting sql.NullString allowPhoneCall bool accentColor string + showNext bool ) err := h.db.QueryRowContext(r.Context(), ` SELECT et.id, et.name, COALESCE(et.description, ''), et.duration_minutes, et.location_type, COALESCE(et.location_value, ''), et.max_future_days, et.min_notice_minutes, et.routing_mode, u.name, COALESCE(u.avatar_url, ''), - et.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent + et.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent, et.show_next_available 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, &showNext) if errors.Is(err, sql.ErrNoRows) { http.Error(w, "Page not found", http.StatusNotFound) @@ -559,6 +561,7 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { PriceCents: priceCents, Currency: currency, MaxFutureDays: maxDays, + NextAvailable: showNext, Questions: questions, BookingLogicJS: template.JS(bookingLogicJS), // #nosec G203 -- our own bundled JS source constant, not user input AssistantEnabled: h.getLLM() != nil, diff --git a/internal/handler/event_type.go b/internal/handler/event_type.go index 41fe25c3..57bb725a 100644 --- a/internal/handler/event_type.go +++ b/internal/handler/event_type.go @@ -42,6 +42,9 @@ type eventTypeJSON struct { // instead of omitting them. Off by default: the slots endpoint is public, so this // makes the host's booked hours legible to anyone with the link (#19). ShowTakenSlots bool `json:"show_taken_slots"` + // ShowNextAvailable shows the next free time above the booking page's time list, as a + // button that opens that day. Off by default (#254). + ShowNextAvailable bool `json:"show_next_available"` // InviteDelivery is who sends the booker's calendar invite: "calendar" (each host's // connected calendar, from the host's own address), "calnode" (Calnode's own .ics, // from the instance sender, so no host address reaches the booker) or "none" (no one: @@ -106,7 +109,7 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { var et eventTypeJSON var desc, locVal, msgConf, msgCancel, msgResched, msgRemind, msgGreeting sql.NullString var subjConf, subjCancel, subjResched, subjRemind sql.NullString - var isActive, isPublic, showTaken int + var isActive, isPublic, showTaken, showNext int dests := []any{ &et.ID, &et.Slug, &et.Name, &desc, @@ -115,7 +118,7 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { &et.RoutingMode, &et.RRStrategy, &et.BufferBeforeMinutes, &et.BufferAfterMinutes, &et.MinNoticeMinutes, &et.MaxFutureDays, &et.MaxActiveBookings, - &isActive, &isPublic, &showTaken, &et.CreatedAt, + &isActive, &isPublic, &showTaken, &showNext, &et.CreatedAt, &msgConf, &msgCancel, &msgResched, &msgRemind, &msgGreeting, &subjConf, &subjCancel, &subjResched, &subjRemind, &et.PriceCents, &et.Currency, &et.InviteDelivery, &et.DisplayOrder, @@ -137,6 +140,7 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { et.IsActive = isActive != 0 et.IsPublic = isPublic != 0 et.ShowTakenSlots = showTaken != 0 + et.ShowNextAvailable = showNext != 0 if msgConf.Valid { et.MsgConfirmation = &msgConf.String } @@ -174,7 +178,7 @@ const etColumns = `id, slug, name, description, routing_mode, rr_strategy, buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, max_active_bookings, - is_active, is_public, show_taken_slots, created_at, + is_active, is_public, show_taken_slots, show_next_available, created_at, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, price_cents, currency, invite_delivery, display_order` @@ -282,6 +286,7 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { MaxActiveBookings *int `json:"max_active_bookings"` AllowPhoneCall *bool `json:"allow_phone_call"` ShowTakenSlots *bool `json:"show_taken_slots"` + ShowNextAvailable *bool `json:"show_next_available"` InviteDelivery *string `json:"invite_delivery"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { @@ -357,6 +362,10 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { if req.ShowTakenSlots != nil && *req.ShowTakenSlots { showTaken = 1 } + showNext := 0 + if req.ShowNextAvailable != nil && *req.ShowNextAvailable { + showNext = 1 + } inviteDelivery := booking.InviteByCalendar if req.InviteDelivery != nil { mode, ok := normalizeInviteDelivery(*req.InviteDelivery) @@ -385,12 +394,12 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { (id, user_id, slug, name, description, duration_minutes, slot_interval_minutes, location_type, location_value, allow_phone_call, routing_mode, buffer_before_minutes, buffer_after_minutes, - min_notice_minutes, max_future_days, max_active_bookings, show_taken_slots, invite_delivery, + min_notice_minutes, max_future_days, max_active_bookings, show_taken_slots, show_next_available, invite_delivery, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, display_order) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, id, user.ID, req.Slug, req.Name, req.Description, req.DurationMinutes, slotInterval, locType, req.LocationValue, req.AllowPhoneCall != nil && *req.AllowPhoneCall, - routingMode, bufBefore, bufAfter, minNotice, maxFuture, maxActive, showTaken, inviteDelivery, + routingMode, bufBefore, bufAfter, minNotice, maxFuture, maxActive, showTaken, showNext, inviteDelivery, defaultMsgConfirmation, defaultMsgCancellation, defaultMsgReschedule, defaultMsgReminder, req.DisplayOrder) if err != nil { if db.IsUniqueViolation(err) { @@ -520,6 +529,7 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { IsPublic *bool `json:"is_public"` AllowPhoneCall *bool `json:"allow_phone_call"` ShowTakenSlots *bool `json:"show_taken_slots"` + ShowNextAvailable *bool `json:"show_next_available"` InviteDelivery *string `json:"invite_delivery"` Archived *bool `json:"archived"` MsgConfirmation *string `json:"msg_confirmation"` @@ -678,6 +688,13 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { } set("show_taken_slots", v) } + if req.ShowNextAvailable != nil { + v := 0 + if *req.ShowNextAvailable { + v = 1 + } + set("show_next_available", v) + } var newInviteDelivery string if req.InviteDelivery != nil { mode, ok := normalizeInviteDelivery(*req.InviteDelivery) diff --git a/internal/handler/event_type_duplicate.go b/internal/handler/event_type_duplicate.go index a4d7bff9..42ddf567 100644 --- a/internal/handler/event_type_duplicate.go +++ b/internal/handler/event_type_duplicate.go @@ -140,7 +140,7 @@ func (h *Handler) DuplicateEventType(w http.ResponseWriter, r *http.Request) { routing_mode, rr_strategy, buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, max_active_bookings, seat_limit, - is_active, is_public, show_taken_slots, archived_at, + is_active, is_public, show_taken_slots, show_next_available, archived_at, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, price_cents, currency, invite_delivery, display_order) @@ -151,7 +151,7 @@ func (h *Handler) DuplicateEventType(w http.ResponseWriter, r *http.Request) { routing_mode, rr_strategy, buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, max_active_bookings, seat_limit, - 0, is_public, show_taken_slots, NULL, + 0, is_public, show_taken_slots, show_next_available, NULL, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, price_cents, currency, invite_delivery, display_order diff --git a/internal/handler/event_type_duplicate_test.go b/internal/handler/event_type_duplicate_test.go index 581aef3d..4c94ba25 100644 --- a/internal/handler/event_type_duplicate_test.go +++ b/internal/handler/event_type_duplicate_test.go @@ -31,6 +31,7 @@ type duplicateResponse struct { IsActive bool `json:"is_active"` IsPublic bool `json:"is_public"` ShowTakenSlots bool `json:"show_taken_slots"` + ShowNextAvailable bool `json:"show_next_available"` Archived bool `json:"archived"` MsgConfirmation *string `json:"msg_confirmation"` SubjConfirmation *string `json:"subj_confirmation"` @@ -61,7 +62,7 @@ func seedRichEventType(t *testing.T, database *sql.DB, ownerID, memberID string) duration_minutes, slot_interval_minutes, location_type, location_value, routing_mode, rr_strategy, buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, max_active_bookings, seat_limit, - is_active, is_public, show_taken_slots, + is_active, is_public, show_taken_slots, show_next_available, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, price_cents, currency) @@ -70,7 +71,7 @@ func seedRichEventType(t *testing.T, database *sql.DB, ownerID, memberID string) 45, 15, 'phone', '+15550100', 'round_robin', 'priority', 10, 20, 240, 45, 3, 4, - 1, 0, 1, + 1, 0, 1, 1, 'See you soon', 'Sorry to miss you', 'New time below', 'Coming up', 'Hi! When suits you?', 'Confirmed: intro', 'Cancelled: intro', 'Moved: intro', 'Reminder: intro', @@ -185,6 +186,9 @@ func TestDuplicateEventType_copiesTheRowAndEveryChildDataset(t *testing.T) { if !got.ShowTakenSlots { t.Error("show_taken_slots: got false; want the source's true") } + if !got.ShowNextAvailable { + t.Error("show_next_available: got false; want the source's true") + } if got.MsgConfirmation == nil || *got.MsgConfirmation != "See you soon" { t.Errorf("msg_confirmation: got %v", got.MsgConfirmation) } @@ -598,7 +602,7 @@ func TestDuplicateEventType_handlesEveryEventTypeColumn(t *testing.T) { "buffer_before_minutes": true, "buffer_after_minutes": true, "min_notice_minutes": true, "max_future_days": true, "max_active_bookings": true, "seat_limit": true, - "is_public": true, "show_taken_slots": true, + "is_public": true, "show_taken_slots": true, "show_next_available": true, "msg_confirmation": true, "msg_cancellation": true, "msg_reschedule": true, "msg_reminder": true, "msg_greeting": true, "subj_confirmation": true, "subj_cancellation": true, "subj_reschedule": true, diff --git a/internal/handler/manage_handler.go b/internal/handler/manage_handler.go index c6adaabe..f9a84045 100644 --- a/internal/handler/manage_handler.go +++ b/internal/handler/manage_handler.go @@ -47,6 +47,7 @@ type managePageData struct { LocationLabel string PriceLabel string // empty on manage → the eventMeta partial omits the price row MaxFutureDays int + NextAvailable bool // show the "next available" button above the time list (#254) DurationMinutes int CurrentStartISO string // RFC3339 for JS OrganizerTZ string @@ -97,13 +98,14 @@ func (h *Handler) ManagePage(w http.ResponseWriter, r *http.Request) { var etName, etSlug, locType, locValue string var durMins, maxDays, minNotice int + var showNext bool var hostName, accentColor string if err := h.db.QueryRowContext(r.Context(), ` SELECT et.name, et.slug, et.duration_minutes, et.max_future_days, et.min_notice_minutes, - et.location_type, COALESCE(et.location_value,''), u.name, u.booking_accent + et.location_type, COALESCE(et.location_value,''), u.name, u.booking_accent, et.show_next_available FROM event_types et JOIN users u ON u.id = et.user_id WHERE et.id = ?`, b.EventTypeID). - Scan(&etName, &etSlug, &durMins, &maxDays, &minNotice, &locType, &locValue, &hostName, &accentColor); err != nil { + Scan(&etName, &etSlug, &durMins, &maxDays, &minNotice, &locType, &locValue, &hostName, &accentColor, &showNext); err != nil { h.logger.ErrorContext(r.Context(), "manage page: load event type", "error", err) http.Error(w, "Internal server error", http.StatusInternalServerError) return @@ -157,6 +159,7 @@ func (h *Handler) ManagePage(w http.ResponseWriter, r *http.Request) { DurationLabel: durationLabel(durMins, loc), LocationLabel: locationLabel(locType, locValue, loc), MaxFutureDays: maxDays, + NextAvailable: showNext, DurationMinutes: durMins, CurrentStartISO: b.StartAt.UTC().Format(time.RFC3339), OrganizerTZ: orgTZ, diff --git a/internal/handler/next_available_test.go b/internal/handler/next_available_test.go new file mode 100644 index 00000000..32fbed65 --- /dev/null +++ b/internal/handler/next_available_test.go @@ -0,0 +1,136 @@ +package handler_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "regexp" + "strings" + "testing" +) + +// html/template pads a bool in script context with spaces ("SHOW_NEXT = true ;"), so match +// the shape rather than the exact bytes. +var showNextTrue = regexp.MustCompile(`SHOW_NEXT\s*=\s*true\b`) +var showNextFalse = regexp.MustCompile(`SHOW_NEXT\s*=\s*false\b`) + +// The next-available line is opt-in per event type (#254): off unless asked for, settable on +// create and on PATCH, and rendered on the booking page only when on. + +func TestShowNextAvailable_defaultsOffAndRoundTripsThroughPatch(t *testing.T) { + h, key, _ := setupWorkspace(t) + slug, _ := seedEventTypeHTTP(t, h, key) + + get := func() map[string]any { + req := authReq(http.MethodGet, "/v1/event-types/"+slug, "", key) + req.SetPathValue("slug", slug) + rec := httptest.NewRecorder() + h.RequireAuth(h.GetEventType)(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("get: %d — %s", rec.Code, rec.Body.String()) + } + var et map[string]any + if err := json.Unmarshal(rec.Body.Bytes(), &et); err != nil { + t.Fatal(err) + } + return et + } + if got := get()["show_next_available"]; got != false { + t.Fatalf("show_next_available = %v on a new event type; want false", got) + } + + patch := func(body string) { + req := authReq(http.MethodPatch, "/v1/event-types/"+slug, body, key) + req.SetPathValue("slug", slug) + rec := httptest.NewRecorder() + h.RequireAuth(h.PatchEventType)(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("patch %s: %d — %s", body, rec.Code, rec.Body.String()) + } + } + patch(`{"show_next_available":true}`) + if got := get()["show_next_available"]; got != true { + t.Errorf("show_next_available = %v after PATCH true; want true", got) + } + // An unrelated PATCH must leave it alone: a nil pointer means "not mentioned". + patch(`{"name":"Renamed"}`) + if got := get()["show_next_available"]; got != true { + t.Errorf("show_next_available = %v after an unrelated PATCH; want it left true", got) + } + patch(`{"show_next_available":false}`) + if got := get()["show_next_available"]; got != false { + t.Errorf("show_next_available = %v after PATCH false; want false", got) + } +} + +func TestBookPage_nextAvailableLinkOnlyWhenEnabled(t *testing.T) { + h, key, _ := setupWorkspace(t) + + render := func(slug, body string) string { + req := authReq(http.MethodPost, "/v1/event-types", body, key) + rec := httptest.NewRecorder() + h.RequireAuth(h.CreateEventType)(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("create %s: %d — %s", slug, rec.Code, rec.Body.String()) + } + pageReq := httptest.NewRequest(http.MethodGet, "/book/"+slug, nil) + pageReq.SetPathValue("slug", slug) + pageRec := httptest.NewRecorder() + h.BookPage(pageRec, pageReq) + if pageRec.Code != http.StatusOK { + t.Fatalf("BookPage %s: %d", slug, pageRec.Code) + } + return pageRec.Body.String() + } + + on := render("next-on", `{"slug":"next-on","name":"On","duration_minutes":30,"show_next_available":true}`) + if !strings.Contains(on, `class="next-available`) { + t.Error("enabled event type: page has no next-available button") + } + if !showNextTrue.MatchString(on) { + t.Error("enabled event type: SHOW_NEXT is not true in the page script") + } + + off := render("next-off", `{"slug":"next-off","name":"Off","duration_minutes":30}`) + if strings.Contains(off, `class="next-available`) { + t.Error("default event type: page renders a next-available button") + } + if !showNextFalse.MatchString(off) { + t.Error("default event type: SHOW_NEXT is not false in the page script") + } +} + +// The reschedule page carries the same calendar, so it gets the same opt-in (#254). +func TestManagePage_nextAvailableLinkOnlyWhenEnabled(t *testing.T) { + h, database, key, _ := setupWorkspaceWithDB(t) + slug, _ := seedEventTypeHTTP(t, h, key) + tok := issueTestToken(t, database, createBookingViaHTTP(t, h, slug, "2026-06-20T09:00:00Z")) + + render := func() string { + req := httptest.NewRequest(http.MethodGet, "/manage/"+tok, nil) + req.SetPathValue("token", tok) + rec := httptest.NewRecorder() + h.ManagePage(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("ManagePage: %d", rec.Code) + } + return rec.Body.String() + } + + off := render() + if strings.Contains(off, `class="next-available`) || !showNextFalse.MatchString(off) { + t.Error("default event type: reschedule page shows or enables next-available") + } + + req := authReq(http.MethodPatch, "/v1/event-types/"+slug, `{"show_next_available":true}`, key) + req.SetPathValue("slug", slug) + rec := httptest.NewRecorder() + h.RequireAuth(h.PatchEventType)(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("patch: %d — %s", rec.Code, rec.Body.String()) + } + on := render() + if !strings.Contains(on, `class="next-available`) || !showNextTrue.MatchString(on) { + t.Error("enabled event type: reschedule page has no next-available button") + } +} diff --git a/internal/handler/templates/book.html b/internal/handler/templates/book.html index 3de3207f..c47f2de4 100644 --- a/internal/handler/templates/book.html +++ b/internal/handler/templates/book.html @@ -153,6 +153,7 @@

{{.Name}}

+ {{if .NextAvailable}}{{end}} {{template "calendarGrid" .}}

@@ -166,6 +167,9 @@

{{.Name}}

+ + {{if .NextAvailable}}{{end}}

{{call .T "select_day_hint"}}