diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 0856972d..8e4760cb 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -411,6 +411,8 @@ New public and assistant bookings recheck selected external calendars before com Google Meet and Teams event types can opt into `allow_phone_call`. Their booking page and widget then accept an optional `phone` value. A valid number selects a telephone appointment; leaving it empty preserves video. The booking stores its own location type so management pages, calendar retries, and paid confirmation do not generate a video link for a telephone appointment. Event duplication preserves the setting. +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. + `internal/booking/service.go` (transactions) + `internal/handler/booking_handler.go` (HTTP + async side effects). diff --git a/frontend/src/lib/i18n/en.json b/frontend/src/lib/i18n/en.json index d14b9130..f2e54b6e 100644 --- a/frontend/src/lib/i18n/en.json +++ b/frontend/src/lib/i18n/en.json @@ -1642,6 +1642,7 @@ "googleMeet": "Google Meet", "livekit": "Calnode Video (LiveKit)", "phone": "Phone call", + "phoneOutbound": "We call the attendee", "link": "Video link", "inPerson": "In person" }, @@ -1651,6 +1652,7 @@ "meetLink": "Meet link", "teamsLink": "Teams link", "phone": "Phone number", + "attendeePhone": "Attendee's phone number", "address": "Address", "details": "Details", "videoRoom": "Video room" @@ -1682,7 +1684,8 @@ "notConfigured": "Zoom isn't set up for this workspace (an admin can add it in Settings → Zoom),", "pasteFallback": "or paste a Zoom link below to use for every booking." }, - "livekit": "A secure video room is created automatically for each booking — no link needed. Guests join in the browser. (Set up the server in Settings → Video.)" + "livekit": "A secure video room is created automatically for each booking — no link needed. Guests join in the browser. (Set up the server in Settings → Video.)", + "phoneOutbound": "The booking form asks the attendee for their phone number (required). You call them at the booked time; the number is the booking's location, so it's in the calendar event and emails as a tap-to-call link." } }, "invite": { diff --git a/frontend/src/lib/i18n/fr.json b/frontend/src/lib/i18n/fr.json index 46ca13d0..6da25076 100644 --- a/frontend/src/lib/i18n/fr.json +++ b/frontend/src/lib/i18n/fr.json @@ -1642,6 +1642,7 @@ "googleMeet": "Google Meet", "livekit": "Calnode Video (LiveKit)", "phone": "Appel téléphonique", + "phoneOutbound": "Nous appelons le participant", "link": "Lien vidéo", "inPerson": "En personne" }, @@ -1651,6 +1652,7 @@ "meetLink": "Lien Meet", "teamsLink": "Lien Teams", "phone": "Numéro de téléphone", + "attendeePhone": "Numéro de téléphone du participant", "address": "Adresse", "details": "Détails", "videoRoom": "Salle vidéo" @@ -1682,7 +1684,8 @@ "notConfigured": "Zoom n'est pas configuré pour cet espace de travail (un administrateur peut l'ajouter dans Paramètres → Zoom),", "pasteFallback": "ou collez un lien Zoom ci-dessous à utiliser pour chaque réservation." }, - "livekit": "Une salle vidéo sécurisée est créée automatiquement pour chaque réservation — aucun lien n'est nécessaire. Les invités rejoignent dans le navigateur. (Configurez le serveur dans Paramètres → Vidéo.)" + "livekit": "Une salle vidéo sécurisée est créée automatiquement pour chaque réservation — aucun lien n'est nécessaire. Les invités rejoignent dans le navigateur. (Configurez le serveur dans Paramètres → Vidéo.)", + "phoneOutbound": "Le formulaire de réservation demande au participant son numéro de téléphone (obligatoire). Vous l'appelez à l'heure réservée ; le numéro est le lieu de la réservation et figure dans l'événement d'agenda et les e-mails sous forme de lien cliquable." } }, "invite": { diff --git a/frontend/src/routes/event-types/[slug]/+page.svelte b/frontend/src/routes/event-types/[slug]/+page.svelte index 6f5c49eb..84e6f5d4 100644 --- a/frontend/src/routes/event-types/[slug]/+page.svelte +++ b/frontend/src/routes/event-types/[slug]/+page.svelte @@ -29,6 +29,7 @@ { value: 'google_meet', label: $t('eventTypeEditor.location.types.googleMeet') }, { value: 'livekit', label: $t('eventTypeEditor.location.types.livekit') }, { value: 'phone', label: $t('eventTypeEditor.location.types.phone') }, + { value: 'phone_outbound', label: $t('eventTypeEditor.location.types.phoneOutbound') }, { value: 'link', label: $t('eventTypeEditor.location.types.link') }, { value: 'in_person', label: $t('eventTypeEditor.location.types.inPerson') }, ]); @@ -399,7 +400,8 @@ invite_delivery: form.invite_delivery, allow_phone_call: allowPhoneCall, location_type: form.location_type, - location_value: form.location_value.trim() || null, + // "We'll call you" has no host-side value: the attendee gives their number at booking. + location_value: form.location_type === 'phone_outbound' ? null : form.location_value.trim() || null, buffer_before_minutes: Number(form.buffer_before_minutes), buffer_after_minutes: Number(form.buffer_after_minutes), min_notice_minutes: Number(form.min_notice_minutes), @@ -763,6 +765,11 @@

{/if} + {:else if form.location_type === 'phone_outbound'} + +

+ {$t('eventTypeEditor.location.hint.phoneOutbound')} +

{:else if form.location_type === 'livekit'}

diff --git a/internal/db/migrations/00073_phone_outbound_location.sql b/internal/db/migrations/00073_phone_outbound_location.sql new file mode 100644 index 00000000..2948b49f --- /dev/null +++ b/internal/db/migrations/00073_phone_outbound_location.sql @@ -0,0 +1,91 @@ +-- +goose NO TRANSACTION +-- 'phone_outbound' location type: the host calls the attendee. The booking form asks +-- the attendee for a required phone number, and the booking is stored exactly like the +-- allow_phone_call path (bookings.location_type = 'phone', location_value = 'tel:'), +-- so tap-to-call, the calendar event location and the emails work unchanged. Only the +-- event type carries the new value; bookings.location_type has no CHECK. +-- +-- Widening the location_type CHECK is the 00042 table rebuild: NO TRANSACTION + +-- foreign_keys=OFF, because a DROP TABLE with foreign keys enabled would cascade-delete +-- the child rows (bookings, hosts, questions, reminders, availability rules), and PRAGMA +-- foreign_keys is a no-op inside a transaction. Columns are named explicitly, in the +-- table's current order (the ones added by ALTER after 00042 sit at the end). + +-- +goose Up +PRAGMA foreign_keys=OFF; + +CREATE TABLE event_types_new ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + team_id TEXT REFERENCES teams(id) ON DELETE SET NULL, + slug TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + description TEXT, + duration_minutes INTEGER NOT NULL, + slot_interval_minutes INTEGER NOT NULL DEFAULT 30, + location_type TEXT NOT NULL DEFAULT 'link' + CHECK (location_type IN ('zoom','google_meet','teams','custom_video','phone','in_person','link','livekit','phone_outbound')), + location_value TEXT, + routing_mode TEXT NOT NULL DEFAULT 'fixed' + CHECK (routing_mode IN ('fixed', 'round_robin', 'collective', 'priority')), + buffer_before_minutes INTEGER NOT NULL DEFAULT 0, + buffer_after_minutes INTEGER NOT NULL DEFAULT 0, + min_notice_minutes INTEGER NOT NULL DEFAULT 0, + max_future_days INTEGER NOT NULL DEFAULT 60, + seat_limit INTEGER NOT NULL DEFAULT 1, + is_active INTEGER NOT NULL DEFAULT 1, + is_public INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')), + msg_confirmation TEXT, + msg_cancellation TEXT, + msg_reschedule TEXT, + msg_reminder TEXT, + max_active_bookings INTEGER NOT NULL DEFAULT 1, + rr_strategy TEXT NOT NULL DEFAULT 'even' + CHECK (rr_strategy IN ('even', 'soonest', 'priority')), + subj_confirmation TEXT, + subj_cancellation TEXT, + subj_reschedule TEXT, + subj_reminder TEXT, + price_cents INTEGER NOT NULL DEFAULT 0, + currency TEXT NOT NULL DEFAULT 'usd', + archived_at TEXT, + msg_greeting TEXT, + show_taken_slots INTEGER NOT NULL DEFAULT 0, + allow_phone_call INTEGER NOT NULL DEFAULT 0, + display_order INTEGER NOT NULL DEFAULT 0, + invite_delivery TEXT NOT NULL DEFAULT 'calendar' + CHECK (invite_delivery IN ('calendar', 'calnode', 'none')) +); + +INSERT INTO event_types_new ( + id, user_id, team_id, slug, name, description, duration_minutes, slot_interval_minutes, + location_type, location_value, routing_mode, buffer_before_minutes, buffer_after_minutes, + min_notice_minutes, max_future_days, seat_limit, is_active, is_public, created_at, + msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, max_active_bookings, + rr_strategy, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, + price_cents, currency, archived_at, msg_greeting, show_taken_slots, allow_phone_call, + display_order, invite_delivery) +SELECT + id, user_id, team_id, slug, name, description, duration_minutes, slot_interval_minutes, + location_type, location_value, routing_mode, buffer_before_minutes, buffer_after_minutes, + min_notice_minutes, max_future_days, seat_limit, is_active, is_public, created_at, + msg_confirmation, msg_cancellation, msg_reschedule, msg_reminder, max_active_bookings, + rr_strategy, subj_confirmation, subj_cancellation, subj_reschedule, subj_reminder, + price_cents, currency, archived_at, msg_greeting, show_taken_slots, allow_phone_call, + display_order, invite_delivery +FROM event_types; + +DROP TABLE event_types; +ALTER TABLE event_types_new RENAME TO event_types; + +PRAGMA foreign_keys=ON; + +-- +goose Down +-- The widened CHECK stays (as in 00042 and 00071). An older binary does not know +-- 'phone_outbound', so those event types become 'phone' with no host number and are +-- deactivated: still a phone call, never silently a video meeting, and not bookable +-- until the operator enters a number (validateLocation requires one for 'phone'). +-- Existing bookings are unaffected: they were stored as 'phone' + 'tel:'. +UPDATE event_types SET location_type = 'phone', location_value = NULL, is_active = 0 +WHERE location_type = 'phone_outbound'; diff --git a/internal/handler/book.go b/internal/handler/book.go index 3f80ee42..7bddd295 100644 --- a/internal/handler/book.go +++ b/internal/handler/book.go @@ -44,7 +44,10 @@ type bookQuestion struct { } type bookPageData struct { - PhoneChoice bool + PhoneChoice bool + // PhoneRequired is the "we'll call you" location: the same phone field, but required, + // because the attendee's number is the only way the host can reach them. + PhoneRequired bool AccentColor string AccentForeground string Slug string @@ -311,6 +314,8 @@ func locationLabel(locType, locValue string, loc *i18n.Locale) string { return loc.T("location_video_meeting") case "phone": return loc.T("location_phone") + case phoneOutboundLocation: + return loc.T("location_phone_outbound") case "in_person": if locValue != "" { return locValue @@ -420,6 +425,7 @@ func (h *Handler) PublicEventType(w http.ResponseWriter, r *http.Request) { "duration_label": durationLabel(durMins, loc), "location_type": locType, "allow_phone_call": allowPhoneCall && onlineMeetingLocation(locType), + "phone_required": locType == phoneOutboundLocation, "booking_accent": accentColor, "booking_accent_foreground": accentForeground(accentColor), "location_label": locationLabel(locType, locValue, loc), @@ -430,7 +436,9 @@ func (h *Handler) PublicEventType(w http.ResponseWriter, r *http.Request) { // would leave it rebuilding a plural-aware label the server already has (#20). "min_notice_minutes": minNotice, "min_notice_label": noticeLabel(minNotice, loc), - "assistant_enabled": h.getLLM() != nil, + // The assistant cannot collect the attendee's number, so it is off for "we'll call + // you" event types rather than offered and then refused at the last step. + "assistant_enabled": h.getLLM() != nil && locType != phoneOutboundLocation, "assistant_greeting": assistantGreeting(msgGreeting, loc), "price_cents": priceCents, "currency": currency, @@ -537,6 +545,7 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { data := bookPageData{ PhoneChoice: allowPhoneCall && onlineMeetingLocation(locType), + PhoneRequired: locType == phoneOutboundLocation, AccentColor: accentColor, AccentForeground: accentForeground(accentColor), Slug: slug, @@ -561,7 +570,7 @@ func (h *Handler) BookPage(w http.ResponseWriter, r *http.Request) { MaxFutureDays: maxDays, Questions: questions, BookingLogicJS: template.JS(bookingLogicJS), // #nosec G203 -- our own bundled JS source constant, not user input - AssistantEnabled: h.getLLM() != nil, + AssistantEnabled: h.getLLM() != nil && locType != phoneOutboundLocation, AssistantDisclosure: loc.T("assistant_disclosure"), AssistantGreeting: assistantGreeting(msgGreeting, loc), CSSVersion: bookingCSSVersion, diff --git a/internal/handler/book_test.go b/internal/handler/book_test.go index 99cf6260..d7be13a2 100644 --- a/internal/handler/book_test.go +++ b/internal/handler/book_test.go @@ -146,6 +146,7 @@ func TestBookPage_locationLabels(t *testing.T) { {"google_meet", "https://meet.google.com/abc-defg-hij", "Google Meet"}, {"teams", "https://teams.microsoft.com/l/meetup-join/x", "Microsoft Teams"}, {"phone", "+1 555 123 4567", "Phone Call"}, + {"phone_outbound", "", "Phone Call (we"}, // the attendee gives the number at booking {"in_person", "123 Main St", "123 Main St"}, {"in_person", "", "In Person"}, // in-person value stays optional {"custom_video", "https://example.com/room", "Video Call"}, diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index 74b51170..509fa9d7 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -72,6 +72,12 @@ func onlineMeetingLocation(locType string) bool { return locType == "google_meet" || locType == "teams" } +// phoneOutboundLocation is the event-type location where the host calls the attendee. +// It exists only on the event type: every booking on it requires the attendee's number +// and is stored as location_type "phone" with "tel:", the same shape as the +// allow_phone_call path, so everything downstream of the booking treats it as a phone call. +const phoneOutboundLocation = "phone_outbound" + // providerMintsPlatform reports whether a connected calendar provider can natively // auto-generate the meeting link for the given online location type: Google Meet // only from a Google calendar, Microsoft Teams only from a Microsoft calendar. When @@ -223,6 +229,9 @@ func (h *Handler) validateLocation(ctx context.Context, ownerID, locType string, return fmt.Errorf("enter a valid phone number") } return nil + case phoneOutboundLocation: + // The attendee supplies the number at booking time; the event type needs none. + return nil default: // in_person and anything else: no value requirement return nil } @@ -481,6 +490,11 @@ var errNoHostAvailable = errors.New("no active host can take this booking") // only be booked through the Stripe Checkout flow on the booking page (agents can't pay). var errPaymentRequired = errors.New("this event requires payment; please book on the booking page") +// errPhoneRequired is returned by the shared booking core for "we'll call you" event types: +// the assistant and MCP have no way to collect the attendee's number, and booking without +// one would leave the host with nobody to call. +var errPhoneRequired = errors.New("this event requires the attendee's phone number; please book on the booking page") + // bookableEventType is the event_types fields the booking-creation and slot-computation // paths need. loadBookableEventType is their one shared query — createBookingForSlug, // CreateBooking, and computeSlots each used to hand-write their own column subset, which @@ -568,6 +582,9 @@ func (h *Handler) createBookingForSlug(ctx context.Context, slug string, startAt if et.PriceCents > 0 { return nil, errPaymentRequired } + if et.LocationType == phoneOutboundLocation { + return nil, errPhoneRequired + } // The attendee's own locale (set by the assistant from the page's resolved language; // empty for MCP callers, which i18n.Get turns into nil → English). answers, err := h.validateAnswersCore(ctx, et.ID, rawAnswers, i18n.Get(organizer.Locale)) @@ -899,7 +916,21 @@ func (h *Handler) CreateBooking(w http.ResponseWriter, r *http.Request) { // Resolve candidate hosts by routing mode: rotation hosts for round-robin, // required hosts otherwise. Archived hosts are excluded by resolveEventTypeHosts. req.Phone = strings.TrimSpace(req.Phone) - if req.Phone != "" { + switch { + case et.LocationType == phoneOutboundLocation: + // The host calls the attendee, so the number is required. A missing or invalid one + // is refused, never downgraded to another meeting type. + if req.Phone == "" { + h.writeError(w, http.StatusBadRequest, loc.T("err_phone_required")) + return + } + if len(req.Phone) > 40 || !validPhone(req.Phone) { + h.writeError(w, http.StatusBadRequest, "invalid telephone number") + return + } + et.LocationType = "phone" + locValue = "tel:" + req.Phone + case req.Phone != "": if !et.AllowPhoneCall || !onlineMeetingLocation(et.LocationType) || len(req.Phone) > 40 || !validPhone(req.Phone) { h.writeError(w, http.StatusBadRequest, "invalid telephone number") return diff --git a/internal/handler/booking_phone_outbound_test.go b/internal/handler/booking_phone_outbound_test.go new file mode 100644 index 00000000..9951f384 --- /dev/null +++ b/internal/handler/booking_phone_outbound_test.go @@ -0,0 +1,162 @@ +package handler_test + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + + "github.com/calnode/calnode/internal/calendar" +) + +// TestBookingPhoneOutbound covers the "we'll call you" location: the attendee's number is +// required, a valid one is stored exactly like the allow_phone_call path (location_type +// "phone", "tel:"), and a missing or invalid one is refused rather than downgraded +// to a Meet. A Google calendar that could mint a Meet link is connected on purpose, so a +// silent fallback to video would show up here. +func TestBookingPhoneOutbound(t *testing.T) { + for _, tc := range []struct { + name, phone string + status int + }{ + {"valid", "+48 600 100 200", http.StatusCreated}, + {"missing", "", http.StatusBadRequest}, + {"blank", " ", http.StatusBadRequest}, + {"invalid", "call me", http.StatusBadRequest}, + {"too long", "+48 " + strings.Repeat("1", 40), http.StatusBadRequest}, + } { + t.Run(tc.name, func(t *testing.T) { + h, db, key, userID := setupWorkspaceWithDB(t) + slug, _ := seedEventTypeHTTP(t, h, key) + // Through the API, so validateLocation and the widened CHECK are both exercised: + // the type needs no host number. + if code, out := patchET(t, h, key, slug, `{"location_type":"phone_outbound"}`); code != http.StatusOK { + t.Fatalf("set phone_outbound: %d %v", code, out) + } + if _, err := db.Exec(`INSERT INTO calendar_connections (id,user_id,provider,access_token_enc,calendar_id,is_destination) VALUES ('conn',?,'google','test','primary',1)`, userID); err != nil { + t.Fatal(err) + } + p := telephoneCalendar{events: make(chan calendar.CreateEventParams, 1)} + svc := calendar.NewService(db) + svc.Register(p) + h.SetCalendar(svc) + + body := fmt.Sprintf(`{"event_type_slug":%q,"start_at":"2026-06-15T09:00:00Z","name":"Test","email":"test@example.com","phone":%q}`, slug, tc.phone) + rec := httptest.NewRecorder() + h.CreateBooking(rec, httptest.NewRequest(http.MethodPost, "/v1/bookings", strings.NewReader(body))) + if rec.Code != tc.status { + t.Fatalf("status %d: %s", rec.Code, rec.Body) + } + if tc.status != http.StatusCreated { + var count int + if err := db.QueryRow(`SELECT COUNT(*) FROM bookings`).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 0 { + t.Fatalf("a %s number created a booking instead of being refused", tc.name) + } + return + } + + var response struct { + ID string `json:"id"` + LocationType string `json:"location_type"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil { + t.Fatal(err) + } + want := "tel:" + tc.phone + var locType, locValue string + if err := db.QueryRow(`SELECT location_type, location_value FROM bookings WHERE id = ?`, response.ID).Scan(&locType, &locValue); err != nil { + t.Fatal(err) + } + if response.LocationType != "phone" || locType != "phone" || locValue != want { + t.Fatalf("booking location: response %q, stored %q %q; want phone %q", response.LocationType, locType, locValue, want) + } + select { + case event := <-p.events: + if event.AddMeet || event.Location != want { + t.Fatalf("calendar AddMeet=%v location=%q; want no Meet and %q", event.AddMeet, event.Location, want) + } + case <-time.After(3 * time.Second): + t.Fatal("calendar event was not created") + } + }) + } +} + +// TestBookPage_phoneOutboundRequiresNumber checks that the booking page and the widget's +// event-type info both mark the number as required, and that the assistant (which cannot +// collect it) is off. +func TestBookPage_phoneOutboundRequiresNumber(t *testing.T) { + h, _, key, _ := setupWorkspaceWithDB(t) + slug, _ := seedEventTypeHTTP(t, h, key) + if code, out := patchET(t, h, key, slug, `{"location_type":"phone_outbound"}`); code != http.StatusOK { + t.Fatalf("set phone_outbound: %d %v", code, out) + } + + req := httptest.NewRequest(http.MethodGet, "/book/"+slug, nil) + req.SetPathValue("slug", slug) + rec := httptest.NewRecorder() + h.BookPage(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("BookPage: %d", rec.Code) + } + page := rec.Body.String() + if !strings.Contains(page, `data-phone-required="true"`) || !strings.Contains(page, `id="f-phone"`) { + t.Error("booking page has no required phone field") + } + + req = httptest.NewRequest(http.MethodGet, "/v1/event-types/"+slug+"/public", nil) + req.SetPathValue("slug", slug) + rec = httptest.NewRecorder() + h.PublicEventType(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("PublicEventType: %d %s", rec.Code, rec.Body) + } + var info struct { + PhoneRequired bool `json:"phone_required"` + AllowPhoneCall bool `json:"allow_phone_call"` + LocationType string `json:"location_type"` + AssistantEnabled bool `json:"assistant_enabled"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &info); err != nil { + t.Fatal(err) + } + if !info.PhoneRequired || info.AllowPhoneCall || info.LocationType != "phone_outbound" || info.AssistantEnabled { + t.Errorf("public info = %+v; want phone_required, not allow_phone_call, assistant off", info) + } +} + +// TestMCP_createBooking_phoneOutboundRefused: MCP has no way to pass the attendee's number, +// so the shared booking core refuses instead of creating a call nobody can make. +func TestMCP_createBooking_phoneOutboundRefused(t *testing.T) { + h, apiKey, _ := setupWorkspace(t) + body := `{"slug":"mcp-we-call","name":"We call you","duration_minutes":30,"location_type":"phone_outbound","max_future_days":0}` + rec := httptest.NewRecorder() + h.RequireAuth(h.CreateEventType)(rec, authReq(http.MethodPost, "/v1/event-types", body, apiKey)) + if rec.Code != http.StatusCreated { + t.Fatalf("create event type: %d — %s", rec.Code, rec.Body.String()) + } + seedFullAvailability(t, h, apiKey) + + cs := connectMCP(t, h) + res, err := cs.CallTool(context.Background(), &mcp.CallToolParams{Name: "create_booking", Arguments: map[string]any{ + "event_type_id": "mcp-we-call", + "slot_start": "2027-01-15T10:00:00Z", + "attendee_name": "Pat Booker", + "attendee_email": "pat@example.com", + }}) + if err != nil { + t.Fatalf("create_booking: %v", err) + } + if !res.IsError { + t.Fatalf("create_booking on a phone_outbound event type succeeded: %+v", res.Content) + } +} diff --git a/internal/handler/embed.js b/internal/handler/embed.js index 33d258e5..a9fa9285 100644 --- a/internal/handler/embed.js +++ b/internal/handler/embed.js @@ -620,7 +620,15 @@ form.appendChild(el('div', { class: 'field' }, [el('label', { text: t(this.i18n, 'name_label') }), name])); form.appendChild(el('div', { class: 'field' }, [el('label', { text: t(this.i18n, 'email_label') }), email])); var phone = el('input', { type: 'tel', maxlength: '40', autocomplete: 'tel', id: 'phone-call-number' }); - if (this.info.allow_phone_call) form.appendChild(el('div', { class: 'field' }, [el('label', { for: 'phone-call-number', text: t(this.i18n, 'phone_call_number') }), phone])); + // "We'll call you" event types require the number; the optional allow_phone_call + // field keeps its own label. Same rule as book.html, checked again on the server. + var phoneRequired = !!this.info.phone_required; + if (phoneRequired) { + phone.required = true; + form.appendChild(el('div', { class: 'field' }, [el('label', { for: 'phone-call-number', html: esc(t(this.i18n, 'phone_outbound_number')) + ' *' }), phone])); + } else if (this.info.allow_phone_call) { + form.appendChild(el('div', { class: 'field' }, [el('label', { for: 'phone-call-number', text: t(this.i18n, 'phone_call_number') }), phone])); + } var qInputs = []; this.questions.forEach(function (q) { var inp, field; @@ -649,6 +657,10 @@ form.addEventListener('submit', function (e) { e.preventDefault(); errBox.textContent = ''; + if (phoneRequired && !phone.value.trim()) { + errBox.textContent = t(self.i18n, 'required_fields_error'); + return; + } cta.disabled = true; cta.textContent = t(self.i18n, 'confirming'); var answers = []; qInputs.forEach(function (x) { diff --git a/internal/handler/embed_handler_test.go b/internal/handler/embed_handler_test.go index ca626070..68017493 100644 --- a/internal/handler/embed_handler_test.go +++ b/internal/handler/embed_handler_test.go @@ -121,3 +121,25 @@ func TestEmbedJS_identityPrefill(t *testing.T) { t.Error("identity fields use disabled, which removes them from the tab order; use readonly") } } + +// TestEmbedJS_phoneOutboundRequired pins the widget half of the "we'll call you" location: +// the widget builds its own form, so the required number field and its client-side check +// live here separately from book.html. The server refuses a missing number either way +// (TestBookingPhoneOutbound); this keeps the widget from offering a form that can only fail. +func TestEmbedJS_phoneOutboundRequired(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{ + `this.info.phone_required`, + `phone.required = true`, + `'phone_outbound_number'`, + `if (phoneRequired && !phone.value.trim())`, + } { + if !strings.Contains(body, want) { + t.Errorf("embed.js no longer contains %q - the required phone field may have regressed", want) + } + } +} diff --git a/internal/handler/templates/book.html b/internal/handler/templates/book.html index 3de3207f..dbce7454 100644 --- a/internal/handler/templates/book.html +++ b/internal/handler/templates/book.html @@ -211,7 +211,12 @@

{{.Name}}

.ID is the event type's own intake-question primary key (admin-configured, not attacker-controlled at booking time), and Go's html/template context-aware-escapes every {{.ID}} below regardless — there is no raw/unescaped output here. */}} - {{if .PhoneChoice}} + {{if .PhoneRequired}} +
+ + +
+ {{else if .PhoneChoice}}
@@ -685,6 +690,12 @@

{{call .T "booking_confirmed"}}

errEl.textContent = t('required_fields_error'); return; } + // "We'll call you" event types: the number is required (the server refuses without it). + const phoneEl = form.elements.phone; + if (phoneEl && phoneEl.dataset.phoneRequired === 'true' && !phoneEl.value.trim()) { + errEl.textContent = t('required_fields_error'); + return; + } // Collect intake question answers and validate required fields. const answers = []; diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 006489fb..b268bdec 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -63,6 +63,7 @@ "duration_hr_min": "%d hr %d min", "location_video_meeting": "Video meeting", "location_phone": "Phone Call", + "location_phone_outbound": "Phone Call (we'll call you)", "location_in_person": "In Person", "location_video_call": "Video Call", @@ -169,6 +170,8 @@ "time_afternoon": "Afternoon", "time_evening": "Evening", "phone_call_number": "Phone number (optional, for a phone call)", + "phone_outbound_number": "Your phone number (we'll call you)", + "err_phone_required": "Please enter your phone number so we can call you.", "calendar_degraded_notice": "Some calendar information couldn't be loaded, so availability may be incomplete.", "directory_book": "Book", diff --git a/internal/i18n/locales/pl.json b/internal/i18n/locales/pl.json index e6f7fcc8..d7e95fcc 100644 --- a/internal/i18n/locales/pl.json +++ b/internal/i18n/locales/pl.json @@ -61,6 +61,7 @@ "duration_hr_min": "%d godz. %d min", "location_video_meeting": "Spotkanie wideo", "location_phone": "Rozmowa telefoniczna", + "location_phone_outbound": "Rozmowa telefoniczna (zadzwonimy do Ciebie)", "location_in_person": "Osobiście", "location_video_call": "Połączenie wideo", "manage_booking_title": "Zarządzaj rezerwacją", @@ -162,6 +163,8 @@ "time_afternoon": "Po południu", "time_evening": "Wieczór", "phone_call_number": "Numer telefonu (opcjonalnie, w przypadku rozmowy telefonicznej)", + "phone_outbound_number": "Twój numer telefonu (zadzwonimy do Ciebie)", + "err_phone_required": "Podaj numer telefonu, abyśmy mogli do Ciebie zadzwonić.", "calendar_degraded_notice": "Nie udało się załadować części danych kalendarza, dlatego informacje o dostępności mogą być niepełne.", "directory_book": "Zarezerwuj", "directory_empty": "Brak dostępnych wydarzeń do zarezerwowania.",