diff --git a/CHANGELOG.md b/CHANGELOG.md index f8f99a5f..f0b04ddf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,17 @@ exact tag (`ghcr.io/calnode/calnode:0.1.0`) if you need stability between upgrad matters for this release — verifies the key file is persisted and that a restart unwraps the existing data key rather than generating a new one. On a publish it pulls the exact digest the build job produced, so it cannot pass against a stale tag. +- **Calendar invites can be left to your own system.** *Calendar invite → Sent by* gains a + third choice, *No one*. Hosts still get the meeting, with its Meet/Teams link, on their + own calendar, but the booker is not a guest there, so their calendar provider sends no + invite, and Calnode attaches none to its emails. For setups that send their own + confirmation and invite. It needs no email setup; if email is set up, the booker's + confirmation, reschedule and cancellation emails still go out, without an invite. + Existing bookings keep the way they were invited. +- **Bookings say how their invite was sent.** The booking JSON (`GET /v1/bookings`, + `GET /v1/bookings/{id}` and the MCP tools) now includes `invite_delivery` (`calendar`, + `calnode` or `none`), and webhooks can add it as a payload field. It is not in the + default field set, so existing webhooks are unchanged. ## [0.11.2] - 2026-10-28 diff --git a/README.md b/README.md index 65102b39..b9db471f 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,7 @@ domains, Resend email, Google & Microsoft OAuth, Litestream backups, troubleshoo - **CalDAV calendars** — iCloud / Fastmail / Nextcloud via app-password (free/busy + event write-back) - Public booking + self-serve **reschedule/cancel** via signed manage links - HTML branded email (logo, banner, business name, size/opacity) with add-to-calendar links +- Per-event-type **calendar invite sender**: the host's calendar, Calnode from your workspace address, or no one (your own system sends it) - REST API (88 endpoints) + API keys; **HMAC webhooks** with per-webhook payloads + delivery log - **Native MCP server** (10 tools incl. meeting notes + transcript; stdio via `calnode mcp` + Streamable HTTP at `/mcp`) - **Conversational booking** ("Book by chat" on the booking page + embed widget; BYO-LLM, off by default) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9e28f781..8245fbd6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -564,10 +564,24 @@ instance sender from Settings → Email (`applyInviteDelivery`, `BookingData.Hid No sender address means no `ORGANIZER` line, never a fallback to the host. Host copies keep the host as organizer and, for a `calnode` booking, leave the booker out entirely and go out as `METHOD:PUBLISH` (`applyHostInvite`, `ICSWithoutAttendee`), so no host calendar holds them as -a guest it could re-invite. Reschedule, cancel, reassign and the reconciler read the mode from -the **booking**, not the event type, so a booking is always updated through the channel -its invite went out on. Switching an event type to `calnode` requires email to be set up -(validated on change). +a guest it could re-invite. `none` (migration 00071) is for integrations that deliver the +invite themselves: the hosts' events are written guestless exactly as for `calnode` +(`hostEventsGuestless`) and host copies behave the same, but no Calnode email to the booker +carries an `.ics`, whatever the host's calendar (`applyInviteDelivery`). The booker's emails +themselves still go out when email is set up; whether Calnode emails at all stays with the +mailer and the notification settings. Reschedule, cancel, reassign and the reconciler read +the mode from the **booking**, not the event type, so a booking is always updated through +the channel its invite went out on. Switching an event type to `calnode` requires email to +be set up (validated on change); `none` does not. The booking JSON carries the mode as +`invite_delivery`, and webhooks can select it as a payload field (not in the default set), +so an integration can tell per booking whether the booker already holds an invite. + +00071 widened the 00068 `CHECK` without a table rebuild: SQLite cannot alter a `CHECK`, and +rebuilding `bookings` would mean carrying its foreign-key children and the double-booking +index through a `NO TRANSACTION` migration (compare 00042, which rebuilt only +`event_types`). Because the `CHECK` belongs to the `invite_delivery` column alone, the +migration adds a widened copy, fills it, drops the old column and renames the copy, inside +goose's normal transaction. The column now sits last in both tables. **RSVPs to Calnode-sent invites (migration 00069, `rsvp_inbound.go`).** A booker's Yes/No/Maybe is an iTIP `REPLY` their mail client emails to the invite's `ORGANIZER`. Each @@ -794,7 +808,8 @@ as the desired state: - **Per-webhook payload fields:** each webhook chooses which fields land in the `data` object (`webhooks.fields` JSON, migration 00027) — incl. attendee PII + intake answers. NULL ⇒ the original default set (so existing webhooks are unchanged and - never start leaking PII). The payload is enriched (`enrich`) + filtered per-webhook + never start leaking PII; fields added later that every booking carries, such as + `invite_delivery`, stay out of that set for the same reason). The payload is enriched (`enrich`) + filtered per-webhook (`buildData`) at enqueue time, so each subscriber gets its own `data`. New webhooks default to all fields ticked (self-hoster unticks what they don't want); a delivery-log view (status/HTTP/attempts) is in the admin webhooks page. diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 5a121d77..4ee4d93a 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -41,8 +41,9 @@ export type EventType = { show_taken_slots: 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. */ - invite_delivery: 'calendar' | 'calnode'; + * in Settings → Email, so no host's personal address reaches the booker. 'none': no + * invite from either; the hosts' events are guestless, for integrations that send their own. */ + invite_delivery: 'calendar' | 'calnode' | 'none'; /** Whether Calnode can currently send invites (a sender and working email). Only * returned on the single event type GET. */ invite_sender_ready?: boolean; @@ -114,6 +115,8 @@ export type Booking = { amount_paid_currency?: string; /** The booker's RSVP to a Calnode-sent invite; absent until an answer arrives. */ rsvp_status?: 'accepted' | 'declined' | 'tentative'; + /** Who sent the booker's calendar invite, fixed when the booking was made. */ + invite_delivery?: 'calendar' | 'calnode' | 'none'; }; export type APIKey = { diff --git a/frontend/src/routes/event-types/[slug]/+page.svelte b/frontend/src/routes/event-types/[slug]/+page.svelte index 28544571..a04054db 100644 --- a/frontend/src/routes/event-types/[slug]/+page.svelte +++ b/frontend/src/routes/event-types/[slug]/+page.svelte @@ -43,6 +43,7 @@ const INVITE_DELIVERY = [ { value: 'calendar', label: "The host's calendar" }, { value: 'calnode', label: 'Calnode, from your workspace' }, + { value: 'none', label: 'No one (you send your own)' }, ]; // ── Event type ─────────────────────────────────────────────────────────────── @@ -746,6 +747,9 @@ Invitees get the invite from your workspace's email sender (Settings → Email), never from a host's own address. Hosts still see the meeting on their own calendar, with the meeting link. + {:else if form.invite_delivery === 'none'} + Neither the host's calendar nor Calnode sends the booker an invite, for when your own + system does. Hosts still see the meeting on their own calendar, with the meeting link. {:else} The host's connected calendar invites the booker, so the invite shows the host's own email address. Choose Calnode to keep hosts' addresses private or to book as a team. diff --git a/frontend/src/routes/webhooks/+page.svelte b/frontend/src/routes/webhooks/+page.svelte index 1dc67e78..2265ff21 100644 --- a/frontend/src/routes/webhooks/+page.svelte +++ b/frontend/src/routes/webhooks/+page.svelte @@ -39,6 +39,7 @@ { key: 'previous_start_at', label: 'Previous start (reschedule)' }, { key: 'previous_end_at', label: 'Previous end (reschedule)' }, { key: 'rsvp_status', label: 'RSVP answer (booking.rsvp)' }, + { key: 'invite_delivery', label: 'Invite sent by (calendar, calnode, none)' }, ] }, { group: 'Payment', fields: [ { key: 'payment_status', label: 'Payment status' }, diff --git a/internal/booking/booking.go b/internal/booking/booking.go index cbd33fe6..1df41ebc 100644 --- a/internal/booking/booking.go +++ b/internal/booking/booking.go @@ -19,7 +19,7 @@ var ( ) // Who sends a booking's calendar invite to the booker (event_types/bookings.invite_delivery, -// migration 00068). +// migrations 00068 and 00071). const ( // InviteByCalendar: the booker is a guest on each host's calendar event, and the host's // provider (Google, Microsoft) emails the invite from the host's own account. @@ -27,6 +27,10 @@ const ( // InviteByCalnode: the hosts' events are created without guests, and Calnode sends the // invite itself, organized by the instance's sender identity instead of any one host. InviteByCalnode = "calnode" + // InviteByNone: the hosts' events are created without guests, as for InviteByCalnode, + // but Calnode attaches no invite either. For integrations that deliver the invite + // themselves; with Calnode's own email set up, the booker's emails still go out. + InviteByNone = "none" ) // Booking is a confirmed or cancelled appointment. @@ -48,8 +52,8 @@ type Booking struct { // ConfirmFailed reports whether the initial confirmation email failed (after // retry). Operator-visible via the booking JSON; see migration 00064. ConfirmFailed bool - // InviteDelivery is who sent this booking's invite (InviteByCalendar/InviteByCalnode), - // fixed at creation; reschedule, cancel and reassign follow it. + // InviteDelivery is who sent this booking's invite (InviteByCalendar/InviteByCalnode/ + // InviteByNone), fixed at creation; reschedule, cancel and reassign follow it. InviteDelivery string } @@ -108,7 +112,8 @@ type CreateParams struct { MaxBookingsPerHour int // InviteDelivery records who sends the booker's calendar invite for this booking: // InviteByCalendar (the hosts' connected calendars; the default when empty) or - // InviteByCalnode (Calnode's own .ics, with the hosts' events created guestless). + // InviteByCalnode (Calnode's own .ics, with the hosts' events created guestless) or + // InviteByNone (guestless host events and no .ics; the integration sends the invite). // Stored on the booking so its reschedule and cancel follow the mode it was created // with, not whatever the event type is set to by then. InviteDelivery string diff --git a/internal/db/invite_delivery_migration_test.go b/internal/db/invite_delivery_migration_test.go new file mode 100644 index 00000000..aa6c4c7f --- /dev/null +++ b/internal/db/invite_delivery_migration_test.go @@ -0,0 +1,124 @@ +package db_test + +import ( + "database/sql" + "os" + "strings" + "testing" + + "github.com/calnode/calnode/internal/db" + "github.com/pressly/goose/v3" +) + +// migrateTo70WithInviteModes starts from the schema before invite_delivery gained 'none' +// and seeds one event type and one booking per mode that existed then. +func migrateTo70WithInviteModes(t *testing.T) *sql.DB { + t.Helper() + database, err := db.Open("sqlite://:memory:") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { database.Close() }) + goose.SetBaseFS(os.DirFS(".")) + if err := goose.SetDialect("sqlite3"); err != nil { + t.Fatal(err) + } + if err := goose.UpTo(database, "migrations", 70); err != nil { + t.Fatal(err) + } + for _, q := range []string{ + `INSERT INTO users (id,email,name) VALUES ('owner','owner@example.com','Owner')`, + `INSERT INTO event_types (id,user_id,slug,name,duration_minutes,invite_delivery) VALUES ('et-cal','owner','cal','Cal',30,'calendar')`, + `INSERT INTO event_types (id,user_id,slug,name,duration_minutes,invite_delivery) VALUES ('et-cn','owner','cn','Cn',30,'calnode')`, + `INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at,invite_delivery) VALUES ('b-cal','et-cal','owner','2026-11-02T10:00:00Z','2026-11-02T10:30:00Z','calendar')`, + `INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at,invite_delivery) VALUES ('b-cn','et-cn','owner','2026-11-02T11:00:00Z','2026-11-02T11:30:00Z','calnode')`, + `INSERT INTO booking_attendees (id,booking_id,name,email,is_organizer) VALUES ('a-1','b-cn','Guest','guest@example.com',1)`, + } { + if _, err := database.Exec(q); err != nil { + t.Fatalf("seed %q: %v", q, err) + } + } + return database +} + +// The column swap in 00071 must keep every stored mode, leave child rows and the +// double-booking guard alone, and accept 'none' while still rejecting unknown values. +func TestMigrate_inviteDeliveryNoneKeepsExistingModes(t *testing.T) { + database := migrateTo70WithInviteModes(t) + if err := db.Migrate(database); err != nil { + t.Fatal(err) + } + + for table, want := range map[string]map[string]string{ + "event_types": {"et-cal": "calendar", "et-cn": "calnode"}, + "bookings": {"b-cal": "calendar", "b-cn": "calnode"}, + } { + for id, mode := range want { + var got string + if err := database.QueryRow(`SELECT invite_delivery FROM `+table+` WHERE id = ?`, id).Scan(&got); err != nil { + t.Fatalf("%s %s: %v", table, id, err) + } + if got != mode { + t.Errorf("%s %s invite_delivery = %q after migrating; want %q", table, id, got, mode) + } + } + } + var attendees int + if err := database.QueryRow(`SELECT COUNT(*) FROM booking_attendees WHERE booking_id = 'b-cn'`).Scan(&attendees); err != nil || attendees != 1 { + t.Errorf("booking attendees after migrating = %d (%v); want the seeded one kept", attendees, err) + } + + if _, err := database.Exec(`INSERT INTO event_types (id,user_id,slug,name,duration_minutes,invite_delivery) VALUES ('et-none','owner','none','None',30,'none')`); err != nil { + t.Fatalf("event type with invite_delivery 'none': %v", err) + } + if _, err := database.Exec(`INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at,invite_delivery) VALUES ('b-none','et-none','owner','2026-11-02T12:00:00Z','2026-11-02T12:30:00Z','none')`); err != nil { + t.Fatalf("booking with invite_delivery 'none': %v", err) + } + for _, q := range []string{ + `INSERT INTO event_types (id,user_id,slug,name,duration_minutes,invite_delivery) VALUES ('et-bad','owner','bad','Bad',30,'carrier-pigeon')`, + `INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at,invite_delivery) VALUES ('b-bad','et-cal','owner','2026-11-02T13:00:00Z','2026-11-02T13:30:00Z','carrier-pigeon')`, + } { + if _, err := database.Exec(q); err == nil || !strings.Contains(err.Error(), "CHECK") { + t.Errorf("unknown invite_delivery accepted (err=%v); want the CHECK to reject it: %s", err, q) + } + } + var defaulted string + if _, err := database.Exec(`INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at) VALUES ('b-def','et-cal','owner','2026-11-02T14:00:00Z','2026-11-02T14:30:00Z')`); err != nil { + t.Fatal(err) + } + if err := database.QueryRow(`SELECT invite_delivery FROM bookings WHERE id = 'b-def'`).Scan(&defaulted); err != nil || defaulted != "calendar" { + t.Errorf("default invite_delivery = %q (%v); want 'calendar'", defaulted, err) + } + + // The double-booking guard is an index on bookings; a table rebuild could have lost it. + if _, err := database.Exec(`INSERT INTO bookings (id,event_type_id,host_id,start_at,end_at) VALUES ('b-dup','et-cal','owner','2026-11-02T10:00:00Z','2026-11-02T10:30:00Z')`); err == nil { + t.Error("double booking accepted after migrating; idx_bookings_no_double is gone") + } +} + +// Rolling back maps 'none' to 'calnode', which an older binary reads as guestless too. +func TestMigrate_inviteDeliveryNoneDownKeepsEventsGuestless(t *testing.T) { + database := migrateTo70WithInviteModes(t) + if err := goose.UpTo(database, "migrations", 71); err != nil { + t.Fatal(err) + } + if _, err := database.Exec(`UPDATE bookings SET invite_delivery = 'none' WHERE id = 'b-cn'`); err != nil { + t.Fatal(err) + } + if _, err := database.Exec(`UPDATE event_types SET invite_delivery = 'none' WHERE id = 'et-cn'`); err != nil { + t.Fatal(err) + } + if err := goose.DownTo(database, "migrations", 70); err != nil { + t.Fatal(err) + } + var b, et string + if err := database.QueryRow(`SELECT invite_delivery FROM bookings WHERE id = 'b-cn'`).Scan(&b); err != nil { + t.Fatal(err) + } + if err := database.QueryRow(`SELECT invite_delivery FROM event_types WHERE id = 'et-cn'`).Scan(&et); err != nil { + t.Fatal(err) + } + if b != "calnode" || et != "calnode" { + t.Errorf("after down: booking %q, event type %q; want both 'calnode'", b, et) + } +} diff --git a/internal/db/migrations/00071_invite_delivery_none.sql b/internal/db/migrations/00071_invite_delivery_none.sql new file mode 100644 index 00000000..34d4af52 --- /dev/null +++ b/internal/db/migrations/00071_invite_delivery_none.sql @@ -0,0 +1,33 @@ +-- +goose Up +-- A third invite_delivery mode, 'none': the hosts' events are created without guests, +-- exactly as for 'calnode', but Calnode attaches no invite to the booker's emails either. +-- For integrations that deliver the invite themselves (their own confirmation email with +-- their own .ics), where any invite from the provider or from Calnode would be a duplicate. +-- +-- 00068 declared the allowed values as a column CHECK, and SQLite cannot ALTER a CHECK. +-- Rather than rebuild bookings and event_types (00042 rebuilt event_types with +-- NO TRANSACTION + foreign_keys=OFF; bookings has never been rebuilt, see 00037, and +-- carries the double-booking unique index and five child tables' foreign keys), the +-- column is swapped: add a widened copy, fill it, drop the old column, take its name. +-- DROP COLUMN is allowed because nothing else in the schema names invite_delivery (its +-- only CHECK is its own), so this runs in goose's normal transaction with foreign keys +-- on, and neither table's indexes or child rows are touched. The column moves to the end +-- of each table; every query names its columns. +ALTER TABLE event_types ADD COLUMN invite_delivery_new TEXT NOT NULL DEFAULT 'calendar' + CHECK (invite_delivery_new IN ('calendar', 'calnode', 'none')); +UPDATE event_types SET invite_delivery_new = invite_delivery; +ALTER TABLE event_types DROP COLUMN invite_delivery; +ALTER TABLE event_types RENAME COLUMN invite_delivery_new TO invite_delivery; + +ALTER TABLE bookings ADD COLUMN invite_delivery_new TEXT NOT NULL DEFAULT 'calendar' + CHECK (invite_delivery_new IN ('calendar', 'calnode', 'none')); +UPDATE bookings SET invite_delivery_new = invite_delivery; +ALTER TABLE bookings DROP COLUMN invite_delivery; +ALTER TABLE bookings RENAME COLUMN invite_delivery_new TO invite_delivery; + +-- +goose Down +-- The widened CHECK stays (as in 00042). 'none' rows become 'calnode', the mode an older +-- binary understands that also keeps the hosts' events guestless: read as 'calendar', the +-- next reschedule or reconcile would have the host's calendar invite the booker after all. +UPDATE bookings SET invite_delivery = 'calnode' WHERE invite_delivery = 'none'; +UPDATE event_types SET invite_delivery = 'calnode' WHERE invite_delivery = 'none'; diff --git a/internal/handler/booking_handler.go b/internal/handler/booking_handler.go index 351efb69..7496ed29 100644 --- a/internal/handler/booking_handler.go +++ b/internal/handler/booking_handler.go @@ -509,7 +509,7 @@ type bookableEventType struct { // so the page can grey them out. Read by the public slots endpoint only: the MCP // tool and the booking assistant must keep seeing bookable times and nothing else. ShowTakenSlots bool - // InviteDelivery is who sends the booker's invite (booking.InviteByCalendar/ByCalnode), + // InviteDelivery is who sends the booker's invite (booking.InviteByCalendar/ByCalnode/ByNone), // copied onto each booking at creation. InviteDelivery string } @@ -657,6 +657,11 @@ type bookingJSON struct { // ConfirmFailed flags a booking whose initial confirmation email failed after // retry — operator-visible so a lost confirmation can be followed up manually. ConfirmFailed bool `json:"confirm_failed,omitempty"` + // InviteDelivery is who sent this booking's calendar invite, fixed when it was made: + // "calendar" (the host's calendar invited the booker), "calnode" (Calnode's .ics) or + // "none" (nobody; the integration sends its own). Always present, so an integration + // can tell whether the booker already holds an invite. + InviteDelivery string `json:"invite_delivery" jsonschema:"who sent the booker's calendar invite: calendar (the host's calendar), calnode (Calnode's own email), or none (no invite was sent)"` // RSVPStatus is the booker's answer to a Calnode-sent invite ("accepted", "declined", // "tentative"), absent until one arrives. Admin list views only. RSVPStatus string `json:"rsvp_status,omitempty"` @@ -684,6 +689,10 @@ func toBookingJSON(b *booking.Booking) bookingJSON { LocationType: b.LocationType, CreatedAt: b.CreatedAt.UTC().Format(time.RFC3339), UpdatedAt: b.UpdatedAt.UTC().Format(time.RFC3339), + InviteDelivery: b.InviteDelivery, + } + if j.InviteDelivery == "" { + j.InviteDelivery = booking.InviteByCalendar } // Payment fields are omitted for free bookings (payment_status defaults to 'none'). if b.PaymentStatus != "" && b.PaymentStatus != "none" { diff --git a/internal/handler/event_type.go b/internal/handler/event_type.go index 3beae545..52c00955 100644 --- a/internal/handler/event_type.go +++ b/internal/handler/event_type.go @@ -43,8 +43,10 @@ type eventTypeJSON struct { // makes the host's booked hours legible to anyone with the link (#19). ShowTakenSlots bool `json:"show_taken_slots"` // InviteDelivery is who sends the booker's calendar invite: "calendar" (each host's - // connected calendar, from the host's own address) or "calnode" (Calnode's own .ics, - // from the instance sender, so no host address reaches the booker). See migration 00068. + // 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: + // 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"` @@ -312,7 +314,7 @@ func (h *Handler) CreateEventType(w http.ResponseWriter, r *http.Request) { if req.InviteDelivery != nil { mode, ok := normalizeInviteDelivery(*req.InviteDelivery) if !ok { - h.writeError(w, http.StatusBadRequest, "invite_delivery must be 'calendar' or 'calnode'") + h.writeError(w, http.StatusBadRequest, "invite_delivery must be 'calendar', 'calnode' or 'none'") return } if mode == booking.InviteByCalnode && !h.inviteSenderReady(r.Context()) { @@ -638,7 +640,7 @@ func (h *Handler) PatchEventType(w http.ResponseWriter, r *http.Request) { if req.InviteDelivery != nil { mode, ok := normalizeInviteDelivery(*req.InviteDelivery) if !ok { - h.writeError(w, http.StatusBadRequest, "invite_delivery must be 'calendar' or 'calnode'") + h.writeError(w, http.StatusBadRequest, "invite_delivery must be 'calendar', 'calnode' or 'none'") return } newInviteDelivery = mode diff --git a/internal/handler/invite_delivery.go b/internal/handler/invite_delivery.go index 81164fd0..ec0d4b78 100644 --- a/internal/handler/invite_delivery.go +++ b/internal/handler/invite_delivery.go @@ -8,7 +8,7 @@ import ( "github.com/calnode/calnode/internal/mailer" ) -// Invite delivery decides who sends the booker's calendar invite (migration 00068): +// Invite delivery decides who sends the booker's calendar invite (migrations 00068, 00071): // // - booking.InviteByCalendar: each host's connected calendar invites the booker, so // Google/Microsoft email the invite from that host's own account. The default. @@ -17,6 +17,13 @@ import ( // Calnode sends the invite itself on the confirmation email, organized by the // instance's sender identity (Settings → Email). No host's address reaches the booker, // and a team books under one name. +// - booking.InviteByNone: the hosts' events are written guestless as for InviteByCalnode, +// and Calnode attaches no invite to the booker's emails either. For integrations that +// send their own invite (typically their own confirmation with their own .ics), where +// anything from the provider or from Calnode would be a duplicate. Needs no email +// setup: the booker's emails still go out when email is configured, just without an +// invite, so whether Calnode emails at all stays the mailer's and the notification +// settings' decision, not this one's. // // The mode is copied onto the booking when it is created (booking.Booking.InviteDelivery) // and read from there afterwards, so a booking's reschedule and cancel follow the channel @@ -33,17 +40,26 @@ func normalizeInviteDelivery(v string) (string, bool) { return booking.InviteByCalendar, true case booking.InviteByCalnode: return booking.InviteByCalnode, true + case booking.InviteByNone: + return booking.InviteByNone, true } return "", false } +// hostEventsGuestless reports whether a mode keeps the booker off the hosts' calendar +// events, so their providers email nobody: every mode except calendar-sent. An empty mode +// is the default, InviteByCalendar. +func hostEventsGuestless(mode string) bool { + return mode == booking.InviteByCalnode || mode == booking.InviteByNone +} + // calendarInvitee is the address passed as CreateEventParams.OrganizerEmail for a host's // calendar event: the booker when the hosts' calendars send the invite, "" when Calnode -// does. Google and Microsoft add that address as the event's attendee, so "" leaves them +// does or nobody does. Google and Microsoft add that address as the event's attendee, so "" leaves them // no one to email and the event private to the host. CalDAV never sends invites; there it // only decides whether the stored event names the booker at all. func calendarInvitee(mode, bookerEmail string) string { - if mode == booking.InviteByCalnode { + if hostEventsGuestless(mode) { return "" } return bookerEmail @@ -74,7 +90,12 @@ func (h *Handler) inviteSenderReady(ctx context.Context) bool { // Calnode-sent: always attach, organized by the booking's fixed invite organizer, never // the host. Calendar-sent: attach only when the primary host's calendar will not invite // the booker itself (noConnectedDestination), with the host as organizer, exactly as before. +// None: never attach, whatever the host's calendar; the invite is someone else's to send. func (h *Handler) applyInviteDelivery(ctx context.Context, d *mailer.BookingData, mode, primaryHostID string) { + if mode == booking.InviteByNone { + d.AttachICS = false + return + } if mode == booking.InviteByCalnode { d.AttachICS = true d.HideHostInInvite = true @@ -85,11 +106,12 @@ func (h *Handler) applyInviteDelivery(ctx context.Context, d *mailer.BookingData } // applyHostInvite turns booking email data into one host's own copy: organized by that -// host, attached only when their calendar does not already hold the event, and - for a -// Calnode-invited booking - without the booker as a guest (see ICSWithoutAttendee). +// host, attached only when their calendar does not already hold the event, and - when the +// hosts' events are guestless (Calnode-sent or no invite) - without the booker as a guest +// (see ICSWithoutAttendee). func (h *Handler) applyHostInvite(ctx context.Context, d *mailer.BookingData, mode, hostID string) { d.HideHostInInvite = false - d.ICSWithoutAttendee = mode == booking.InviteByCalnode + d.ICSWithoutAttendee = hostEventsGuestless(mode) d.AttachICS = h.noConnectedDestination(ctx, hostID) } diff --git a/internal/handler/invite_delivery_internal_test.go b/internal/handler/invite_delivery_internal_test.go index f5ecc4e8..383c7e55 100644 --- a/internal/handler/invite_delivery_internal_test.go +++ b/internal/handler/invite_delivery_internal_test.go @@ -339,7 +339,14 @@ func assertWorkspaceInvite(t *testing.T, what, ics, method string, hostAddrs ... func (f *inviteFixture) calnodeBooking(t *testing.T) (*booking.Booking, string) { t.Helper() - if rec := f.createEventType(t, "intro", booking.InviteByCalnode); rec.Code != http.StatusCreated { + return f.modeBooking(t, booking.InviteByCalnode) +} + +// modeBooking books an event type created with the given invite mode and checks the mode +// was copied onto the booking. +func (f *inviteFixture) modeBooking(t *testing.T, mode string) (*booking.Booking, string) { + t.Helper() + if rec := f.createEventType(t, "intro", mode); rec.Code != http.StatusCreated { t.Fatalf("create event type: %d — %s", rec.Code, rec.Body.String()) } id, _ := f.book(t, "intro") @@ -347,8 +354,8 @@ func (f *inviteFixture) calnodeBooking(t *testing.T) (*booking.Booking, string) if err != nil { t.Fatalf("get booking: %v", err) } - if b.InviteDelivery != booking.InviteByCalnode { - t.Fatalf("booking invite_delivery = %q; want calnode copied from the event type", b.InviteDelivery) + if b.InviteDelivery != mode { + t.Fatalf("booking invite_delivery = %q; want %s copied from the event type", b.InviteDelivery, mode) } return b, b.EventTypeID } @@ -407,25 +414,175 @@ func TestInviteDelivery_reassignKeepsBothHostsPrivate(t *testing.T) { } // The reconciler re-creates a host event whose inline create failed; for a Calnode -// booking it must not add the booker, or the provider would invite them after all. +// booking, or one with no invite, it must not add the booker, or the provider would +// invite them after all. func TestInviteDelivery_reconcilerHealsWithoutInvitingBooker(t *testing.T) { - f := newInviteFixture(t, true) - b, _ := f.calnodeBooking(t) + for _, mode := range []string{booking.InviteByCalnode, booking.InviteByNone} { + t.Run(mode, func(t *testing.T) { + f := newInviteFixture(t, true) + b, _ := f.modeBooking(t, mode) + + if _, err := f.h.db.Exec(`UPDATE booking_hosts SET external_event_id = NULL WHERE booking_id = ?`, b.ID); err != nil { + t.Fatal(err) + } + if _, err := f.h.db.Exec(`UPDATE bookings SET created_at = ? WHERE id = ?`, + time.Now().UTC().Add(-time.Hour).Format(time.RFC3339), b.ID); err != nil { + t.Fatal(err) + } + f.h.reconcileCreations(context.Background(), f.h.getCal()) + + events := f.cal.events() + if len(events) != 2 { + t.Fatalf("host calendar events = %d; want the missing one re-created", len(events)) + } + if events[1].OrganizerEmail != "" { + t.Errorf("healed event invites %q; want no guest", events[1].OrganizerEmail) + } + }) + } +} - if _, err := f.h.db.Exec(`UPDATE booking_hosts SET external_event_id = NULL WHERE booking_id = ?`, b.ID); err != nil { +// No invite at all is for integrations that send their own. It is not an email feature, +// so unlike Calnode-sent invites it needs neither a sender nor a working mailer. +func TestInviteDelivery_noneNeedsNoEmail(t *testing.T) { + f := newInviteFixture(t, false) + f.h.SetMailer(&mailer.Noop{}, "https://book.team.example") + + if rec := f.createEventType(t, "intro", booking.InviteByNone); rec.Code != http.StatusCreated { + t.Fatalf("create with no invite and no email: %d — %s; want 201", rec.Code, rec.Body.String()) + } + if rec := f.createEventType(t, "other", booking.InviteByCalendar); rec.Code != http.StatusCreated { + t.Fatalf("create event type: %d — %s", rec.Code, rec.Body.String()) + } + if rec := f.do(t, f.h.PatchEventType, http.MethodPatch, "/v1/event-types/other", + `{"invite_delivery":"none"}`); rec.Code != http.StatusOK { + t.Fatalf("switch to no invite with no email: %d — %s; want 200", rec.Code, rec.Body.String()) + } + var stored string + if err := f.h.db.QueryRow(`SELECT invite_delivery FROM event_types WHERE slug = 'other'`).Scan(&stored); err != nil { t.Fatal(err) } - if _, err := f.h.db.Exec(`UPDATE bookings SET created_at = ? WHERE id = ?`, - time.Now().UTC().Add(-time.Hour).Format(time.RFC3339), b.ID); err != nil { + if stored != booking.InviteByNone { + t.Errorf("stored invite_delivery = %q after the switch; want none", stored) + } + // The sender requirement still holds for Calnode-sent invites. + if rec := f.do(t, f.h.PatchEventType, http.MethodPatch, "/v1/event-types/other", + `{"invite_delivery":"calnode"}`); rec.Code != http.StatusBadRequest { + t.Errorf("switch to calnode invites with no email: %d; want 400", rec.Code) + } +} + +// With no invite, the host's calendar holds the meeting but invites nobody, and nothing +// Calnode sends carries an invite. The booker's confirmation itself still goes out when +// email is set up: the mode decides the invite, not whether Calnode emails. +func TestInviteDelivery_noneSendsNoInvite(t *testing.T) { + f := newInviteFixture(t, false) + f.modeBooking(t, booking.InviteByNone) + + events := f.cal.events() + if len(events) != 1 { + t.Fatalf("host calendar events: got %d; want 1 (the host still needs the meeting on their calendar)", len(events)) + } + if events[0].OrganizerEmail != "" { + t.Errorf("host event invites %q; want no guest, so the provider emails nobody", events[0].OrganizerEmail) + } + if ics := icsOf(f.waitFor(t, inviteBookerEmail, 1)); ics != "" { + t.Errorf("booker confirmation carries an .ics; the integration sends the invite:\n%s", ics) + } + if ics := icsOf(f.waitFor(t, inviteHostEmail, 1)); strings.Contains(ics, inviteBookerEmail) { + t.Errorf("host copy names the booker as a guest:\n%s", ics) + } +} + +// Reschedule and cancel follow the booking's mode, not the event type's or the host's +// calendar. With the event type switched back and the host's calendar disconnected, a +// calendar-sent booking would now get Calnode's .ics; one with no invite still must not. +func TestInviteDelivery_noneRescheduleAndCancelSendNoInvite(t *testing.T) { + f := newInviteFixture(t, false) + b, etID := f.modeBooking(t, booking.InviteByNone) + + if rec := f.do(t, f.h.PatchEventType, http.MethodPatch, "/v1/event-types/intro", + `{"invite_delivery":"calendar"}`); rec.Code != http.StatusOK { + t.Fatalf("switch back to calendar: %d — %s", rec.Code, rec.Body.String()) + } + if _, err := f.h.db.Exec(`DELETE FROM calendar_connections`); err != nil { t.Fatal(err) } - f.h.reconcileCreations(context.Background(), f.h.getCal()) + ctx := context.Background() + newStart := b.StartAt.Add(24 * time.Hour) + updated, err := f.h.bookingSvc.Reschedule(ctx, b.ID, newStart, newStart.Add(30*time.Minute)) + if err != nil { + t.Fatalf("reschedule: %v", err) + } + f.h.rescheduleSideEffects(*updated, etID, b.StartAt, b.EndAt) + if ics := icsOf(f.waitFor(t, inviteBookerEmail, 2)); ics != "" { + t.Errorf("reschedule email carries an .ics:\n%s", ics) + } + + if err := f.h.bookingSvc.CancelByID(ctx, b.ID, "changed plans"); err != nil { + t.Fatalf("cancel: %v", err) + } + cancelled, err := f.h.bookingSvc.Get(ctx, b.ID) + if err != nil { + t.Fatalf("get booking: %v", err) + } + f.h.cancelSideEffects(*cancelled) + if ics := icsOf(f.waitFor(t, inviteBookerEmail, 3)); ics != "" { + t.Errorf("cancellation email carries an .ics:\n%s", ics) + } +} + +// Reassigning a booking with no invite moves the event to the new host's calendar +// without the booker, and the booker's notice of the change carries no invite. +func TestInviteDelivery_noneReassignInvitesNobody(t *testing.T) { + f := newInviteFixture(t, false) + b, _ := f.modeBooking(t, booking.InviteByNone) + + if _, err := f.h.db.Exec(`INSERT INTO users (id, email, name, iana_timezone, is_admin, created_at) + VALUES ('host-2', 'colleague@host.example', 'Colleague', 'UTC', 0, '2026-01-01T00:00:00Z')`); err != nil { + t.Fatalf("seed second host: %v", err) + } + if _, err := f.h.db.Exec(`INSERT INTO calendar_connections + (id, user_id, provider, access_token_enc, calendar_id, check_conflicts, is_destination, created_at) + VALUES ('conn-2', 'host-2', 'google', 'e', 'primary', 1, 1, '2026-01-01T00:00:00Z')`); err != nil { + t.Fatalf("seed second host calendar: %v", err) + } + req := httptest.NewRequest(http.MethodPost, "/v1/bookings/"+b.ID+"/reassign", strings.NewReader(`{"host_id":"host-2"}`)) + req.SetPathValue("id", b.ID) + req.Header.Set("X-API-Key", f.apiKey) + rec := httptest.NewRecorder() + f.h.RequireAuth(f.h.ReassignBooking)(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("reassign: %d — %s", rec.Code, rec.Body.String()) + } + + if ics := icsOf(f.waitFor(t, inviteBookerEmail, 2)); ics != "" { + t.Errorf("reassign email carries an .ics:\n%s", ics) + } events := f.cal.events() - if len(events) != 2 { - t.Fatalf("host calendar events = %d; want the missing one re-created", len(events)) + if len(events) != 2 || events[1].OrganizerEmail != "" { + t.Errorf("new host's calendar events = %+v; want the moved event created without the booker", events) } - if events[1].OrganizerEmail != "" { - t.Errorf("healed event invites %q; want no guest", events[1].OrganizerEmail) +} + +// Integrations read the mode per booking, so they can tell whether the booker already +// holds an invite: on the single booking and on the workspace list. +func TestInviteDelivery_bookingJSONReportsMode(t *testing.T) { + f := newInviteFixture(t, false) + b, _ := f.modeBooking(t, booking.InviteByNone) + const want = `"invite_delivery":"none"` + + req := httptest.NewRequest(http.MethodGet, "/v1/bookings/"+b.ID, nil) + req.SetPathValue("id", b.ID) + rec := httptest.NewRecorder() + f.h.GetBooking(rec, req) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), want) { + t.Errorf("GET booking: %d — %s; want it to contain %s", rec.Code, rec.Body.String(), want) + } + + if rec := f.do(t, f.h.ListBookings, http.MethodGet, "/v1/bookings?scope=all", ""); rec.Code != http.StatusOK || + !strings.Contains(rec.Body.String(), want) { + t.Errorf("list bookings: %d — %s; want it to contain %s", rec.Code, rec.Body.String(), want) } } diff --git a/internal/handler/reassign.go b/internal/handler/reassign.go index e3788447..484f9893 100644 --- a/internal/handler/reassign.go +++ b/internal/handler/reassign.go @@ -204,10 +204,14 @@ func (h *Handler) ReassignBooking(w http.ResponseWriter, r *http.Request) { } // A Calnode-sent invite is re-issued (same UID, newer SEQUENCE) so the booker's // calendar entry follows the change. A calendar-sent one needs nothing here: the - // new host's calendar invited the booker when the event was recreated above. - if inviteMode == booking.InviteByCalnode { + // new host's calendar invited the booker when the event was recreated above, and a + // booking with no invite gets none now either (applyInviteDelivery says so). + switch inviteMode { + case booking.InviteByCalnode: h.applyInviteDelivery(ctx, &d, inviteMode, newHostID) d.ICSSequence = int(time.Now().Unix()) + case booking.InviteByNone: + h.applyInviteDelivery(ctx, &d, inviteMode, newHostID) } prefs := h.hostPrefsOrDefault(ctx, bCopy.ID, newHostID) if prefs.NotifyConfirmation { diff --git a/internal/webhook/payload_test.go b/internal/webhook/payload_test.go index 3062cfa3..30a23dc0 100644 --- a/internal/webhook/payload_test.go +++ b/internal/webhook/payload_test.go @@ -72,3 +72,18 @@ func TestValidFields_dropsUnknown(t *testing.T) { t.Errorf("ValidFields = %v; want [id attendee_email]", got) } } + +// invite_delivery is opt-in: selected, it carries the booking's mode; in the default set +// it would change every unconfigured webhook's payload, so it is not there. +func TestBuildData_inviteDeliveryIsOptIn(t *testing.T) { + bd := enrichedBooking{core: BookingPayload{ID: "b1"}, inviteDelivery: "none"} + if _, ok := buildData(bd, defaultFields)[FieldInviteDelivery]; ok { + t.Error("default payload must not include invite_delivery (backwards-compat)") + } + if got := buildData(bd, []string{FieldInviteDelivery})[FieldInviteDelivery]; got != "none" { + t.Errorf("invite_delivery = %v; want \"none\"", got) + } + if got := ValidFields([]string{FieldInviteDelivery}); len(got) != 1 { + t.Errorf("invite_delivery is not a selectable field: %v", got) + } +} diff --git a/internal/webhook/webhook.go b/internal/webhook/webhook.go index 0e0948ab..2b90d433 100644 --- a/internal/webhook/webhook.go +++ b/internal/webhook/webhook.go @@ -56,6 +56,7 @@ const ( FieldAmountPaid = "amount_paid_cents" FieldCurrency = "amount_paid_currency" FieldRSVPStatus = "rsvp_status" + FieldInviteDelivery = "invite_delivery" ) // AllFields is every selectable field, in payload order. Used to validate config @@ -67,11 +68,14 @@ var AllFields = []string{ FieldHostID, FieldHostName, FieldHostEmail, FieldAttendeeName, FieldAttendeeEmail, FieldAttendeeTZ, FieldAnswers, FieldPaymentStatus, FieldAmountPaid, FieldCurrency, FieldRSVPStatus, + FieldInviteDelivery, } // defaultFields reproduces the original payload (no PII, no answers) so a webhook with no // field config (fields IS NULL) keeps its historical shape. Payment fields are included but // omitempty, so free bookings are byte-identical to before; only paid bookings gain them. +// FieldInviteDelivery is opt-in for the same reason: every booking has a value, so adding +// it here would change the payload of every unconfigured webhook. var defaultFields = []string{ FieldID, FieldEventTypeSlug, FieldHostID, FieldStartAt, FieldEndAt, FieldStatus, FieldLocation, FieldCancelReason, FieldCreatedAt, @@ -282,10 +286,13 @@ type enrichedBooking struct { hostName, hostEmail string attendeeName, attendeeEmail, attendeeTZ string answers []map[string]string + // inviteDelivery is who sent the booker's invite (calendar, calnode or none), read + // from the booking row so every event carries it without each caller passing it. + inviteDelivery string } // enrich loads the data not carried in BookingPayload (host name/email, event-type -// name, attendee identity, intake answers) from the booking row. Best-effort: any +// name, attendee identity, intake answers, invite delivery) from the booking row. Best-effort: any // query failure simply leaves those fields empty. Queries are drained sequentially, // safe on the single-connection pool, and run before Enqueue opens its tx. func (s *Service) enrich(ctx context.Context, p BookingPayload) enrichedBooking { @@ -294,11 +301,11 @@ func (s *Service) enrich(ctx context.Context, p BookingPayload) enrichedBooking return bd } _ = s.db.QueryRowContext(ctx, ` - SELECT COALESCE(et.name,''), COALESCE(u.name,''), COALESCE(u.email,'') + SELECT COALESCE(et.name,''), COALESCE(u.name,''), COALESCE(u.email,''), b.invite_delivery FROM bookings b JOIN event_types et ON et.id = b.event_type_id JOIN users u ON u.id = b.host_id - WHERE b.id = ?`, p.ID).Scan(&bd.eventTypeName, &bd.hostName, &bd.hostEmail) + WHERE b.id = ?`, p.ID).Scan(&bd.eventTypeName, &bd.hostName, &bd.hostEmail, &bd.inviteDelivery) _ = s.db.QueryRowContext(ctx, ` SELECT COALESCE(name,''), COALESCE(email,''), COALESCE(iana_timezone,'') @@ -351,6 +358,7 @@ func buildData(bd enrichedBooking, fields []string) map[string]any { FieldPaymentStatus: bd.core.PaymentStatus, FieldCurrency: bd.core.AmountPaidCurrency, FieldRSVPStatus: bd.core.RSVPStatus, + FieldInviteDelivery: bd.inviteDelivery, } out := make(map[string]any, len(fields)) for _, f := range fields {