From 77b494fafb4d3e25fe07345443c2f04d7e3b175e Mon Sep 17 00:00:00 2001 From: Wynne Pirini Date: Tue, 1 Dec 2026 13:54:59 +1300 Subject: [PATCH 1/3] feat(event-types): replace is_public with a visibility state (#272, step 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Step 1 of #272: `public`, `unlisted`, `private`. `internal` is reserved in the schema but not settable yet — it needs optional authentication on the public booking/slots endpoints, which is #269. Why one model rather than a fourth boolean: `is_public` was read at 18 sites with no shared helper, and #237 (unlisted, link works but not listed) and #269 (internal, credential-only) each wanted a state it could not express. Building them separately would have produced two half-models of the same concept. Design: - `Visibility` in internal/handler/visibility.go is the ONLY definition of what a state means: Listed(), PublicBookable(), Bookable(authenticated), settable(). Every surface asks those predicates instead of testing the string, which is the lesson from calselect.go — five separate checks drift invisibly. - parseVisibility fails closed: an unrecognised stored value is private, so a corrupt row hides a page rather than exposing one. - Migration 00074 adds `visibility` with a CHECK covering all four values (no table rebuild when internal lands), backfills `is_public = 1 -> public`, `0 -> private`, then drops `is_public`. Existing drafts stay unbookable. - `internal` is rejected by both create and PATCH (400), so an operator cannot select a state whose booking path does not exist yet. Surfaces: directory (public only), MCP listing (public only), book page, public questions and the booking gate (public + unlisted), duplicate, demo seed. Admin UI: the is-public checkbox becomes a three-option select, and the read-only view labels all four states (including internal, for rows written after step 2). en/fr catalogue entries added. Verified on a real instance, which is where a bug was caught: the create path was silently ignoring the new field and storing 'public' for every request. Fixed before commit — POST now honours visibility, rejects internal with 400, and the book pages behave as the model says: et-public -> 200 et-unlisted -> 200 (link works, not listed) et-private -> 404 Tests: Visibility predicate table, internal bookable-only-when-authenticated, fail-closed parsing, plus the existing suites updated for the renamed column. go test ./... green; pnpm check 0 errors; pnpm test:visual 27 passed. Breaking change recorded in CHANGELOG under Upgrading: is_public is removed from REST and MCP payloads, and external clients must switch to visibility. --- CHANGELOG.md | 7 ++ frontend/src/lib/api.ts | 2 +- frontend/src/lib/i18n/en.json | 10 ++- frontend/src/lib/i18n/fr.json | 10 ++- .../routes/event-types/[slug]/+page.svelte | 41 ++++++++--- internal/db/constraint_test.go | 4 +- .../00074_event_type_visibility.sql | 23 +++++++ internal/demo/demo.go | 4 +- internal/handler/book.go | 4 +- internal/handler/book_test.go | 4 +- internal/handler/booking_handler.go | 16 +++-- internal/handler/directory.go | 4 +- internal/handler/directory_order_test.go | 2 +- internal/handler/directory_test.go | 4 +- internal/handler/event_type.go | 60 ++++++++++------ internal/handler/event_type_duplicate.go | 4 +- internal/handler/event_type_duplicate_test.go | 12 ++-- internal/handler/mcp.go | 2 +- internal/handler/question_handler.go | 2 +- internal/handler/slots_notice_test.go | 4 +- internal/handler/visibility.go | 68 ++++++++++++++++++ internal/handler/visibility_test.go | 69 +++++++++++++++++++ 22 files changed, 293 insertions(+), 63 deletions(-) create mode 100644 internal/db/migrations/00074_event_type_visibility.sql create mode 100644 internal/handler/visibility.go create mode 100644 internal/handler/visibility_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 1149229b..495fc759 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,13 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad ### Upgrading +- **API break: `is_public` is gone.** Event types now expose `visibility` + (`public` | `unlisted` | `private`) instead of the `is_public` boolean, in both REST and + MCP payloads. An external client reading `is_public` will get `undefined` and must + switch to `visibility`. Migration `00074` backfills `is_public = 0` to `private`, so + event types that were unpublished stay unbookable — nothing becomes public by + upgrading. A fourth value, `internal`, exists in the schema but cannot be set yet. + - **Back up the database before upgrading.** This release includes a migration (`00072`) that renames two columns on `bookings` and adds one. Migrations run automatically at boot, so the upgrade is the moment to want a restore point that predates it. diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index cd6c8723..3896b311 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -34,7 +34,7 @@ export type EventType = { // duration on create; editable so a 45-minute meeting can still be offered on the hour. slot_interval_minutes: number; is_active: boolean; - is_public: boolean; + visibility: 'public' | 'unlisted' | 'private' | 'internal'; /** Show already-booked times struck through on the booking page instead of hiding * them. Off by default: the slots endpoint is public, so this makes the host's * booked hours visible to anyone with the link. */ diff --git a/frontend/src/lib/i18n/en.json b/frontend/src/lib/i18n/en.json index 1a3870ce..3d233480 100644 --- a/frontend/src/lib/i18n/en.json +++ b/frontend/src/lib/i18n/en.json @@ -1618,7 +1618,9 @@ "active": "Active", "inactive": "Inactive", "listed": "Listed", - "unlisted": "Unlisted (link only)" + "unlisted": "Unlisted (link only)", + "private": "Private", + "internal": "Internal" }, "durationSuffix": " min" }, @@ -1646,7 +1648,11 @@ "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.", - "allowPhoneCall": "Let invitees choose a phone call by entering their number" + "allowPhoneCall": "Let invitees choose a phone call by entering their number", + "visibilityPublic": "Public (listed and bookable)", + "visibilityUnlisted": "Unlisted (link only)", + "visibilityPrivate": "Private (not bookable)", + "visibilityInternal": "Internal (not available yet)" }, "location": { "section": "Location", diff --git a/frontend/src/lib/i18n/fr.json b/frontend/src/lib/i18n/fr.json index b9af9802..eba51cc7 100644 --- a/frontend/src/lib/i18n/fr.json +++ b/frontend/src/lib/i18n/fr.json @@ -1618,7 +1618,9 @@ "active": "Actif", "inactive": "Inactif", "listed": "Répertorié", - "unlisted": "Non répertorié (lien uniquement)" + "unlisted": "Non répertorié (lien uniquement)", + "private": "Privé", + "internal": "Interne" }, "durationSuffix": " min" }, @@ -1646,7 +1648,11 @@ "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.", - "allowPhoneCall": "Permettre aux invités de choisir un appel téléphonique en saisissant leur numéro" + "allowPhoneCall": "Permettre aux invités de choisir un appel téléphonique en saisissant leur numéro", + "visibilityPublic": "Public (listé et réservable)", + "visibilityUnlisted": "Non listé (lien uniquement)", + "visibilityPrivate": "Privé (non réservable)", + "visibilityInternal": "Interne (pas encore disponible)" }, "location": { "section": "Lieu", diff --git a/frontend/src/routes/event-types/[slug]/+page.svelte b/frontend/src/routes/event-types/[slug]/+page.svelte index 84e6f5d4..6eddd97c 100644 --- a/frontend/src/routes/event-types/[slug]/+page.svelte +++ b/frontend/src/routes/event-types/[slug]/+page.svelte @@ -84,10 +84,29 @@ // Any location that produces a join link the booker has to receive somehow. const isOnlineLocation = (t: string) => isOnlineMeeting(t) || t === 'zoom' || t === 'livekit'; + // Visibility is a closed set (#272). The read-only view labels all four in case a + // row arrives with a state this build cannot set (internal, until step 2). + function visibilityLabel(v: EventType['visibility']) { + switch (v) { + case 'unlisted': return $t('eventTypeEditor.readOnly.status.unlisted'); + case 'private': return $t('eventTypeEditor.readOnly.status.private'); + case 'internal': return $t('eventTypeEditor.readOnly.status.internal'); + default: return $t('eventTypeEditor.readOnly.status.listed'); + } + } + function visibilityKey(v: EventType['visibility']) { + switch (v) { + case 'unlisted': return 'eventTypeEditor.general.visibilityUnlisted'; + case 'private': return 'eventTypeEditor.general.visibilityPrivate'; + case 'internal': return 'eventTypeEditor.general.visibilityInternal'; + default: return 'eventTypeEditor.general.visibilityPublic'; + } + } + 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, visibility: 'public' as EventType['visibility'], show_taken_slots: false, invite_delivery: 'calendar' as EventType['invite_delivery'], location_type: 'link', location_value: '', buffer_before_minutes: 0, buffer_after_minutes: 0, @@ -334,7 +353,7 @@ duration_minutes: et.duration_minutes, slot_interval_minutes: et.slot_interval_minutes, is_active: et.is_active, - is_public: et.is_public, + visibility: et.visibility, show_taken_slots: et.show_taken_slots ?? false, invite_delivery: et.invite_delivery ?? 'calendar', location_type: et.location_type, @@ -395,7 +414,7 @@ duration_minutes: Number(form.duration_minutes), slot_interval_minutes: Number(form.slot_interval_minutes), is_active: form.is_active, - is_public: form.is_public, + visibility: form.visibility, show_taken_slots: form.show_taken_slots, invite_delivery: form.invite_delivery, allow_phone_call: allowPhoneCall, @@ -612,7 +631,7 @@ {/if}
{$t('eventTypeEditor.readOnly.labels.location')}
{LOCATION_TYPES.find((l) => l.value === et?.location_type)?.label ?? et.location_type}{#if et.location_value} · {et.location_value}{/if}
{$t('eventTypeEditor.readOnly.labels.routing')}
{et.routing_mode.replace('_', ' ')}
-
{$t('eventTypeEditor.readOnly.labels.status')}
{et.is_active ? $t('eventTypeEditor.readOnly.status.active') : $t('eventTypeEditor.readOnly.status.inactive')} · {et.is_public ? $t('eventTypeEditor.readOnly.status.listed') : $t('eventTypeEditor.readOnly.status.unlisted')}
+
{$t('eventTypeEditor.readOnly.labels.status')}
{et.is_active ? $t('eventTypeEditor.readOnly.status.active') : $t('eventTypeEditor.readOnly.status.inactive')} · {visibilityLabel(et.visibility)}
{$t('eventTypeEditor.readOnly.labels.bookingPage')}
/book/{et.slug}
@@ -682,11 +701,15 @@
-

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

-
- - -
+ + + {$t(visibilityKey(form.visibility))} + + {$t('eventTypeEditor.general.visibilityPublic')} + {$t('eventTypeEditor.general.visibilityUnlisted')} + {$t('eventTypeEditor.general.visibilityPrivate')} + +
diff --git a/internal/db/constraint_test.go b/internal/db/constraint_test.go index 1fdc59a1..a45c9cfe 100644 --- a/internal/db/constraint_test.go +++ b/internal/db/constraint_test.go @@ -108,8 +108,8 @@ func TestConstraintPredicates(t *testing.T) { t.Run("foreign key on delete restrict", func(t *testing.T) { const etID = "et-restrict" if _, err := database.Exec( - `INSERT INTO event_types (id, user_id, slug, name, duration_minutes, slot_interval_minutes, location_type, is_active, is_public, archived_at) - VALUES (?, ?, 'restrict-et', 'Restrict ET', 30, 30, 'in_person', 1, 1, NULL)`, + `INSERT INTO event_types (id, user_id, slug, name, duration_minutes, slot_interval_minutes, location_type, is_active, visibility, archived_at) + VALUES (?, ?, 'restrict-et', 'Restrict ET', 30, 30, 'in_person', 1, 'public', NULL)`, etID, userID); err != nil { t.Fatalf("seed event type: %v", err) } diff --git a/internal/db/migrations/00074_event_type_visibility.sql b/internal/db/migrations/00074_event_type_visibility.sql new file mode 100644 index 00000000..6d337d3b --- /dev/null +++ b/internal/db/migrations/00074_event_type_visibility.sql @@ -0,0 +1,23 @@ +-- +goose Up +-- Event-type visibility (#272): replace the is_public boolean with a four-state column. +-- +-- is_public=1 -> public, is_public=0 -> private. Existing drafts must stay unbookable: +-- nothing is reinterpreted as unlisted or internal. +-- +-- 'internal' is allowed by the CHECK now even though nothing may set it yet (the API +-- rejects it until optional authentication lands, step 2 / #269). Including it here +-- avoids a table rebuild later, which in SQLite means recreating the table and every +-- index on it. +ALTER TABLE event_types ADD COLUMN visibility TEXT NOT NULL DEFAULT 'public' + CHECK (visibility IN ('public', 'unlisted', 'internal', 'private')); + +UPDATE event_types SET visibility = CASE WHEN is_public = 1 THEN 'public' ELSE 'private' END; + +ALTER TABLE event_types DROP COLUMN is_public; + +-- +goose Down +-- Lossy by nature: unlisted and internal have no is_public equivalent, so both collapse +-- to not-public (=0). Documented rather than pretended away. +ALTER TABLE event_types ADD COLUMN is_public INTEGER NOT NULL DEFAULT 0; +UPDATE event_types SET is_public = CASE WHEN visibility = 'public' THEN 1 ELSE 0 END; +ALTER TABLE event_types DROP COLUMN visibility; diff --git a/internal/demo/demo.go b/internal/demo/demo.go index 440230bb..b16ec5d2 100644 --- a/internal/demo/demo.go +++ b/internal/demo/demo.go @@ -111,8 +111,8 @@ func Seed(ctx context.Context, db *sql.DB) error { INSERT INTO event_types (id, user_id, team_id, slug, name, description, duration_minutes, location_type, location_value, routing_mode, min_notice_minutes, - max_future_days, is_active, is_public) - VALUES (?, ?, ?, ?, ?, ?, ?, 'link', 'https://example.com/demo-meeting', ?, ?, ?, 1, 1)`, + max_future_days, is_active, visibility) + VALUES (?, ?, ?, ?, ?, ?, ?, 'link', 'https://example.com/demo-meeting', ?, ?, ?, 1, 'public')`, et.id, OwnerUserID, teamVal, et.slug, et.name, et.description, et.durationMinutes, routingMode, et.minNoticeMinutes, et.maxFutureDays); err != nil { return fmt.Errorf("demo seed: event type %s: %w", et.slug, err) diff --git a/internal/handler/book.go b/internal/handler/book.go index 7bddd295..c6ff541d 100644 --- a/internal/handler/book.go +++ b/internal/handler/book.go @@ -361,7 +361,7 @@ func (h *Handler) PublicEventType(w http.ResponseWriter, r *http.Request) { et.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent 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`, + WHERE et.slug = ? AND et.is_active = 1 AND et.visibility IN ('public', 'unlisted')`, slug).Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor) if errors.Is(err, sql.ErrNoRows) { h.writeError(w, http.StatusNotFound, "event type not found") @@ -480,7 +480,7 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { et.price_cents, et.currency, et.msg_greeting, et.allow_phone_call, u.booking_accent 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`, + WHERE et.slug = ? AND et.is_active = 1 AND et.visibility IN ('public', 'unlisted')`, slug).Scan(&etID, &name, &description, &durMins, &locType, &locValue, &maxDays, &minNotice, &routingMode, &hostName, &avatarURL, &priceCents, ¤cy, &msgGreeting, &allowPhoneCall, &accentColor) if errors.Is(err, sql.ErrNoRows) { diff --git a/internal/handler/book_test.go b/internal/handler/book_test.go index d7be13a2..58204ebb 100644 --- a/internal/handler/book_test.go +++ b/internal/handler/book_test.go @@ -116,12 +116,12 @@ func TestBookPage_privateEventType_returns404(t *testing.T) { slug, _ := seedEventTypeHTTP(t, h, apiKey) // Make the event type private. - patchReq := authReq(http.MethodPatch, "/v1/event-types/"+slug, `{"is_public":false}`, apiKey) + patchReq := authReq(http.MethodPatch, "/v1/event-types/"+slug, `{"visibility":"private"}`, apiKey) patchReq.SetPathValue("slug", slug) patchRec := httptest.NewRecorder() h.RequireAuth(h.PatchEventType)(patchRec, patchReq) if patchRec.Code != http.StatusOK { - t.Fatalf("patch is_public=false: got %d — %s", patchRec.Code, patchRec.Body.String()) + t.Fatalf("patch visibility=private: got %d — %s", patchRec.Code, patchRec.Body.String()) } req := httptest.NewRequest(http.MethodGet, "/book/"+slug, nil) diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index e1f54313..8dc47e59 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -516,6 +516,7 @@ type bookableEventType struct { BufferAfterMinutes int MinNoticeMinutes int MaxFutureDays int + Visibility Visibility MaxActiveBookings int PriceCents int Currency string @@ -535,20 +536,27 @@ type bookableEventType struct { // everywhere, not just hidden from its own page. func (h *Handler) loadBookableEventType(ctx context.Context, slug string) (*bookableEventType, error) { var et bookableEventType - var isActive, isPublic, showTaken int + var isActive, showTaken int + var visibilityRaw string err := h.db.QueryRowContext(ctx, ` SELECT id, user_id, name, duration_minutes, slot_interval_minutes, location_type, location_value, allow_phone_call, routing_mode, rr_strategy, buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, - is_active, is_public, show_taken_slots, max_active_bookings, price_cents, currency, + is_active, visibility, show_taken_slots, max_active_bookings, price_cents, currency, invite_delivery FROM event_types WHERE slug = ?`, slug). Scan(&et.ID, &et.UserID, &et.Name, &et.DurationMinutes, &et.SlotIntervalMinutes, &et.LocationType, &et.LocationValue, &et.AllowPhoneCall, &et.RoutingMode, &et.RRStrategy, &et.BufferBeforeMinutes, &et.BufferAfterMinutes, &et.MinNoticeMinutes, &et.MaxFutureDays, - &isActive, &isPublic, &showTaken, &et.MaxActiveBookings, &et.PriceCents, &et.Currency, + &isActive, &visibilityRaw, &showTaken, &et.MaxActiveBookings, &et.PriceCents, &et.Currency, &et.InviteDelivery) - if err != nil || isActive == 0 || isPublic == 0 { + if err != nil || isActive == 0 { + return nil, errEventTypeNotFound + } + // Step 1 (#272): no caller of this gate is authenticated yet, so "internal" is not + // reachable here. Step 2 (#269) threads an authenticated flag through instead. + et.Visibility = parseVisibility(visibilityRaw) + if !et.Visibility.Bookable(false) { return nil, errEventTypeNotFound } et.ShowTakenSlots = showTaken != 0 diff --git a/internal/handler/directory.go b/internal/handler/directory.go index 4b5626cd..6f2baf42 100644 --- a/internal/handler/directory.go +++ b/internal/handler/directory.go @@ -141,7 +141,7 @@ func (h *Handler) PersonPage(w http.ResponseWriter, r *http.Request) { brand := h.loadBranding(r.Context()) loc := h.resolveLocaleWithFallback(r, brand.FallbackLocale) items, err := h.directoryItems(r.Context(), loc, - `et.is_public = 1 AND et.is_active = 1 AND (et.user_id = ? OR EXISTS + `et.visibility = 'public' AND et.is_active = 1 AND (et.user_id = ? OR EXISTS (SELECT 1 FROM event_type_hosts hh WHERE hh.event_type_id = et.id AND hh.user_id = ?))`, userID, userID) if err != nil { @@ -206,7 +206,7 @@ func (h *Handler) TeamPage(w http.ResponseWriter, r *http.Request) { brand := h.loadBranding(r.Context()) loc := h.resolveLocaleWithFallback(r, brand.FallbackLocale) items, err := h.directoryItems(r.Context(), loc, - `et.team_id = ? AND et.is_public = 1 AND et.is_active = 1`, teamID) + `et.team_id = ? AND et.visibility = 'public' AND et.is_active = 1`, teamID) if err != nil { h.logger.ErrorContext(r.Context(), "team page: load event types", "error", err) http.Error(w, "Internal server error", http.StatusInternalServerError) diff --git a/internal/handler/directory_order_test.go b/internal/handler/directory_order_test.go index d053c29b..9a0b6338 100644 --- a/internal/handler/directory_order_test.go +++ b/internal/handler/directory_order_test.go @@ -139,7 +139,7 @@ func TestDirectories_displayOrder(t *testing.T) { for _, slug := range []string{"hidden", "inactive", "unrelated"} { mustExec(t, database, `INSERT INTO event_types (id,user_id,team_id,slug,name,duration_minutes,display_order) VALUES (?,?,'order-team',?, ?,30,-100)`, slug, ownerID, slug, slug) } - mustExec(t, database, `UPDATE event_types SET is_public = 0 WHERE slug = 'hidden'`) + mustExec(t, database, `UPDATE event_types SET visibility = 'private' WHERE slug = 'hidden'`) mustExec(t, database, `UPDATE event_types SET is_active = 0 WHERE slug = 'inactive'`) mustExec(t, database, `UPDATE event_types SET user_id = 'other-owner', team_id = NULL WHERE slug = 'unrelated'`) checkPages := func(want []string) { diff --git a/internal/handler/directory_test.go b/internal/handler/directory_test.go index 1e4a1765..14ffa5ff 100644 --- a/internal/handler/directory_test.go +++ b/internal/handler/directory_test.go @@ -77,8 +77,8 @@ func TestPersonPage_listsPublicActiveEventTypes(t *testing.T) { } slugVisible, _ := seedEventTypeHTTP(t, h, key) slugHidden, _ := seedEventTypeHTTP(t, h, key) - // Hide one via is_public. - req := authReq(http.MethodPatch, "/v1/event-types/"+slugHidden, `{"is_public":false}`, key) + // Hide one via visibility. + req := authReq(http.MethodPatch, "/v1/event-types/"+slugHidden, `{"visibility":"private"}`, key) req.SetPathValue("slug", slugHidden) rec := httptest.NewRecorder() h.RequireAuth(h.PatchEventType)(rec, req) diff --git a/internal/handler/event_type.go b/internal/handler/event_type.go index 41fe25c3..d60bbe51 100644 --- a/internal/handler/event_type.go +++ b/internal/handler/event_type.go @@ -47,13 +47,16 @@ type eventTypeJSON struct { // from the instance sender, so no host address reaches the booker) or "none" (no one: // guestless host events and no .ics, for integrations that send their own invite). // See migrations 00068 and 00071. - InviteDelivery string `json:"invite_delivery"` - IsPublic bool `json:"is_public"` - CreatedAt string `json:"created_at"` - MsgConfirmation *string `json:"msg_confirmation"` - MsgCancellation *string `json:"msg_cancellation"` - MsgReschedule *string `json:"msg_reschedule"` - MsgReminder *string `json:"msg_reminder"` + InviteDelivery string `json:"invite_delivery"` + // Visibility is how the type is exposed: public / unlisted / private (and + // internal, once step 2 lands). See visibility.go for the single definition of + // what each state means. Replaces the old is_public boolean (#272). + Visibility Visibility `json:"visibility"` + CreatedAt string `json:"created_at"` + MsgConfirmation *string `json:"msg_confirmation"` + MsgCancellation *string `json:"msg_cancellation"` + MsgReschedule *string `json:"msg_reschedule"` + MsgReminder *string `json:"msg_reminder"` // MsgGreeting overrides the conversational assistant's opening line for this event // type. Unlike the Msg* fields above, nil/empty means "no override" — the assistant // falls back to the locale-keyed default greeting, not a fixed English seed. @@ -106,7 +109,8 @@ 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, showTaken int + var visibilityRaw string dests := []any{ &et.ID, &et.Slug, &et.Name, &desc, @@ -115,7 +119,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, &visibilityRaw, &showTaken, &et.CreatedAt, &msgConf, &msgCancel, &msgResched, &msgRemind, &msgGreeting, &subjConf, &subjCancel, &subjResched, &subjRemind, &et.PriceCents, &et.Currency, &et.InviteDelivery, &et.DisplayOrder, @@ -135,7 +139,7 @@ func scanEventTypeRow(s rowScanner, trailing ...any) (*eventTypeJSON, error) { et.LocationValue = &locVal.String } et.IsActive = isActive != 0 - et.IsPublic = isPublic != 0 + et.Visibility = parseVisibility(visibilityRaw) et.ShowTakenSlots = showTaken != 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, visibility, show_taken_slots, 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` @@ -283,6 +287,7 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { AllowPhoneCall *bool `json:"allow_phone_call"` ShowTakenSlots *bool `json:"show_taken_slots"` InviteDelivery *string `json:"invite_delivery"` + Visibility *string `json:"visibility"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { h.writeError(w, http.StatusBadRequest, "invalid JSON") @@ -357,6 +362,17 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { if req.ShowTakenSlots != nil && *req.ShowTakenSlots { showTaken = 1 } + // Visibility defaults to public (the pre-#272 default) but must be honoured when + // given; silently ignoring it would create a public event type from a request that + // asked for private. + visibility := VisibilityPublic + if req.Visibility != nil { + visibility = Visibility(*req.Visibility) + if !visibility.settable() { + h.writeError(w, http.StatusBadRequest, "visibility must be 'public', 'unlisted' or 'private'") + return + } + } inviteDelivery := booking.InviteByCalendar if req.InviteDelivery != nil { mode, ok := normalizeInviteDelivery(*req.InviteDelivery) @@ -386,12 +402,12 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { slot_interval_minutes, location_type, location_value, allow_phone_call, routing_mode, buffer_before_minutes, buffer_after_minutes, min_notice_minutes, max_future_days, max_active_bookings, show_taken_slots, invite_delivery, - msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, display_order) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + visibility, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, display_order) + 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, - defaultMsgConfirmation, defaultMsgCancellation, defaultMsgReschedule, defaultMsgReminder, req.DisplayOrder) + string(visibility), defaultMsgConfirmation, defaultMsgCancellation, defaultMsgReschedule, defaultMsgReminder, req.DisplayOrder) if err != nil { if db.IsUniqueViolation(err) { h.writeError(w, http.StatusConflict, "slug already in use") @@ -517,7 +533,7 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { MaxFutureDays *int `json:"max_future_days"` MaxActiveBookings *int `json:"max_active_bookings"` IsActive *bool `json:"is_active"` - IsPublic *bool `json:"is_public"` + Visibility *string `json:"visibility"` AllowPhoneCall *bool `json:"allow_phone_call"` ShowTakenSlots *bool `json:"show_taken_slots"` InviteDelivery *string `json:"invite_delivery"` @@ -661,12 +677,16 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { } set("is_active", v) } - if req.IsPublic != nil { - v := 0 - if *req.IsPublic { - v = 1 + if req.Visibility != nil { + v := Visibility(*req.Visibility) + if !v.settable() { + // "internal" is a known state but is not selectable until step 2 (#269): + // accepting it would let an operator pick a visibility whose booking path + // does not exist yet, which fails silently at booking time. + h.writeError(w, http.StatusBadRequest, "visibility must be 'public', 'unlisted' or 'private'") + return } - set("is_public", v) + set("visibility", string(v)) } if req.AllowPhoneCall != nil { set("allow_phone_call", *req.AllowPhoneCall) diff --git a/internal/handler/event_type_duplicate.go b/internal/handler/event_type_duplicate.go index a4d7bff9..a2b1e344 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, visibility, show_taken_slots, 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, visibility, show_taken_slots, 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..b5c5f9e1 100644 --- a/internal/handler/event_type_duplicate_test.go +++ b/internal/handler/event_type_duplicate_test.go @@ -29,7 +29,7 @@ type duplicateResponse struct { MaxFutureDays int `json:"max_future_days"` MaxActiveBookings int `json:"max_active_bookings"` IsActive bool `json:"is_active"` - IsPublic bool `json:"is_public"` + Visibility string `json:"visibility"` ShowTakenSlots bool `json:"show_taken_slots"` Archived bool `json:"archived"` MsgConfirmation *string `json:"msg_confirmation"` @@ -61,7 +61,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, visibility, show_taken_slots, msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, msg_greeting, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, price_cents, currency) @@ -70,7 +70,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, 'private', 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', @@ -179,8 +179,8 @@ func TestDuplicateEventType_copiesTheRowAndEveryChildDataset(t *testing.T) { t.Errorf("limits: got %d/%d/%d; want 240/45/3", got.MinNoticeMinutes, got.MaxFutureDays, got.MaxActiveBookings) } - if got.IsPublic { - t.Error("is_public: got true; want the source's false") + if got.Visibility != "private" { + t.Errorf("visibility: got %q; want the source's private", got.Visibility) } if !got.ShowTakenSlots { t.Error("show_taken_slots: got false; want the source's true") @@ -598,7 +598,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, + "visibility": true, "show_taken_slots": 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/mcp.go b/internal/handler/mcp.go index 855844c3..29e430fc 100644 --- a/internal/handler/mcp.go +++ b/internal/handler/mcp.go @@ -100,7 +100,7 @@ func (h *Handler) mcpListEventTypes(ctx context.Context, _ *mcp.CallToolRequest, rows, err := h.db.QueryContext(ctx, ` SELECT slug, name, duration_minutes, location_type, COALESCE(description, '') FROM event_types - WHERE is_active = 1 AND is_public = 1 + WHERE is_active = 1 AND visibility = 'public' ORDER BY name`) if err != nil { return nil, listEventTypesOut{}, fmt.Errorf("list event types: %w", err) diff --git a/internal/handler/question_handler.go b/internal/handler/question_handler.go index ea2a1183..c2f23000 100644 --- a/internal/handler/question_handler.go +++ b/internal/handler/question_handler.go @@ -41,7 +41,7 @@ func (h *Handler) ListQuestions(w http.ResponseWriter, r *http.Request) { var etID string err := h.db.QueryRowContext(r.Context(), - `SELECT id FROM event_types WHERE slug = ? AND is_active = 1 AND is_public = 1`, slug).Scan(&etID) + `SELECT id FROM event_types WHERE slug = ? AND is_active = 1 AND visibility IN ('public', 'unlisted')`, slug).Scan(&etID) if errors.Is(err, sql.ErrNoRows) { h.writeError(w, http.StatusNotFound, "event type not found") return diff --git a/internal/handler/slots_notice_test.go b/internal/handler/slots_notice_test.go index cf0365ab..8a117224 100644 --- a/internal/handler/slots_notice_test.go +++ b/internal/handler/slots_notice_test.go @@ -25,8 +25,8 @@ func seedNoticeEventType(t *testing.T, database *sql.DB, ownerID, slug string, m etID := uid.New() if _, err := database.Exec(` INSERT INTO event_types (id, user_id, slug, name, duration_minutes, slot_interval_minutes, - min_notice_minutes, max_future_days, is_active, is_public) - VALUES (?, ?, ?, 'Intro Call', 30, 30, ?, 0, 1, 1)`, + min_notice_minutes, max_future_days, is_active, visibility) + VALUES (?, ?, ?, 'Intro Call', 30, 30, ?, 0, 1, 'public')`, etID, ownerID, slug, minNoticeMinutes); err != nil { t.Fatalf("seed event type: %v", err) } diff --git a/internal/handler/visibility.go b/internal/handler/visibility.go new file mode 100644 index 00000000..a53aed18 --- /dev/null +++ b/internal/handler/visibility.go @@ -0,0 +1,68 @@ +package handler + +// Visibility is how an event type is exposed. It replaces the old is_public boolean, +// which could only express "listed and bookable" vs "invisible and unbookable" and +// could not describe a link-only or credential-only type (#272). +// +// There is exactly one place that decides what a state means (this file); every +// surface asks these predicates rather than testing the raw string. That is the lesson +// from the destination-calendar bug in calselect.go: five separate checks of the same +// concept drift, and the drift is invisible until someone's booking lands in the wrong +// place. +type Visibility string + +const ( + // VisibilityPublic is listed in directories and bookable by anyone. + VisibilityPublic Visibility = "public" + // VisibilityUnlisted is hidden from directories but bookable by anyone with the link. + VisibilityUnlisted Visibility = "unlisted" + // VisibilityInternal is hidden from every public surface and bookable only by an + // authenticated caller. NOT YET SETTABLE: it needs optional authentication on the + // public booking/slots endpoints, which is step 2 (#269). The value exists now so + // the schema does not need a table rebuild when that lands. + VisibilityInternal Visibility = "internal" + // VisibilityPrivate is bookable by nobody. This is what is_public=false became. + VisibilityPrivate Visibility = "private" +) + +// parseVisibility maps a stored value to a state, failing closed: an unknown string is +// treated as private, so a corrupt or hand-edited row can never leak a booking page. +func parseVisibility(raw string) Visibility { + switch Visibility(raw) { + case VisibilityPublic, VisibilityUnlisted, VisibilityPrivate: + return Visibility(raw) + case VisibilityInternal: + // Known, but only meaningful once step 2 exists. Treat it as private until then + // rather than exposing a public surface that cannot honour it. + return VisibilityPrivate + default: + return VisibilityPrivate + } +} + +// Listed reports whether the event type appears in directories and discovery listings. +// Only public does; a link-only type must not be discoverable. +func (v Visibility) Listed() bool { return v == VisibilityPublic } + +// PublicBookable reports whether an anonymous request may fetch slots and book it. +func (v Visibility) PublicBookable() bool { + return v == VisibilityPublic || v == VisibilityUnlisted +} + +// Bookable reports whether a caller may book it, given whether that caller is +// authenticated. Step 1 has no authenticated path into the public booking endpoints, +// so no caller passes true yet; the signature exists so step 2 does not have to change +// every caller again. +func (v Visibility) Bookable(authenticated bool) bool { + if v == VisibilityInternal { + return authenticated + } + return v.PublicBookable() +} + +// settable reports whether the API may store this value. Internal is deliberately +// excluded until step 2: accepting it would let an operator select a state whose +// booking path does not exist, which fails silently at booking time. +func (v Visibility) settable() bool { + return v == VisibilityPublic || v == VisibilityUnlisted || v == VisibilityPrivate +} diff --git a/internal/handler/visibility_test.go b/internal/handler/visibility_test.go new file mode 100644 index 00000000..1bc3f3a3 --- /dev/null +++ b/internal/handler/visibility_test.go @@ -0,0 +1,69 @@ +package handler + +import "testing" + +// #272: one definition of what each state means. These predicates are what every +// surface calls, so a mistake here is a booking page or a directory listing that +// disagrees with the rest of the app. +func TestVisibilityPredicates(t *testing.T) { + cases := []struct { + v Visibility + listed bool + publicBookable bool + bookableAnon bool + bookableAuth bool + settable bool + }{ + {VisibilityPublic, true, true, true, true, true}, + {VisibilityUnlisted, false, true, true, true, true}, + {VisibilityPrivate, false, false, false, false, true}, + // internal is a known state but not selectable until step 2 (#269), and is + // treated as private for every public surface until then. + {VisibilityInternal, false, false, false, true, false}, + } + + for _, c := range cases { + if got := c.v.Listed(); got != c.listed { + t.Errorf("%s: Listed() = %v; want %v", c.v, got, c.listed) + } + if got := c.v.PublicBookable(); got != c.publicBookable { + t.Errorf("%s: PublicBookable() = %v; want %v", c.v, got, c.publicBookable) + } + if got := c.v.Bookable(false); got != c.bookableAnon { + t.Errorf("%s: Bookable(false) = %v; want %v", c.v, got, c.bookableAnon) + } + if got := c.v.Bookable(true); got != c.bookableAuth { + t.Errorf("%s: Bookable(true) = %v; want %v", c.v, got, c.bookableAuth) + } + if got := c.v.settable(); got != c.settable { + t.Errorf("%s: settable() = %v; want %v", c.v, got, c.settable) + } + } +} + +// Bookable(true) for internal is the one that has to be right when step 2 lands: it is +// the whole reason the state exists. +func TestVisibilityInternalIsBookableWhenAuthenticated(t *testing.T) { + v := VisibilityInternal + if !v.Bookable(true) { + t.Error("internal should be bookable by an authenticated caller") + } + if v.Listed() || v.PublicBookable() { + t.Error("internal must never be listed or publicly bookable") + } +} + +// A stored value nobody recognises must fail closed: an unknown string is private, not +// public. A corrupt row should hide a booking page, never expose one. +func TestParseVisibilityFailsClosed(t *testing.T) { + for _, raw := range []string{"", "nonsense", "Public", "PUBLIC", "unlisted ", "internal"} { + if got := parseVisibility(raw); got != VisibilityPrivate { + t.Errorf("parseVisibility(%q) = %q; want private", raw, got) + } + } + for _, raw := range []string{"public", "unlisted", "private"} { + if got := parseVisibility(raw); string(got) != raw { + t.Errorf("parseVisibility(%q) = %q; want %q", raw, got, raw) + } + } +} From 6abd5ceaa510c5d644d316986b44c4f8fbc5f67a Mon Sep 17 00:00:00 2001 From: Wynne Pirini Date: Tue, 1 Dec 2026 14:02:43 +1300 Subject: [PATCH 2/3] chore(db): renumber visibility migration to 00075 after main took 00074 --- ..._event_type_visibility.sql => 00075_event_type_visibility.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename internal/db/migrations/{00074_event_type_visibility.sql => 00075_event_type_visibility.sql} (100%) diff --git a/internal/db/migrations/00074_event_type_visibility.sql b/internal/db/migrations/00075_event_type_visibility.sql similarity index 100% rename from internal/db/migrations/00074_event_type_visibility.sql rename to internal/db/migrations/00075_event_type_visibility.sql From d0ed7a04628e8cb9f45b47cd39aed1436d43d98b Mon Sep 17 00:00:00 2001 From: Wynne Pirini Date: Wed, 2 Dec 2026 11:11:23 +1300 Subject: [PATCH 3/3] chore(db): renumber visibility migration to 00079 per the open queue #281 holds 00075, and the queue runs 00076 #283, 00077 #285, 00078 #286. This must merge after those, so it takes 00079. A lower number landing later leaves a gap and goose refuses to boot. --- CHANGELOG.md | 2 +- ...vent_type_visibility.sql => 00079_event_type_visibility.sql} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename internal/db/migrations/{00075_event_type_visibility.sql => 00079_event_type_visibility.sql} (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cbf0686..bc21529f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad - **API break: `is_public` is gone.** Event types now expose `visibility` (`public` | `unlisted` | `private`) instead of the `is_public` boolean, in both REST and MCP payloads. An external client reading `is_public` will get `undefined` and must - switch to `visibility`. Migration `00074` backfills `is_public = 0` to `private`, so + switch to `visibility`. Migration `00079` backfills `is_public = 0` to `private`, so event types that were unpublished stay unbookable — nothing becomes public by upgrading. A fourth value, `internal`, exists in the schema but cannot be set yet. diff --git a/internal/db/migrations/00075_event_type_visibility.sql b/internal/db/migrations/00079_event_type_visibility.sql similarity index 100% rename from internal/db/migrations/00075_event_type_visibility.sql rename to internal/db/migrations/00079_event_type_visibility.sql